From f871be4d71d8a95b0bf537fb3a4cee9633fccada Mon Sep 17 00:00:00 2001 From: wangshi Date: Fri, 7 Mar 2025 10:02:59 +0800 Subject: [PATCH 1/4] add typescript schema Signed-off-by: wangshi --- .../src/main/java/antlr/TypeScriptLexer.g4 | 315 ++++++ .../src/main/java/antlr/TypeScriptParser.g4 | 984 ++++++++++++++++++ 2 files changed, 1299 insertions(+) create mode 100644 src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptLexer.g4 create mode 100644 src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptParser.g4 diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptLexer.g4 b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptLexer.g4 new file mode 100644 index 00000000..b15a8d41 --- /dev/null +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptLexer.g4 @@ -0,0 +1,315 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) + * Copyright (c) 2017 by Ivan Kochurkin (Positive Technologies): + added ECMAScript 6 support, cleared and transformed to the universal grammar. + * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) + * Copyright (c) 2019 by Andrii Artiushok (contributor -> added TypeScript support) + * Copyright (c) 2024 by Andrew Leppard (www.wegrok.review) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +// $antlr-format alignTrailingComments true, columnLimit 150, maxEmptyLinesToKeep 1, reflowComments false, useTab false +// $antlr-format allowShortRulesOnASingleLine true, allowShortBlocksOnASingleLine true, minEmptyLines 0, alignSemicolons ownLine +// $antlr-format alignColons trailing, singleLineOverrulesHangingColon true, alignLexerCommands true, alignLabels true, alignTrailers true + +lexer grammar TypeScriptLexer; + +channels { + ERROR +} + +options { + superClass = TypeScriptLexerBase; +} + +MultiLineComment : '/*' .*? '*/' -> channel(HIDDEN); +SingleLineComment : '//' ~[\r\n\u2028\u2029]* -> channel(HIDDEN); +RegularExpressionLiteral: + '/' RegularExpressionFirstChar RegularExpressionChar* {this.IsRegexPossible()}? '/' IdentifierPart* +; + +OpenBracket : '['; +CloseBracket : ']'; +OpenParen : '('; +CloseParen : ')'; +OpenBrace : '{' {this.ProcessOpenBrace();}; +TemplateCloseBrace : {this.IsInTemplateString()}? '}' -> popMode; +CloseBrace : '}' {this.ProcessCloseBrace();}; +SemiColon : ';'; +Comma : ','; +Assign : '='; +QuestionMark : '?'; +QuestionMarkDot : '?.'; +Colon : ':'; +Ellipsis : '...'; +Dot : '.'; +PlusPlus : '++'; +MinusMinus : '--'; +Plus : '+'; +Minus : '-'; +BitNot : '~'; +Not : '!'; +Multiply : '*'; +Divide : '/'; +Modulus : '%'; +Power : '**'; +NullCoalesce : '??'; +Hashtag : '#'; +LeftShiftArithmetic : '<<'; +// We can't match these in the lexer because it would cause issues when parsing +// types like Map> +// RightShiftArithmetic : '>>'; +// RightShiftLogical : '>>>'; +LessThan : '<'; +MoreThan : '>'; +LessThanEquals : '<='; +GreaterThanEquals : '>='; +Equals_ : '=='; +NotEquals : '!='; +IdentityEquals : '==='; +IdentityNotEquals : '!=='; +BitAnd : '&'; +BitXOr : '^'; +BitOr : '|'; +And : '&&'; +Or : '||'; +MultiplyAssign : '*='; +DivideAssign : '/='; +ModulusAssign : '%='; +PlusAssign : '+='; +MinusAssign : '-='; +LeftShiftArithmeticAssign : '<<='; +RightShiftArithmeticAssign : '>>='; +RightShiftLogicalAssign : '>>>='; +BitAndAssign : '&='; +BitXorAssign : '^='; +BitOrAssign : '|='; +PowerAssign : '**='; +NullishCoalescingAssign : '??='; +ARROW : '=>'; + +/// Null Literals + +NullLiteral: 'null'; + +/// Boolean Literals + +BooleanLiteral: 'true' | 'false'; + +/// Numeric Literals + +DecimalLiteral: + DecimalIntegerLiteral '.' [0-9] [0-9_]* ExponentPart? + | '.' [0-9] [0-9_]* ExponentPart? + | DecimalIntegerLiteral ExponentPart? +; + +/// Numeric Literals + +HexIntegerLiteral : '0' [xX] [0-9a-fA-F] HexDigit*; +OctalIntegerLiteral : '0' [0-7]+ {!this.IsStrictMode()}?; +OctalIntegerLiteral2 : '0' [oO] [0-7] [_0-7]*; +BinaryIntegerLiteral : '0' [bB] [01] [_01]*; + +BigHexIntegerLiteral : '0' [xX] [0-9a-fA-F] HexDigit* 'n'; +BigOctalIntegerLiteral : '0' [oO] [0-7] [_0-7]* 'n'; +BigBinaryIntegerLiteral : '0' [bB] [01] [_01]* 'n'; +BigDecimalIntegerLiteral : DecimalIntegerLiteral 'n'; + +/// Keywords + +Break : 'break'; +Do : 'do'; +Instanceof : 'instanceof'; +Typeof : 'typeof'; +Case : 'case'; +Else : 'else'; +New : 'new'; +Var : 'var'; +Catch : 'catch'; +Finally : 'finally'; +Return : 'return'; +Void : 'void'; +Continue : 'continue'; +For : 'for'; +Switch : 'switch'; +While : 'while'; +Debugger : 'debugger'; +Function_ : 'function'; +This : 'this'; +With : 'with'; +Default : 'default'; +If : 'if'; +Throw : 'throw'; +Delete : 'delete'; +In : 'in'; +Try : 'try'; +As : 'as'; +From : 'from'; +ReadOnly : 'readonly'; +Async : 'async'; +Await : 'await'; +Yield : 'yield'; +YieldStar : 'yield*'; + +/// Future Reserved Words + +Class : 'class'; +Enum : 'enum'; +Extends : 'extends'; +Super : 'super'; +Const : 'const'; +Export : 'export'; +Import : 'import'; + +/// The following tokens are also considered to be FutureReservedWords +/// when parsing strict mode + +Implements : 'implements'; +Let : 'let'; +Private : 'private'; +Public : 'public'; +Interface : 'interface'; +Package : 'package'; +Protected : 'protected'; +Static : 'static'; + +//keywords: +Any : 'any'; +Number : 'number'; +Never : 'never'; +Boolean : 'boolean'; +String : 'string'; +Unique : 'unique'; +Symbol : 'symbol'; +Undefined : 'undefined'; +Object : 'object'; + +Of : 'of'; +KeyOf : 'keyof'; + +TypeAlias: 'type'; + +Constructor : 'constructor'; +Namespace : 'namespace'; +Require : 'require'; +Module : 'module'; +Declare : 'declare'; + +Abstract: 'abstract'; + +Is: 'is'; + +// +// Ext.2 Additions to 1.8: Decorators +// +At: '@'; + +/// Identifier Names and Identifiers + +Identifier: IdentifierStart IdentifierPart*; + +/// String Literals +StringLiteral: + ('"' DoubleStringCharacter* '"' | '\'' SingleStringCharacter* '\'') {this.ProcessStringLiteral();} +; + +BackTick: '`' {this.IncreaseTemplateDepth();} -> pushMode(TEMPLATE); + +WhiteSpaces: [\t\u000B\u000C\u0020\u00A0]+ -> channel(HIDDEN); + +LineTerminator: [\r\n\u2028\u2029] -> channel(HIDDEN); + +/// Comments + +HtmlComment : '' -> channel(HIDDEN); +CDataComment : '' -> channel(HIDDEN); +UnexpectedCharacter : . -> channel(ERROR); + +mode TEMPLATE; + +TemplateStringEscapeAtom : '\\' .; +BackTickInside : '`' {this.DecreaseTemplateDepth();} -> type(BackTick), popMode; +TemplateStringStartExpression : '${' {this.StartTemplateString();} -> pushMode(DEFAULT_MODE); +TemplateStringAtom : ~[`\\]; + +// Fragment rules + +fragment DoubleStringCharacter: ~["\\\r\n] | '\\' EscapeSequence | LineContinuation; + +fragment SingleStringCharacter: ~['\\\r\n] | '\\' EscapeSequence | LineContinuation; + +fragment EscapeSequence: + CharacterEscapeSequence + | '0' // no digit ahead! TODO + | HexEscapeSequence + | UnicodeEscapeSequence + | ExtendedUnicodeEscapeSequence +; + +fragment CharacterEscapeSequence: SingleEscapeCharacter | NonEscapeCharacter; + +fragment HexEscapeSequence: 'x' HexDigit HexDigit; + +fragment UnicodeEscapeSequence: + 'u' HexDigit HexDigit HexDigit HexDigit + | 'u' '{' HexDigit HexDigit+ '}' +; + +fragment ExtendedUnicodeEscapeSequence: 'u' '{' HexDigit+ '}'; + +fragment SingleEscapeCharacter: ['"\\bfnrtv]; + +fragment NonEscapeCharacter: ~['"\\bfnrtv0-9xu\r\n]; + +fragment EscapeCharacter: SingleEscapeCharacter | [0-9] | [xu]; + +fragment LineContinuation: '\\' [\r\n\u2028\u2029]+; + +fragment HexDigit: [_0-9a-fA-F]; + +fragment DecimalIntegerLiteral: '0' | [1-9] [0-9_]*; + +fragment ExponentPart: [eE] [+-]? [0-9_]+; + +fragment IdentifierPart: IdentifierStart | [\p{Mn}] | [\p{Nd}] | [\p{Pc}] | '\u200C' | '\u200D'; + +fragment IdentifierStart: [\p{L}] | [$_] | '\\' UnicodeEscapeSequence; + +fragment RegularExpressionFirstChar: + ~[*\r\n\u2028\u2029\\/[] + | RegularExpressionBackslashSequence + | '[' RegularExpressionClassChar* ']' +; + +fragment RegularExpressionChar: + ~[\r\n\u2028\u2029\\/[] + | RegularExpressionBackslashSequence + | '[' RegularExpressionClassChar* ']' +; + +fragment RegularExpressionClassChar: ~[\r\n\u2028\u2029\]\\] | RegularExpressionBackslashSequence; + +fragment RegularExpressionBackslashSequence: '\\' ~[\r\n\u2028\u2029]; \ No newline at end of file diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptParser.g4 b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptParser.g4 new file mode 100644 index 00000000..4331162f --- /dev/null +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptParser.g4 @@ -0,0 +1,984 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014 by Bart Kiers (original author) and Alexandre Vitorelli (contributor -> ported to CSharp) + * Copyright (c) 2017 by Ivan Kochurkin (Positive Technologies): + added ECMAScript 6 support, cleared and transformed to the universal grammar. + * Copyright (c) 2018 by Juan Alvarez (contributor -> ported to Go) + * Copyright (c) 2019 by Andrii Artiushok (contributor -> added TypeScript support) + * Copyright (c) 2024 by Andrew Leppard (www.wegrok.review) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +// $antlr-format alignTrailingComments true, columnLimit 150, minEmptyLines 1, maxEmptyLinesToKeep 1, reflowComments false, useTab false +// $antlr-format allowShortRulesOnASingleLine false, allowShortBlocksOnASingleLine true, alignSemicolons hanging, alignColons hanging + +parser grammar TypeScriptParser; + +options { + tokenVocab = TypeScriptLexer; + superClass = TypeScriptParserBase; +} + +// SupportSyntax + +initializer + : '=' singleExpression + ; + +bindingPattern + : (arrayLiteral | objectLiteral) + ; + +// TypeScript SPart +// A.1 Types +typeParameters + : '<' typeParameterList? '>' + ; + +typeParameterList + : typeParameter (',' typeParameter)* + ; + +typeParameter + : identifier constraint? + | identifier '=' typeArgument + | typeParameters + ; + +constraint + : 'extends' type_ + ; + +typeArguments + : '<' typeArgumentList? '>' + ; + +typeArgumentList + : typeArgument (',' typeArgument)* + ; + +typeArgument + : type_ + ; + +// Union and intersection types can have a leading '|' or '&' +// See https://github.com/microsoft/TypeScript/pull/12386 +type_ + : ('|' | '&')? unionOrIntersectionOrPrimaryType + | functionType + | constructorType + | typeGeneric + ; + +unionOrIntersectionOrPrimaryType + : unionOrIntersectionOrPrimaryType '|' unionOrIntersectionOrPrimaryType # Union + | unionOrIntersectionOrPrimaryType '&' unionOrIntersectionOrPrimaryType # Intersection + | primaryType # Primary + ; + +primaryType + : '(' type_ ')' # ParenthesizedPrimType + | predefinedType # PredefinedPrimType + | typeReference # ReferencePrimType + | objectType # ObjectPrimType + | primaryType {this.notLineTerminator()}? '[' primaryType? ']' # ArrayPrimType + | '[' tupleElementTypes ']' # TuplePrimType + | typeQuery # QueryPrimType + | This # ThisPrimType + | typeReference Is primaryType # RedefinitionOfType + | KeyOf primaryType # KeyOfType + ; + +predefinedType + : Any + | NullLiteral + | Number + | DecimalLiteral + | Boolean + | BooleanLiteral + | String + | StringLiteral + | Unique? Symbol + | Never + | Undefined + | Object + | Void + ; + +typeReference + : typeName typeGeneric? + ; + +typeGeneric + : '<' typeArgumentList typeGeneric?'>' + ; + +typeName + : identifier + | namespaceName + ; + +objectType + : '{' typeBody? '}' + ; + +typeBody + : typeMemberList (SemiColon | ',')? + ; + +typeMemberList + : typeMember ((SemiColon | ',') typeMember)* + ; + +typeMember + : propertySignatur + | callSignature + | constructSignature + | indexSignature + | methodSignature ('=>' type_)? + ; + +arrayType + : primaryType {this.notLineTerminator()}? '[' ']' + ; + +tupleType + : '[' tupleElementTypes ']' + ; + +// Tuples can have a trailing comma. See https://github.com/Microsoft/TypeScript/issues/28893 +tupleElementTypes + : type_ (',' type_)* ','? + ; + +functionType + : typeParameters? '(' parameterList? ')' '=>' type_ + ; + +constructorType + : 'new' typeParameters? '(' parameterList? ')' '=>' type_ + ; + +typeQuery + : 'typeof' typeQueryExpression + ; + +typeQueryExpression + : identifier + | (identifierName '.')+ identifierName + ; + +propertySignatur + : ReadOnly? propertyName '?'? typeAnnotation? ('=>' type_)? + ; + +typeAnnotation + : ':' type_ + ; + +callSignature + : typeParameters? '(' parameterList? ')' typeAnnotation? + ; + +// Function parameter list can have a trailing comma. +// See https://github.com/Microsoft/TypeScript/issues/16152 +parameterList + : restParameter + | parameter (',' parameter)* (',' restParameter)? ','? + ; + +requiredParameterList + : requiredParameter (',' requiredParameter)* + ; + +parameter + : requiredParameter + | optionalParameter + ; + +optionalParameter + : decoratorList? ( + accessibilityModifier? identifierOrPattern ( + '?' typeAnnotation? + | typeAnnotation? initializer + ) + ) + ; + +restParameter + : '...' singleExpression typeAnnotation? + ; + +requiredParameter + : decoratorList? accessibilityModifier? identifierOrPattern typeAnnotation? + ; + +accessibilityModifier + : Public + | Private + | Protected + ; + +identifierOrPattern + : identifierName + | bindingPattern + ; + +constructSignature + : 'new' typeParameters? '(' parameterList? ')' typeAnnotation? + ; + +indexSignature + : '[' identifier ':' (Number | String) ']' typeAnnotation + ; + +methodSignature + : propertyName '?'? callSignature + ; + +typeAliasDeclaration + : Export? 'type' identifier typeParameters? '=' type_ eos + ; + +constructorDeclaration + : accessibilityModifier? Constructor '(' formalParameterList? ')' ( + ('{' functionBody '}') + | SemiColon + )? + ; + +// A.5 Interface + +interfaceDeclaration + : Export? Declare? Interface identifier typeParameters? interfaceExtendsClause? objectType SemiColon? + ; + +interfaceExtendsClause + : Extends classOrInterfaceTypeList + ; + +classOrInterfaceTypeList + : typeReference (',' typeReference)* + ; + +// A.7 Interface + +enumDeclaration + : Const? Enum identifier '{' enumBody? '}' + ; + +enumBody + : enumMemberList ','? + ; + +enumMemberList + : enumMember (',' enumMember)* + ; + +enumMember + : propertyName ('=' singleExpression)? + ; + +// A.8 Namespaces + +namespaceDeclaration + : Declare? Namespace namespaceName '{' statementList? '}' + ; + +namespaceName + : identifier ('.'+ identifier)* + ; + +importAliasDeclaration + : identifier '=' namespaceName SemiColon + ; + +// Ext.2 Additions to 1.8: Decorators + +decoratorList + : decorator+ + ; + +decorator + : '@' (decoratorMemberExpression | decoratorCallExpression) + ; + +decoratorMemberExpression + : identifier + | decoratorMemberExpression '.' identifierName + | '(' singleExpression ')' + ; + +decoratorCallExpression + : decoratorMemberExpression arguments + ; + +// ECMAPart +program + : sourceElements? EOF + ; + +sourceElement + : Export? statement + ; + +statement + : block + | variableStatement + | importStatement + | exportStatement + | emptyStatement_ + | abstractDeclaration //ADDED + | classDeclaration + | functionDeclaration + | expressionStatement + | interfaceDeclaration //ADDED + | namespaceDeclaration //ADDED + | ifStatement + | iterationStatement + | continueStatement + | breakStatement + | returnStatement + | yieldStatement + | withStatement + | labelledStatement + | switchStatement + | throwStatement + | tryStatement + | debuggerStatement + | arrowFunctionDeclaration + | generatorFunctionDeclaration + | typeAliasDeclaration //ADDED + | enumDeclaration //ADDED + | Export statement + ; + +block + : '{' statementList? '}' + ; + +statementList + : statement+ + ; + +abstractDeclaration + : Abstract (identifier callSignature | variableStatement) eos + ; + +importStatement + : Import importFromBlock + ; + +importFromBlock + : importDefault? (importNamespace | importModuleItems) importFrom eos + | StringLiteral eos + ; + +importModuleItems + : '{' (importAliasName ',')* (importAliasName ','?)? '}' + ; + +importAliasName + : moduleExportName (As importedBinding)? + ; + +moduleExportName + : identifierName + | StringLiteral + ; + +// yield and await are permitted as BindingIdentifier in the grammar +importedBinding + : Identifier + | Yield + | Await + ; + +importDefault + : aliasName ',' + ; + +importNamespace + : ('*' | identifierName) (As identifierName)? + ; + +importFrom + : From StringLiteral + ; + +aliasName + : identifierName (As identifierName)? + ; + +exportStatement + : Export Default? (exportFromBlock | declaration) eos # ExportDeclaration + | Export Default singleExpression eos # ExportDefaultDeclaration + ; + +exportFromBlock + : importNamespace importFrom eos + | exportModuleItems importFrom? eos + ; + +exportModuleItems + : '{' (exportAliasName ',')* (exportAliasName ','?)? '}' + ; + +exportAliasName + : moduleExportName (As moduleExportName)? + ; + +declaration + : variableStatement + | classDeclaration + | functionDeclaration + ; + +variableStatement + : bindingPattern typeAnnotation? initializer SemiColon? + | accessibilityModifier? varModifier? ReadOnly? variableDeclarationList SemiColon? + | Declare varModifier? variableDeclarationList SemiColon? + ; + +variableDeclarationList + : variableDeclaration (',' variableDeclaration)* + ; + +variableDeclaration + : (identifierOrKeyWord | arrayLiteral | objectLiteral) typeAnnotation? singleExpression? ( + '=' typeParameters? singleExpression + )? // ECMAScript 6: Array & Object Matching + ; + +emptyStatement_ + : SemiColon + ; + +expressionStatement + : {this.notOpenBraceAndNotFunctionAndNotInterface()}? expressionSequence SemiColon? + ; + +ifStatement + : If '(' expressionSequence ')' statement (Else statement)? + ; + +iterationStatement + : Do statement While '(' expressionSequence ')' eos # DoStatement + | While '(' expressionSequence ')' statement # WhileStatement + | For '(' expressionSequence? SemiColon expressionSequence? SemiColon expressionSequence? ')' statement # ForStatement + | For '(' varModifier variableDeclarationList SemiColon expressionSequence? SemiColon expressionSequence? ')' statement # ForVarStatement + | For '(' singleExpression In expressionSequence ')' statement # ForInStatement + | For '(' varModifier variableDeclaration In expressionSequence ')' statement # ForVarInStatement + | For Await? '(' singleExpression identifier {this.p("of")}? expressionSequence (As type_)? ')' statement # ForOfStatement + | For Await? '(' varModifier variableDeclaration identifier {this.p("of")}? expressionSequence (As type_)? ')' statement # ForVarOfStatement + ; + +varModifier + : Var + | Let + | Const + ; + +continueStatement + : Continue ({this.notLineTerminator()}? identifier)? eos + ; + +breakStatement + : Break ({this.notLineTerminator()}? identifier)? eos + ; + +returnStatement + : Return ({this.notLineTerminator()}? expressionSequence)? eos + ; + +yieldStatement + : (Yield | YieldStar) ({this.notLineTerminator()}? expressionSequence)? eos + ; + +withStatement + : With '(' expressionSequence ')' statement + ; + +switchStatement + : Switch '(' expressionSequence ')' caseBlock + ; + +caseBlock + : '{' caseClauses? (defaultClause caseClauses?)? '}' + ; + +caseClauses + : caseClause+ + ; + +caseClause + : Case expressionSequence ':' statementList? + ; + +defaultClause + : Default ':' statementList? + ; + +labelledStatement + : identifier ':' statement + ; + +throwStatement + : Throw {this.notLineTerminator()}? expressionSequence eos + ; + +tryStatement + : Try block (catchProduction finallyProduction? | finallyProduction) + ; + +catchProduction + : Catch ('(' identifier typeAnnotation? ')')? block + ; + +finallyProduction + : Finally block + ; + +debuggerStatement + : Debugger eos + ; + +functionDeclaration + : Async? Function_ '*'? identifier callSignature (('{' functionBody '}') | SemiColon) + ; + +//Ovveride ECMA +classDeclaration + : decoratorList? (Export Default?)? Abstract? Class identifier typeParameters? classHeritage classTail + ; + +classHeritage + : classExtendsClause? implementsClause? + ; + +classTail + : '{' classElement* '}' + ; + +classExtendsClause + : Extends typeReference + ; + +implementsClause + : Implements classOrInterfaceTypeList + ; + +// Classes modified +classElement + : constructorDeclaration + | decoratorList? propertyMemberDeclaration + | indexMemberDeclaration + | statement + ; + +propertyMemberDeclaration + : propertyMemberBase propertyName '?'? typeAnnotation? initializer? SemiColon # PropertyDeclarationExpression + | propertyMemberBase propertyName callSignature (('{' functionBody '}') | SemiColon) # MethodDeclarationExpression + | propertyMemberBase (getAccessor | setAccessor) # GetterSetterDeclarationExpression + | abstractDeclaration # AbstractMemberDeclaration + ; + +propertyMemberBase + : accessibilityModifier? Async? Static? ReadOnly? + ; + +indexMemberDeclaration + : indexSignature SemiColon + ; + +generatorMethod + : (Async {this.notLineTerminator()}?)? '*'? propertyName '(' formalParameterList? ')' '{' functionBody '}' + ; + +generatorFunctionDeclaration + : Async? Function_ '*' identifier? '(' formalParameterList? ')' '{' functionBody '}' + ; + +generatorBlock + : '{' generatorDefinition (',' generatorDefinition)* ','? '}' + ; + +generatorDefinition + : '*' iteratorDefinition + ; + +iteratorBlock + : '{' iteratorDefinition (',' iteratorDefinition)* ','? '}' + ; + +iteratorDefinition + : '[' singleExpression ']' '(' formalParameterList? ')' '{' functionBody '}' + ; + +classElementName + : propertyName + | privateIdentifier + ; + +privateIdentifier + : '#' identifierName + ; + +formalParameterList + : formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)? ','? + | lastFormalParameterArg + | arrayLiteral // ECMAScript 6: Parameter Context Matching + | objectLiteral (':' formalParameterList)? // ECMAScript 6: Parameter Context Matching + ; + +formalParameterArg + : decorator? accessibilityModifier? assignable '?'? typeAnnotation? ( + '=' singleExpression + )? // ECMAScript 6: Initialization + ; + +lastFormalParameterArg // ECMAScript 6: Rest Parameter + : Ellipsis identifier typeAnnotation? + ; + +functionBody + : sourceElements? + ; + +sourceElements + : sourceElement+ + ; + +arrayLiteral + : ('[' elementList ']') + ; + +// JavaScript supports arrasys like [,,1,2,,]. +elementList + : ','* arrayElement? (','+ arrayElement) * ','* // Yes, everything is optional + ; + +arrayElement // ECMAScript 6: Spread Operator + : Ellipsis? (singleExpression | identifier) ','? + ; + +objectLiteral + : '{' (propertyAssignment (',' propertyAssignment)* ','?)? '}' + ; + +// MODIFIED +propertyAssignment + : propertyName (':' | '=') singleExpression # PropertyExpressionAssignment + | '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment + | getAccessor # PropertyGetter + | setAccessor # PropertySetter + | generatorMethod # MethodProperty + | identifierOrKeyWord # PropertyShorthand + | Ellipsis? singleExpression # SpreadOperator + | restParameter # RestParameterInObject + ; + +getAccessor + : getter '(' ')' typeAnnotation? '{' functionBody '}' + ; + +setAccessor + : setter '(' formalParameterList? ')' '{' functionBody '}' + ; + +propertyName + : identifierName + | StringLiteral + | numericLiteral + | '[' singleExpression ']' + ; + +arguments + : '(' (argumentList ','?)? ')' + ; + +argumentList + : argument (',' argument)* + ; + +argument // ECMAScript 6: Spread Operator + : Ellipsis? (singleExpression | identifier) + ; + +expressionSequence + : singleExpression (',' singleExpression)* + ; + +singleExpression + : anonymousFunction # FunctionExpression + | Class identifier? typeParameters? classHeritage classTail # ClassExpression + | singleExpression '?.'? '[' expressionSequence ']' # MemberIndexExpression + | singleExpression '?.' singleExpression # OptionalChainExpression + | singleExpression '!'? '.' '#'? identifierName typeGeneric? # MemberDotExpression + | singleExpression '?'? '.' '#'? identifierName typeGeneric? # MemberDotExpression + // Split to try `new Date()` first, then `new Date`. + | New singleExpression typeArguments? arguments # NewExpression + | New singleExpression typeArguments? # NewExpression + | singleExpression arguments # ArgumentsExpression + | singleExpression {this.notLineTerminator()}? '++' # PostIncrementExpression + | singleExpression {this.notLineTerminator()}? '--' # PostDecreaseExpression + | Delete singleExpression # DeleteExpression + | Void singleExpression # VoidExpression + | Typeof singleExpression # TypeofExpression + | '++' singleExpression # PreIncrementExpression + | '--' singleExpression # PreDecreaseExpression + | '+' singleExpression # UnaryPlusExpression + | '-' singleExpression # UnaryMinusExpression + | '~' singleExpression # BitNotExpression + | '!' singleExpression # NotExpression + | Await singleExpression # AwaitExpression + | singleExpression '**' singleExpression # PowerExpression + | singleExpression ('*' | '/' | '%') singleExpression # MultiplicativeExpression + | singleExpression ('+' | '-') singleExpression # AdditiveExpression + | singleExpression '??' singleExpression # CoalesceExpression + | singleExpression ('<<' | '>' '>' | '>' '>' '>') singleExpression # BitShiftExpression + | singleExpression ('<' | '>' | '<=' | '>=') singleExpression # RelationalExpression + | singleExpression Instanceof singleExpression # InstanceofExpression + | singleExpression In singleExpression # InExpression + | singleExpression ('==' | '!=' | '===' | '!==') singleExpression # EqualityExpression + | singleExpression '&' singleExpression # BitAndExpression + | singleExpression '^' singleExpression # BitXOrExpression + | singleExpression '|' singleExpression # BitOrExpression + | singleExpression '&&' singleExpression # LogicalAndExpression + | singleExpression '||' singleExpression # LogicalOrExpression + | singleExpression '?' singleExpression ':' singleExpression # TernaryExpression + | singleExpression '=' singleExpression # AssignmentExpression + | singleExpression assignmentOperator singleExpression # AssignmentOperatorExpression + | singleExpression templateStringLiteral # TemplateStringExpression // ECMAScript 6 + | iteratorBlock # IteratorsExpression // ECMAScript 6 + | generatorBlock # GeneratorsExpression // ECMAScript 6 + | generatorFunctionDeclaration # GeneratorsFunctionExpression // ECMAScript 6 + | yieldStatement # YieldExpression // ECMAScript 6 + | This # ThisExpression + | identifierName singleExpression? # IdentifierExpression + | Super # SuperExpression + | literal # LiteralExpression + | arrayLiteral # ArrayLiteralExpression + | objectLiteral # ObjectLiteralExpression + | '(' expressionSequence ')' # ParenthesizedExpression + | typeArguments expressionSequence? # GenericTypes + | singleExpression As asExpression # CastAsExpression +// TypeScript v2.0 + | singleExpression '!' # NonNullAssertionExpression + ; + +asExpression + : predefinedType ('[' ']')? + | singleExpression + ; + +assignable + : identifier + | keyword + | arrayLiteral + | objectLiteral + ; + +anonymousFunction + : functionDeclaration + | Async? Function_ '*'? '(' formalParameterList? ')' typeAnnotation? '{' functionBody '}' + | arrowFunctionDeclaration + ; + +arrowFunctionDeclaration + : Async? arrowFunctionParameters typeAnnotation? '=>' arrowFunctionBody + ; + +arrowFunctionParameters + : propertyName + | '(' formalParameterList? ')' + ; + +arrowFunctionBody + : singleExpression + | '{' functionBody '}' + ; + +assignmentOperator + : '*=' + | '/=' + | '%=' + | '+=' + | '-=' + | '<<=' + | '>>=' + | '>>>=' + | '&=' + | '^=' + | '|=' + | '**=' + | '??=' + ; + +literal + : NullLiteral + | BooleanLiteral + | StringLiteral + | templateStringLiteral + | RegularExpressionLiteral + | numericLiteral + | bigintLiteral + ; + +templateStringLiteral + : BackTick templateStringAtom* BackTick + ; + +templateStringAtom + : TemplateStringAtom + | TemplateStringStartExpression singleExpression TemplateCloseBrace + | TemplateStringEscapeAtom + ; + +numericLiteral + : DecimalLiteral + | HexIntegerLiteral + | OctalIntegerLiteral + | OctalIntegerLiteral2 + | BinaryIntegerLiteral + ; + +bigintLiteral + : BigDecimalIntegerLiteral + | BigHexIntegerLiteral + | BigOctalIntegerLiteral + | BigBinaryIntegerLiteral + ; + +getter + : {this.n("get")}? identifier classElementName + ; + +setter + : {this.n("set")}? identifier classElementName + ; + +identifierName + : identifier + | reservedWord + ; + +identifier + : Identifier + | Async + | As + | From + | Yield + | Of + | Any + | Any + | Number + | Boolean + | String + | Unique + | Symbol + | Never + | Undefined + | Object + | KeyOf + | TypeAlias + | Constructor + | Namespace + | Abstract + ; + +identifierOrKeyWord + : identifier + | TypeAlias + | Require + ; + +reservedWord + : keyword + | NullLiteral + | BooleanLiteral + ; + +keyword + : Break + | Do + | Instanceof + | Typeof + | Case + | Else + | New + | Var + | Catch + | Finally + | Return + | Void + | Continue + | For + | Switch + | While + | Debugger + | Function_ + | This + | With + | Default + | If + | Throw + | Delete + | In + | Try + | Class + | Enum + | Extends + | Super + | Const + | Export + | Import + | Implements + | Let + | Private + | Public + | Interface + | Package + | Protected + | Static + | Yield + | Async + | Await + | ReadOnly + | From + | As + | Require + | TypeAlias + | String + | Boolean + | Number + | Module + ; + +eos + : SemiColon + | EOF + | {this.lineTerminatorAhead()}? + | {this.closeBrace()}? + ; \ No newline at end of file -- Gitee From beaae675856c7f1d90798a480be1dea12a4298af Mon Sep 17 00:00:00 2001 From: wangshi Date: Fri, 7 Mar 2025 10:06:22 +0800 Subject: [PATCH 2/4] add typescript listener Signed-off-by: wangshi --- .../java/antlr/TypeScriptCustomListener.java | 239 ++++++++++++++++++ .../java/antlr/TypeScriptErrorListener.java | 52 ++++ .../ohosgen/src/main/java/parse/ParseTs.java | 3 + 3 files changed, 294 insertions(+) create mode 100644 src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java index f68ed75a..0a6c5528 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java @@ -15,6 +15,10 @@ package antlr; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.List; + /** *

类名:该类用于xxx

* description typescript custom visitor @@ -29,5 +33,240 @@ public class TypeScriptCustomListener extends TypeScriptParserBaseListener { public void enterVariableDeclaration(TypeScriptParser.VariableDeclarationContext ctx) { String varName = ctx.identifierOrKeyWord().getText(); System.out.println("变量名: " + varName); + System.out.println("var : " + ctx.getText()); + String typeAnno = ctx.typeAnnotation() != null ? ctx.typeAnnotation().getText() : ""; + System.out.println("type : " + typeAnno); + List secList = ctx.singleExpression(); + for (TypeScriptParser.SingleExpressionContext sec: secList) { + String value = sec.getText(); + System.out.println("single : " + value); + int cnt = sec.getChildCount(); + System.out.println("single child cnt: " + cnt); + for (int i=0; i plc = ctx.callSignature().parameterList().parameter(); + for (TypeScriptParser.ParameterContext pc : plc) { + System.out.println("Function param: " + pc.getText()); + TypeScriptParser. RequiredParameterContext rpc = pc.requiredParameter(); + String ta = rpc.typeAnnotation().getText(); + String iop = rpc.identifierOrPattern().getText(); + System.out.println("Function type: " + ta + " name: " + iop); + } + } + System.out.println("--------------------"); + } + + @Override + public void enterClassDeclaration(TypeScriptParser.ClassDeclarationContext ctx) { + super.enterClassDeclaration(ctx); + // 提取类名、方法、属性等信息 + String className = ctx.identifier().getText(); + System.out.println("Class: " + className); + + + // 获取修饰符(如public/abstract) + TypeScriptParser.DecoratorListContext dlc = ctx.decoratorList(); + if (dlc != null) { + System.out.println("Class decoratorList: " + dlc.getText()); + } + // 处理继承关系(extends/implements) + TypeScriptParser.ClassHeritageContext heritage = ctx.classHeritage(); + System.out.println("Class heritage: " + heritage.getText()); + } + + @Override + public void enterClassElement(TypeScriptParser.ClassElementContext ctx) { + super.enterClassElement(ctx); + System.out.println("Class element: " + ctx.getText()); + TypeScriptParser.StatementContext sc = ctx.statement(); + if (sc != null) { + System.out.println("Class state: " + sc.getText()); + } + + TypeScriptParser.PropertyMemberDeclarationContext pmdc = ctx.propertyMemberDeclaration(); + if (pmdc != null) { + System.out.println("Class property: " + pmdc.getText()); + } + } + + @Override + public void enterMethodDeclarationExpression(TypeScriptParser.MethodDeclarationExpressionContext ctx) { + super.enterMethodDeclarationExpression(ctx); + System.out.println("Method property: " + ctx.getText()); + String propertyName = ctx.propertyName().getText(); + System.out.println("Method name: " + propertyName); + String callSign = ctx.callSignature().getText(); + System.out.println("Method callSign: " + callSign); + String typeAnno = ctx.callSignature().typeAnnotation().getText(); + System.out.println("Method typeAnno: " + typeAnno); + List plc = ctx.callSignature().parameterList().parameter(); + for (TypeScriptParser.ParameterContext pc : plc) { + System.out.println("Method param: " + pc.getText()); + TypeScriptParser. RequiredParameterContext rpc = pc.requiredParameter(); + String ta = rpc.typeAnnotation().getText(); + String iop = rpc.identifierOrPattern().getText(); + System.out.println("Method type: " + ta + " name: " + iop); + } + int cnt = ctx.getChildCount(); + System.out.println("Method param cnt: " + cnt); + } + + @Override + public void enterPropertyDeclarationExpression(TypeScriptParser.PropertyDeclarationExpressionContext ctx) { + super.enterPropertyDeclarationExpression(ctx); + System.out.println("Property property: " + ctx.getText()); + String propertyName = ctx.propertyName().getText(); + String typeName = ctx.typeAnnotation().getText(); + System.out.println("Property name: " + propertyName + " type: " + typeName); } + + @Override + public void enterTypeAliasDeclaration(TypeScriptParser.TypeAliasDeclarationContext ctx) { + super.enterTypeAliasDeclaration(ctx); + String typeName = ctx.identifier().getText(); + System.out.println("Type: " + typeName); + TypeScriptParser.TypeParametersContext tpc = ctx.typeParameters(); + if (tpc != null) { + System.out.println("Type params: " + tpc.getText()); + } + TypeScriptParser.Type_Context t_c = ctx.type_(); + if (t_c != null) { + System.out.println("Type type_: " + t_c.getText()); + + TypeScriptParser.UnionOrIntersectionOrPrimaryTypeContext upt = t_c.unionOrIntersectionOrPrimaryType(); + if (upt != null) { + System.out.println("Type uoiop: " + upt.getText()); + } + TypeScriptParser.TypeGenericContext tgc = t_c.typeGeneric(); + if (tgc != null) { + System.out.println("Type typeGeneric: " + tgc.getText()); + } + TypeScriptParser.ConstructorTypeContext ctc = t_c.constructorType(); + if (ctc != null) { + System.out.println("Type constructorType: " + ctc.getText()); + } + TypeScriptParser.FunctionTypeContext ftc = t_c.functionType(); + if (ftc != null) { + System.out.println("Type functionType: " + ftc.getText()); + } + } + + System.out.println("-------------------"); + } + + @Override + public void enterEnumBody(TypeScriptParser.EnumBodyContext ctx) { +// super.enterEnumBody(ctx); + System.out.println("find Enum Body: "); + String enumName = ctx.getText(); + System.out.println("Enum: " + enumName); + } + + @Override + public void enterEnumMemberList(TypeScriptParser.EnumMemberListContext ctx) { + super.enterEnumMemberList(ctx); + List memList = ctx.enumMember(); + for (TypeScriptParser.EnumMemberContext enumMemberContext : memList) { + String memName = enumMemberContext.getText(); + System.out.println("Enum mem: " + memName); + } + } + + @Override + public void enterEnumDeclaration(TypeScriptParser.EnumDeclarationContext ctx) { + super.enterEnumDeclaration(ctx); + System.out.println("find Enum Declare: "); + String res = ""; + String enumName = ctx.identifier().getText(); + res += "Enum: " + enumName; + System.out.println("Enum name: " + res); + + List members = ctx.enumBody().enumMemberList().enumMember(); + for (int i=0; i tmcList = tlc.typeMember(); + for (TypeScriptParser.TypeMemberContext tmc: tmcList) { + String callSign = tmc.callSignature().getText(); + System.out.println("interface callSign: " + callSign); + String typeAnno = tmc.callSignature().typeAnnotation().getText(); + System.out.println("interface typeAnno: " + typeAnno); + List plc = tmc.callSignature().parameterList().parameter(); + for (TypeScriptParser.ParameterContext pc : plc) { + System.out.println("interface param: " + pc.getText()); + TypeScriptParser. RequiredParameterContext rpc = pc.requiredParameter(); + String ta = rpc.typeAnnotation().getText(); + String iop = rpc.identifierOrPattern().getText(); + System.out.println("interface type: " + ta + " name: " + iop); + } + } + System.out.println("----------------"); + } + + @Override + public void enterAbstractDeclaration(TypeScriptParser.AbstractDeclarationContext ctx) { + super.enterAbstractDeclaration(ctx); + System.out.println("find abstract Declare: "+ ctx.toString()); + } + + @Override + public void enterExportDeclaration(TypeScriptParser.ExportDeclarationContext ctx) { + super.enterExportDeclaration(ctx); + System.out.println("find export Declare: " + ctx.toString()); + } + + } diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java new file mode 100644 index 00000000..20ee16f9 --- /dev/null +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 Shenzhen Kaihong Digital. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package antlr; + +import org.antlr.v4.runtime.*; +import org.antlr.v4.runtime.misc.IntervalSet; +/** + *

类名:该类用于xxx

+ * description typescript error listener + * + * @author Administrator + * date 2025-02-28 + * @version 1.0 + * @since 2025-02-28 + */ +public class TypeScriptErrorListener extends BaseErrorListener { + @Override + public void syntaxError(Recognizer recognizer, + Object offendingSymbol, + int line, + int charPositionInLine, + String msg, + RecognitionException e) { + System.err.println("syntax error"); + System.out.println("syntax error"); + // 输出错误位置和消息 + String errorHeader = String.format("语法错误@行%d:%d - ", line, charPositionInLine + 1); + String errorDetail = String.format("符号 '%s' 无效,预期: %s", + ((Token) offendingSymbol).getText(), + getExpectedTokens(recognizer, e)); + System.err.println(errorHeader + errorDetail + " | 错误详情: " + msg); + } + + private String getExpectedTokens(Recognizer recognizer, RecognitionException e) { + if (e == null) return "未知预期符号"; + IntervalSet expectedTokens = e.getExpectedTokens(); + return expectedTokens.toString(recognizer.getVocabulary()); + } +} \ No newline at end of file diff --git a/src/intellij_plugin/ohosgen/src/main/java/parse/ParseTs.java b/src/intellij_plugin/ohosgen/src/main/java/parse/ParseTs.java index 5d85340d..4d1208a6 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/parse/ParseTs.java +++ b/src/intellij_plugin/ohosgen/src/main/java/parse/ParseTs.java @@ -16,6 +16,7 @@ package parse; import antlr.TypeScriptCustomListener; +import antlr.TypeScriptErrorListener; import antlr.TypeScriptLexer; import antlr.TypeScriptParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -89,6 +90,8 @@ public class ParseTs extends ParseBase { CommonTokenStream tokens = new CommonTokenStream(lexer); // 初始化语法分析器并生成 AST TypeScriptParser parser = new TypeScriptParser(tokens); + parser.removeErrorListeners(); + parser.addErrorListener(new TypeScriptErrorListener()); ParseTree tree = parser.program(); TypeScriptCustomListener tsc = new TypeScriptCustomListener(); ParseTreeWalker walker = new ParseTreeWalker(); -- Gitee From 7924391f479fcb75e7db8c7434c1212f0f0dae83 Mon Sep 17 00:00:00 2001 From: wangshi Date: Fri, 7 Mar 2025 10:53:21 +0800 Subject: [PATCH 3/4] fix code check Signed-off-by: wangshi --- .../java/antlr/TypeScriptCustomListener.java | 32 +++++++++---------- .../java/antlr/TypeScriptErrorListener.java | 9 ++++-- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java index 0a6c5528..a1a3f44a 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java @@ -37,12 +37,12 @@ public class TypeScriptCustomListener extends TypeScriptParserBaseListener { String typeAnno = ctx.typeAnnotation() != null ? ctx.typeAnnotation().getText() : ""; System.out.println("type : " + typeAnno); List secList = ctx.singleExpression(); - for (TypeScriptParser.SingleExpressionContext sec: secList) { + for (TypeScriptParser.SingleExpressionContext sec : secList) { String value = sec.getText(); System.out.println("single : " + value); int cnt = sec.getChildCount(); System.out.println("single child cnt: " + cnt); - for (int i=0; i members = ctx.enumBody().enumMemberList().enumMember(); - for (int i=0; i tmcList = tlc.typeMember(); - for (TypeScriptParser.TypeMemberContext tmc: tmcList) { + for (TypeScriptParser.TypeMemberContext tmc : tmcList) { String callSign = tmc.callSignature().getText(); System.out.println("interface callSign: " + callSign); String typeAnno = tmc.callSignature().typeAnnotation().getText(); @@ -259,7 +259,7 @@ public class TypeScriptCustomListener extends TypeScriptParserBaseListener { @Override public void enterAbstractDeclaration(TypeScriptParser.AbstractDeclarationContext ctx) { super.enterAbstractDeclaration(ctx); - System.out.println("find abstract Declare: "+ ctx.toString()); + System.out.println("find abstract Declare: " + ctx.toString()); } @Override diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java index 20ee16f9..356a2835 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java @@ -17,6 +17,9 @@ package antlr; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.IntervalSet; + +import java.util.Locale; + /** *

类名:该类用于xxx

* description typescript error listener @@ -37,7 +40,7 @@ public class TypeScriptErrorListener extends BaseErrorListener { System.err.println("syntax error"); System.out.println("syntax error"); // 输出错误位置和消息 - String errorHeader = String.format("语法错误@行%d:%d - ", line, charPositionInLine + 1); + String errorHeader = String.format(Locale.ROOT, "语法错误@行%d:%d - ", line, charPositionInLine + 1); String errorDetail = String.format("符号 '%s' 无效,预期: %s", ((Token) offendingSymbol).getText(), getExpectedTokens(recognizer, e)); @@ -45,7 +48,9 @@ public class TypeScriptErrorListener extends BaseErrorListener { } private String getExpectedTokens(Recognizer recognizer, RecognitionException e) { - if (e == null) return "未知预期符号"; + if (e == null) { + return "未知预期符号"; + } IntervalSet expectedTokens = e.getExpectedTokens(); return expectedTokens.toString(recognizer.getVocabulary()); } -- Gitee From ddb1cffdd6e7df7434fe47782e882bdf070b4668 Mon Sep 17 00:00:00 2001 From: wangshi Date: Fri, 7 Mar 2025 11:30:00 +0800 Subject: [PATCH 4/4] fix code check Signed-off-by: wangshi --- .../ohosgen/src/main/java/antlr/TypeScriptCustomListener.java | 2 +- .../ohosgen/src/main/java/antlr/TypeScriptErrorListener.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java index a1a3f44a..0d502fb1 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptCustomListener.java @@ -42,7 +42,7 @@ public class TypeScriptCustomListener extends TypeScriptParserBaseListener { System.out.println("single : " + value); int cnt = sec.getChildCount(); System.out.println("single child cnt: " + cnt); - for (int i=0; i < cnt; i++) { + for (int i = 0; i < cnt; i++) { ParseTree pt = sec.getChild(i); System.out.println("single child pt: " + pt.getText()); } diff --git a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java index 356a2835..08215ac7 100644 --- a/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java +++ b/src/intellij_plugin/ohosgen/src/main/java/antlr/TypeScriptErrorListener.java @@ -42,7 +42,7 @@ public class TypeScriptErrorListener extends BaseErrorListener { // 输出错误位置和消息 String errorHeader = String.format(Locale.ROOT, "语法错误@行%d:%d - ", line, charPositionInLine + 1); String errorDetail = String.format("符号 '%s' 无效,预期: %s", - ((Token) offendingSymbol).getText(), + offendingSymbol instanceof Token ? ((Token) offendingSymbol).getText() : "", getExpectedTokens(recognizer, e)); System.err.println(errorHeader + errorDetail + " | 错误详情: " + msg); } -- Gitee