Repository: go-lang-plugin-org/go-lang-idea-plugin Branch: master Commit: e73dab44213f Files: 2309 Total size: 5.3 MB Directory structure: gitextract_gj_5aest/ ├── .gitattributes ├── .gitignore ├── .idea/ │ ├── ant.xml │ ├── codeStyleSettings.xml │ ├── copyright/ │ │ ├── apache.xml │ │ ├── no_copyright.xml │ │ └── profiles_settings.xml │ ├── dictionaries/ │ │ ├── ignatov.xml │ │ └── zolotov.xml │ ├── encodings.xml │ ├── externalDependencies.xml │ ├── inspectionProfiles/ │ │ ├── Project_Default.xml │ │ ├── idea_default.xml │ │ └── profiles_settings.xml │ ├── runConfigurations/ │ │ ├── All_tests.xml │ │ ├── Build_plugin.xml │ │ ├── Go.xml │ │ ├── Local_IDE.xml │ │ └── Performance_tests.xml │ ├── scopes/ │ │ ├── scope_settings.xml │ │ └── testdata.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── LICENCE ├── README.md ├── build.gradle ├── cloneToWt.sh ├── gen/ │ └── com/ │ └── goide/ │ ├── GoTypes.java │ ├── lexer/ │ │ └── _GoLexer.java │ ├── parser/ │ │ └── GoParser.java │ └── psi/ │ ├── GoAddExpr.java │ ├── GoAndExpr.java │ ├── GoAnonymousFieldDefinition.java │ ├── GoArgumentList.java │ ├── GoArrayOrSliceType.java │ ├── GoAssignOp.java │ ├── GoAssignmentStatement.java │ ├── GoBinaryExpr.java │ ├── GoBlock.java │ ├── GoBreakStatement.java │ ├── GoBuiltinArgumentList.java │ ├── GoBuiltinCallExpr.java │ ├── GoCallExpr.java │ ├── GoChannelType.java │ ├── GoCommCase.java │ ├── GoCommClause.java │ ├── GoCompositeLit.java │ ├── GoConditionalExpr.java │ ├── GoConstDeclaration.java │ ├── GoConstDefinition.java │ ├── GoConstSpec.java │ ├── GoContinueStatement.java │ ├── GoConversionExpr.java │ ├── GoDeferStatement.java │ ├── GoElement.java │ ├── GoElseStatement.java │ ├── GoExprCaseClause.java │ ├── GoExprSwitchStatement.java │ ├── GoExpression.java │ ├── GoFallthroughStatement.java │ ├── GoFieldDeclaration.java │ ├── GoFieldDefinition.java │ ├── GoFieldName.java │ ├── GoForClause.java │ ├── GoForStatement.java │ ├── GoFunctionDeclaration.java │ ├── GoFunctionLit.java │ ├── GoFunctionType.java │ ├── GoGoStatement.java │ ├── GoGotoStatement.java │ ├── GoIfStatement.java │ ├── GoImportDeclaration.java │ ├── GoImportList.java │ ├── GoImportSpec.java │ ├── GoImportString.java │ ├── GoIncDecStatement.java │ ├── GoIndexOrSliceExpr.java │ ├── GoInterfaceType.java │ ├── GoKey.java │ ├── GoLabelDefinition.java │ ├── GoLabelRef.java │ ├── GoLabeledStatement.java │ ├── GoLeftHandExprList.java │ ├── GoLiteral.java │ ├── GoLiteralTypeExpr.java │ ├── GoLiteralValue.java │ ├── GoMapType.java │ ├── GoMethodDeclaration.java │ ├── GoMethodSpec.java │ ├── GoMulExpr.java │ ├── GoOrExpr.java │ ├── GoPackageClause.java │ ├── GoParType.java │ ├── GoParamDefinition.java │ ├── GoParameterDeclaration.java │ ├── GoParameters.java │ ├── GoParenthesesExpr.java │ ├── GoPointerType.java │ ├── GoRangeClause.java │ ├── GoReceiver.java │ ├── GoRecvStatement.java │ ├── GoReferenceExpression.java │ ├── GoResult.java │ ├── GoReturnStatement.java │ ├── GoSelectStatement.java │ ├── GoSelectorExpr.java │ ├── GoSendStatement.java │ ├── GoShortVarDeclaration.java │ ├── GoSignature.java │ ├── GoSimpleStatement.java │ ├── GoSpecType.java │ ├── GoStatement.java │ ├── GoStringLiteral.java │ ├── GoStructType.java │ ├── GoSwitchStart.java │ ├── GoSwitchStatement.java │ ├── GoTag.java │ ├── GoType.java │ ├── GoTypeAssertionExpr.java │ ├── GoTypeCaseClause.java │ ├── GoTypeDeclaration.java │ ├── GoTypeGuard.java │ ├── GoTypeList.java │ ├── GoTypeReferenceExpression.java │ ├── GoTypeSpec.java │ ├── GoTypeSwitchGuard.java │ ├── GoTypeSwitchStatement.java │ ├── GoUnaryExpr.java │ ├── GoValue.java │ ├── GoVarDeclaration.java │ ├── GoVarDefinition.java │ ├── GoVarSpec.java │ ├── GoVisitor.java │ └── impl/ │ ├── GoAddExprImpl.java │ ├── GoAndExprImpl.java │ ├── GoAnonymousFieldDefinitionImpl.java │ ├── GoArgumentListImpl.java │ ├── GoArrayOrSliceTypeImpl.java │ ├── GoAssignOpImpl.java │ ├── GoAssignmentStatementImpl.java │ ├── GoBinaryExprImpl.java │ ├── GoBlockImpl.java │ ├── GoBreakStatementImpl.java │ ├── GoBuiltinArgumentListImpl.java │ ├── GoBuiltinCallExprImpl.java │ ├── GoCallExprImpl.java │ ├── GoChannelTypeImpl.java │ ├── GoCommCaseImpl.java │ ├── GoCommClauseImpl.java │ ├── GoCompositeLitImpl.java │ ├── GoConditionalExprImpl.java │ ├── GoConstDeclarationImpl.java │ ├── GoConstDefinitionImpl.java │ ├── GoConstSpecImpl.java │ ├── GoContinueStatementImpl.java │ ├── GoConversionExprImpl.java │ ├── GoDeferStatementImpl.java │ ├── GoElementImpl.java │ ├── GoElseStatementImpl.java │ ├── GoExprCaseClauseImpl.java │ ├── GoExprSwitchStatementImpl.java │ ├── GoExpressionImpl.java │ ├── GoFallthroughStatementImpl.java │ ├── GoFieldDeclarationImpl.java │ ├── GoFieldDefinitionImpl.java │ ├── GoFieldNameImpl.java │ ├── GoForClauseImpl.java │ ├── GoForStatementImpl.java │ ├── GoFunctionDeclarationImpl.java │ ├── GoFunctionLitImpl.java │ ├── GoFunctionTypeImpl.java │ ├── GoGoStatementImpl.java │ ├── GoGotoStatementImpl.java │ ├── GoIfStatementImpl.java │ ├── GoImportDeclarationImpl.java │ ├── GoImportListImpl.java │ ├── GoImportSpecImpl.java │ ├── GoImportStringImpl.java │ ├── GoIncDecStatementImpl.java │ ├── GoIndexOrSliceExprImpl.java │ ├── GoInterfaceTypeImpl.java │ ├── GoKeyImpl.java │ ├── GoLabelDefinitionImpl.java │ ├── GoLabelRefImpl.java │ ├── GoLabeledStatementImpl.java │ ├── GoLeftHandExprListImpl.java │ ├── GoLiteralImpl.java │ ├── GoLiteralTypeExprImpl.java │ ├── GoLiteralValueImpl.java │ ├── GoMapTypeImpl.java │ ├── GoMethodDeclarationImpl.java │ ├── GoMethodSpecImpl.java │ ├── GoMulExprImpl.java │ ├── GoOrExprImpl.java │ ├── GoPackageClauseImpl.java │ ├── GoParTypeImpl.java │ ├── GoParamDefinitionImpl.java │ ├── GoParameterDeclarationImpl.java │ ├── GoParametersImpl.java │ ├── GoParenthesesExprImpl.java │ ├── GoPointerTypeImpl.java │ ├── GoRangeClauseImpl.java │ ├── GoReceiverImpl.java │ ├── GoRecvStatementImpl.java │ ├── GoReferenceExpressionImpl.java │ ├── GoResultImpl.java │ ├── GoReturnStatementImpl.java │ ├── GoSelectStatementImpl.java │ ├── GoSelectorExprImpl.java │ ├── GoSendStatementImpl.java │ ├── GoShortVarDeclarationImpl.java │ ├── GoSignatureImpl.java │ ├── GoSimpleStatementImpl.java │ ├── GoSpecTypeImpl.java │ ├── GoStatementImpl.java │ ├── GoStringLiteralImpl.java │ ├── GoStructTypeImpl.java │ ├── GoSwitchStartImpl.java │ ├── GoSwitchStatementImpl.java │ ├── GoTagImpl.java │ ├── GoTypeAssertionExprImpl.java │ ├── GoTypeCaseClauseImpl.java │ ├── GoTypeDeclarationImpl.java │ ├── GoTypeGuardImpl.java │ ├── GoTypeImpl.java │ ├── GoTypeListImpl.java │ ├── GoTypeReferenceExpressionImpl.java │ ├── GoTypeSpecImpl.java │ ├── GoTypeSwitchGuardImpl.java │ ├── GoTypeSwitchStatementImpl.java │ ├── GoUnaryExprImpl.java │ ├── GoValueImpl.java │ ├── GoVarDeclarationImpl.java │ ├── GoVarDefinitionImpl.java │ └── GoVarSpecImpl.java ├── google-app-engine/ │ ├── google-app-engine-yaml/ │ │ ├── build.gradle │ │ └── src/ │ │ └── yaml/ │ │ ├── AppEngineYamlCompletionContributor.java │ │ └── YamlConstants.java │ └── src/ │ └── com/ │ └── intellij/ │ └── appengine/ │ ├── AppEngineExtension.java │ └── GoogleAppEngineIcons.java ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── grammars/ │ ├── copyrightHeader.java │ └── go.bnf ├── plan9/ │ ├── build.gradle │ ├── gen/ │ │ └── com/ │ │ └── plan9/ │ │ └── intel/ │ │ └── lang/ │ │ └── core/ │ │ ├── lexer/ │ │ │ ├── _AsmIntelHighlightingLexer.java │ │ │ └── _AsmIntelLexer.java │ │ ├── parser/ │ │ │ └── AsmIntelParser.java │ │ └── psi/ │ │ ├── AsmIntelFrameSize.java │ │ ├── AsmIntelFunction.java │ │ ├── AsmIntelFunctionBody.java │ │ ├── AsmIntelFunctionFlags.java │ │ ├── AsmIntelFunctionHeader.java │ │ ├── AsmIntelInstructionStmt.java │ │ ├── AsmIntelLiteral.java │ │ ├── AsmIntelOperands.java │ │ ├── AsmIntelPreprocessorDirective.java │ │ ├── AsmIntelStatement.java │ │ ├── AsmIntelTypes.java │ │ ├── AsmIntelVisitor.java │ │ └── impl/ │ │ ├── AsmIntelFrameSizeImpl.java │ │ ├── AsmIntelFunctionBodyImpl.java │ │ ├── AsmIntelFunctionFlagsImpl.java │ │ ├── AsmIntelFunctionHeaderImpl.java │ │ ├── AsmIntelFunctionImpl.java │ │ ├── AsmIntelInstructionStmtImpl.java │ │ ├── AsmIntelLiteralImpl.java │ │ ├── AsmIntelOperandsImpl.java │ │ ├── AsmIntelPreprocessorDirectiveImpl.java │ │ └── AsmIntelStatementImpl.java │ ├── resources/ │ │ └── colorscheme/ │ │ ├── AsmIntelDarcula.xml │ │ ├── AsmIntelDefault.xml │ │ └── highlighterDemoText.s │ ├── src/ │ │ └── com/ │ │ └── plan9/ │ │ └── intel/ │ │ ├── AsmIntelFileType.java │ │ ├── AsmIntelFileTypeFactory.java │ │ ├── Icons.java │ │ ├── ide/ │ │ │ └── highlighting/ │ │ │ ├── AsmIntelColorsAndFontsPage.java │ │ │ ├── AsmIntelHighlightingLexer.flex │ │ │ ├── AsmIntelHighlightingLexer.java │ │ │ ├── AsmIntelLexerTokens.java │ │ │ ├── AsmIntelSyntaxHighlighter.java │ │ │ ├── AsmIntelSyntaxHighlighterFactory.java │ │ │ └── AsmIntelSyntaxHighlightingColors.java │ │ └── lang/ │ │ ├── AsmIntelLanguage.java │ │ └── core/ │ │ ├── AsmIntelParserDefinition.java │ │ ├── grammar/ │ │ │ └── x86.bnf │ │ ├── lexer/ │ │ │ ├── AsmIntelLexer.flex │ │ │ ├── AsmIntelLexer.java │ │ │ └── AsmIntelTokenType.java │ │ └── psi/ │ │ ├── AsmIntelElementType.java │ │ ├── AsmIntelFile.java │ │ └── impl/ │ │ └── AsmIntelElementImpl.java │ ├── testData/ │ │ └── intel/ │ │ ├── lexer/ │ │ │ ├── commentsAndWhitespace.s │ │ │ ├── commentsAndWhitespace.txt │ │ │ ├── identifiers.s │ │ │ ├── identifiers.txt │ │ │ ├── simpleFile.s │ │ │ └── simpleFile.txt │ │ └── parser/ │ │ ├── SingleFunction.s │ │ └── SingleFunction.txt │ └── tests/ │ └── com/ │ └── plan9/ │ └── intel/ │ └── lang/ │ └── core/ │ ├── lexer/ │ │ └── AsmIntelLexerTest.java │ └── parser/ │ └── AsmIntelParserTest.java ├── pluginResources/ │ └── META-INF/ │ └── plugin.xml ├── resources/ │ ├── META-INF/ │ │ ├── app-engine.xml │ │ ├── coverage.xml │ │ ├── gogland.xml │ │ ├── google-app-engine-core-yaml.xml │ │ ├── java-deps.xml │ │ └── plan9.xml │ ├── colorscheme/ │ │ └── Darcula - dlsniper.xml │ ├── com/ │ │ └── goide/ │ │ └── GoBundle.properties │ ├── fileTemplates/ │ │ └── internal/ │ │ ├── Go Application.go.ft │ │ ├── Go Application.go.html │ │ ├── Go File.go.ft │ │ └── Go File.go.html │ ├── inspectionDescriptions/ │ │ ├── GoAddTrailingComma.html │ │ ├── GoAnonymousFieldDefinitionType.html │ │ ├── GoAssignmentNilWithoutExplicitType.html │ │ ├── GoAssignmentToConstant.html │ │ ├── GoAssignmentToReceiver.html │ │ ├── GoBoolExpressions.html │ │ ├── GoCgoInTest.html │ │ ├── GoCommentStart.html │ │ ├── GoDeferGo.html │ │ ├── GoDeferInLoop.html │ │ ├── GoDirectAssignToStructFieldInMap.html │ │ ├── GoDuplicateArgument.html │ │ ├── GoDuplicateFieldsOrMethods.html │ │ ├── GoDuplicateFunctionOrMethod.html │ │ ├── GoDuplicateReturnArgument.html │ │ ├── GoEmbeddedInterfacePointer.html │ │ ├── GoEmptyDeclaration.html │ │ ├── GoExportedOwnDeclaration.html │ │ ├── GoFunctionCall.html │ │ ├── GoFunctionVariadicParameter.html │ │ ├── GoImportUsedAsName.html │ │ ├── GoInfiniteFor.html │ │ ├── GoInvalidPackageImport.html │ │ ├── GoInvalidStringOrChar.html │ │ ├── GoMissingReturn.html │ │ ├── GoMixedNamedUnnamedParameters.html │ │ ├── GoMultiplePackages.html │ │ ├── GoNoNewVariables.html │ │ ├── GoPlaceholderCount.html │ │ ├── GoRangeIterationOnIllegalType.html │ │ ├── GoReceiverNames.html │ │ ├── GoRedeclareImportAsFunction.html │ │ ├── GoRedundantBlankArgInRange.html │ │ ├── GoRedundantSecondIndexInSlices.html │ │ ├── GoRedundantTypeDeclInCompositeLit.html │ │ ├── GoReservedWordUsedAsName.html │ │ ├── GoSelfImport.html │ │ ├── GoStringAndByteTypeMismatch.html │ │ ├── GoStructInitialization.html │ │ ├── GoStructTag.html │ │ ├── GoTestSignatures.html │ │ ├── GoUnderscoreUsedAsValue.html │ │ ├── GoUnresolvedReference.html │ │ ├── GoUnusedConst.html │ │ ├── GoUnusedExportedFunction.html │ │ ├── GoUnusedFunction.html │ │ ├── GoUnusedGlobalVariable.html │ │ ├── GoUnusedImport.html │ │ ├── GoUnusedLabel.html │ │ ├── GoUnusedParameter.html │ │ ├── GoUnusedVariable.html │ │ ├── GoUsedAsValueInCondition.html │ │ └── GoVarDeclaration.html │ ├── intentionDescriptions/ │ │ ├── GoAddFunctionBlockIntention/ │ │ │ ├── after.go.template │ │ │ ├── before.go.template │ │ │ └── description.html │ │ └── GoMoveToStructInitializationIntention/ │ │ ├── after.go.template │ │ ├── before.go.template │ │ └── description.html │ └── liveTemplates/ │ ├── go.xml │ ├── goHidden.xml │ └── goTags.xml ├── settings.gradle ├── src/ │ └── com/ │ └── goide/ │ ├── GoCommenter.java │ ├── GoCommentsConverter.java │ ├── GoDocumentationProvider.java │ ├── GoFileElementType.java │ ├── GoFileType.java │ ├── GoFileTypeFactory.java │ ├── GoIconProvider.java │ ├── GoIcons.java │ ├── GoIndexPatternBuilder.java │ ├── GoLanguage.java │ ├── GoModuleBuilder.java │ ├── GoModuleType.java │ ├── GoNamesValidator.java │ ├── GoParserDefinition.java │ ├── GoProjectGenerator.java │ ├── UpdateComponent.java │ ├── actions/ │ │ ├── file/ │ │ │ ├── GoCreateFileAction.java │ │ │ ├── GoCreateFromTemplateHandler.java │ │ │ └── GoTemplatePropertiesProvider.java │ │ └── tool/ │ │ ├── GoDownloadableFileAction.java │ │ ├── GoExternalToolsAction.java │ │ ├── GoFmtCheckinFactory.java │ │ ├── GoFmtFileAction.java │ │ ├── GoFmtProjectAction.java │ │ ├── GoImportsFileAction.java │ │ ├── GoTypeFileAction.java │ │ └── GoVetFileAction.java │ ├── appengine/ │ │ ├── GoAppEngineExtension.java │ │ ├── GoAppEngineIcons.java │ │ ├── GoAppEngineLibraryPresentationProvider.java │ │ ├── YamlFilesModificationTracker.java │ │ └── run/ │ │ ├── GoAppEngineRunConfiguration.java │ │ ├── GoAppEngineRunConfigurationEditor.form │ │ ├── GoAppEngineRunConfigurationEditor.java │ │ ├── GoAppEngineRunConfigurationType.java │ │ └── GoAppEngineRunningState.java │ ├── codeInsight/ │ │ ├── GoExpressionTypeProvider.java │ │ ├── imports/ │ │ │ ├── GoAutoImportConfigurable.java │ │ │ ├── GoCodeInsightSettings.java │ │ │ ├── GoExcludePathLookupActionProvider.java │ │ │ ├── GoGetPackageFix.java │ │ │ ├── GoImportOptimizer.java │ │ │ └── GoImportPackageQuickFix.java │ │ └── unwrap/ │ │ ├── GoBracesUnwrapper.java │ │ ├── GoElseRemover.java │ │ ├── GoElseUnwrapper.java │ │ ├── GoElseUnwrapperBase.java │ │ ├── GoForUnwrapper.java │ │ ├── GoFunctionArgumentUnwrapper.java │ │ ├── GoIfUnwrapper.java │ │ ├── GoUnwrapDescriptor.java │ │ └── GoUnwrapper.java │ ├── completion/ │ │ ├── AddBracketsInsertHandler.java │ │ ├── BracesInsertHandler.java │ │ ├── CancellableCollectProcessor.java │ │ ├── GoAutoImportCompletionContributor.java │ │ ├── GoAutoImportInsertHandler.java │ │ ├── GoCharFilter.java │ │ ├── GoCompletionConfidence.java │ │ ├── GoCompletionContributor.java │ │ ├── GoCompletionUtil.java │ │ ├── GoImportPathsCompletionProvider.java │ │ ├── GoKeywordCompletionContributor.java │ │ ├── GoKeywordCompletionProvider.java │ │ ├── GoReferenceCompletionProvider.java │ │ ├── GoStructLiteralCompletion.java │ │ ├── GoTestFunctionCompletionProvider.java │ │ └── SingleCharInsertHandler.java │ ├── configuration/ │ │ ├── GoBuildTagsUI.form │ │ ├── GoBuildTagsUI.java │ │ ├── GoConfigurableProvider.java │ │ ├── GoLibrariesConfigurable.java │ │ ├── GoLibrariesConfigurableProvider.java │ │ ├── GoModuleAwareConfigurable.java │ │ ├── GoModuleEditorsProvider.java │ │ ├── GoModuleSettingsConfigurable.java │ │ ├── GoModuleSettingsUI.form │ │ ├── GoModuleSettingsUI.java │ │ ├── GoSdkConfigurable.form │ │ ├── GoSdkConfigurable.java │ │ ├── GoUIUtil.java │ │ ├── GoVendoringUI.form │ │ ├── GoVendoringUI.java │ │ └── ListenableHideableDecorator.java │ ├── dlv/ │ │ ├── DlvCommandProcessor.java │ │ ├── DlvDebugProcess.java │ │ ├── DlvRemoteVmConnection.java │ │ ├── DlvStackFrame.java │ │ ├── DlvSuspendContext.java │ │ ├── DlvVm.java │ │ ├── DlvXValue.java │ │ ├── JsonReaderEx.java │ │ ├── breakpoint/ │ │ │ ├── DlvBreakpointProperties.java │ │ │ └── DlvBreakpointType.java │ │ └── protocol/ │ │ ├── DlvApi.java │ │ ├── DlvRequest.java │ │ └── DlvResponse.java │ ├── editor/ │ │ ├── GoBraceMatcher.java │ │ ├── GoFoldingBuilder.java │ │ ├── GoImplementationTextSelectioner.java │ │ ├── GoParameterInfoHandler.java │ │ ├── GoQuoteHandler.java │ │ ├── GoStatementMover.java │ │ ├── GoTypeDeclarationProvider.java │ │ ├── GoTypedHandler.java │ │ ├── GoWordSelectioner.java │ │ ├── marker/ │ │ │ └── GoMethodSeparatorProvider.java │ │ ├── smart/ │ │ │ └── GoSmartEnterProcessor.java │ │ └── surround/ │ │ ├── GoBoolExpressionSurrounderBase.java │ │ ├── GoExpressionSurroundDescriptor.java │ │ ├── GoExpressionSurrounder.java │ │ ├── GoStatementsSurroundDescriptor.java │ │ ├── GoStatementsSurrounder.java │ │ ├── GoWithBlockSurrounder.java │ │ ├── GoWithForSurrounder.java │ │ ├── GoWithIfElseExpressionSurrounder.java │ │ ├── GoWithIfElseSurrounder.java │ │ ├── GoWithIfExpressionSurrounder.java │ │ ├── GoWithIfSurrounder.java │ │ ├── GoWithNotExpressionSurrounder.java │ │ └── GoWithParenthesisSurrounder.java │ ├── formatter/ │ │ ├── GoFormattingModelBuilder.java │ │ └── settings/ │ │ ├── GoCodeStyleConfigurable.java │ │ ├── GoCodeStyleSettingsProvider.java │ │ └── GoLanguageCodeStyleSettingsProvider.java │ ├── generate/ │ │ ├── GoGenerateTestActionBase.java │ │ └── GoGenerateTestMethodActionGroup.java │ ├── go/ │ │ ├── GoGotoContributorBase.java │ │ ├── GoSymbolContributor.java │ │ └── GoTypeContributor.java │ ├── highlighting/ │ │ ├── GoAnnotator.java │ │ ├── GoColorsAndFontsPage.java │ │ ├── GoHighlightingAnnotator.java │ │ ├── GoProblemFileHighlightFilter.java │ │ ├── GoSyntaxHighlighter.java │ │ ├── GoSyntaxHighlighterFactory.java │ │ ├── GoSyntaxHighlightingColors.java │ │ └── exitpoint/ │ │ ├── GoBreakStatementExitPointHandler.java │ │ ├── GoFunctionExitPointHandler.java │ │ └── GoHighlightExitPointsHandlerFactory.java │ ├── inspections/ │ │ ├── GoAddTrailingCommaInspection.java │ │ ├── GoAnonymousFieldDefinitionTypeInspection.java │ │ ├── GoAssignmentNilWithoutExplicitTypeInspection.java │ │ ├── GoAssignmentToReceiverInspection.java │ │ ├── GoBoolExpressionsInspection.java │ │ ├── GoCgoInTestInspection.java │ │ ├── GoCommentStartInspection.java │ │ ├── GoDeferGoInspection.java │ │ ├── GoDeferInLoopInspection.java │ │ ├── GoDirectAssignToStructFieldInMapInspection.java │ │ ├── GoDuplicateArgumentInspection.java │ │ ├── GoDuplicateFieldsOrMethodsInspection.java │ │ ├── GoDuplicateFunctionOrMethodInspection.java │ │ ├── GoDuplicateReturnArgumentInspection.java │ │ ├── GoEmbeddedInterfacePointerInspection.java │ │ ├── GoEmptyDeclarationInspection.java │ │ ├── GoExportedOwnDeclarationInspection.java │ │ ├── GoFileIgnoredByBuildToolNotificationProvider.java │ │ ├── GoFunctionCallInspection.java │ │ ├── GoFunctionVariadicParameterInspection.java │ │ ├── GoImportUsedAsNameInspection.java │ │ ├── GoInfiniteForInspection.java │ │ ├── GoInspectionBase.java │ │ ├── GoInspectionUtil.java │ │ ├── GoInvalidPackageImportInspection.java │ │ ├── GoInvalidStringOrCharInspection.java │ │ ├── GoMissingReturnInspection.java │ │ ├── GoMixedNamedUnnamedParametersInspection.java │ │ ├── GoMultiplePackagesInspection.java │ │ ├── GoNoNewVariablesInspection.java │ │ ├── GoPlaceholderChecker.java │ │ ├── GoPlaceholderCountInspection.java │ │ ├── GoRangeIterationOnIllegalTypeInspection.java │ │ ├── GoReceiverNamesInspection.java │ │ ├── GoRedeclareImportAsFunctionInspection.java │ │ ├── GoRedundantBlankArgInRangeInspection.java │ │ ├── GoRedundantSecondIndexInSlicesInspection.java │ │ ├── GoRedundantTypeDeclInCompositeLit.java │ │ ├── GoReservedWordUsedAsNameInspection.java │ │ ├── GoSelfImportInspection.java │ │ ├── GoSpellcheckingStrategy.java │ │ ├── GoStringAndByteTypeMismatchInspection.java │ │ ├── GoStructInitializationInspection.java │ │ ├── GoStructTagInspection.java │ │ ├── GoTestSignaturesInspection.java │ │ ├── GoUnderscoreUsedAsValueInspection.java │ │ ├── GoUnusedImportInspection.java │ │ ├── GoUsedAsValueInCondition.java │ │ ├── GoVarDeclarationInspection.java │ │ ├── WrongModuleTypeNotificationProvider.java │ │ ├── WrongSdkConfigurationNotificationProvider.java │ │ ├── suppression/ │ │ │ └── GoInspectionSuppressor.java │ │ └── unresolved/ │ │ ├── GoAssignmentToConstantInspection.java │ │ ├── GoIntroduceFunctionFix.java │ │ ├── GoIntroduceGlobalConstantFix.java │ │ ├── GoIntroduceGlobalVariableFix.java │ │ ├── GoIntroduceLocalConstantFix.java │ │ ├── GoIntroduceLocalVariableFix.java │ │ ├── GoIntroduceTypeFix.java │ │ ├── GoReplaceAssignmentWithDeclarationQuickFix.java │ │ ├── GoUnresolvedFixBase.java │ │ ├── GoUnresolvedReferenceInspection.java │ │ ├── GoUnusedConstInspection.java │ │ ├── GoUnusedExportedFunctionInspection.java │ │ ├── GoUnusedFunctionInspection.java │ │ ├── GoUnusedGlobalVariableInspection.java │ │ ├── GoUnusedLabelInspection.java │ │ ├── GoUnusedParameterInspection.java │ │ └── GoUnusedVariableInspection.java │ ├── intentions/ │ │ ├── GoAddFunctionBlockIntention.java │ │ └── GoMoveToStructInitializationIntention.java │ ├── lexer/ │ │ ├── GoLexer.java │ │ ├── gen_lexer.sh │ │ └── go.flex │ ├── marker/ │ │ └── GoRecursiveCallMarkerProvider.java │ ├── parser/ │ │ └── GoParserUtil.java │ ├── project/ │ │ ├── GoApplicationLibrariesService.java │ │ ├── GoBuildTargetSettings.java │ │ ├── GoExcludedPathsSettings.java │ │ ├── GoLibrariesService.java │ │ ├── GoModuleLibrariesInitializer.java │ │ ├── GoModuleLibrariesService.java │ │ ├── GoModuleSettings.java │ │ ├── GoProjectLibrariesService.java │ │ ├── GoProjectStructureDetector.java │ │ ├── GoVendoringUtil.java │ │ └── migration/ │ │ ├── GoBuildTagsSettingsConverterProvider.java │ │ └── GoProjectModelConverterProvider.java │ ├── psi/ │ │ ├── GoCaseClause.java │ │ ├── GoCompositeElement.java │ │ ├── GoCompositeElementType.java │ │ ├── GoFile.java │ │ ├── GoFunctionOrMethodDeclaration.java │ │ ├── GoNamedElement.java │ │ ├── GoNamedSignatureOwner.java │ │ ├── GoPsiTreeUtil.java │ │ ├── GoRecursiveVisitor.java │ │ ├── GoReferenceExpressionBase.java │ │ ├── GoSignatureOwner.java │ │ ├── GoTokenType.java │ │ ├── GoTopLevelDeclaration.java │ │ ├── GoTypeOwner.java │ │ └── impl/ │ │ ├── GoCType.java │ │ ├── GoCachedReference.java │ │ ├── GoCompositeElementImpl.java │ │ ├── GoElementFactory.java │ │ ├── GoExpressionUtil.java │ │ ├── GoFieldNameReference.java │ │ ├── GoFunctionOrMethodDeclarationImpl.java │ │ ├── GoLabelReference.java │ │ ├── GoLightType.java │ │ ├── GoNamedElementImpl.java │ │ ├── GoPsiImplUtil.java │ │ ├── GoReference.java │ │ ├── GoReferenceBase.java │ │ ├── GoScopeProcessor.java │ │ ├── GoScopeProcessorBase.java │ │ ├── GoStubbedElementImpl.java │ │ ├── GoTypeProcessor.java │ │ ├── GoTypeReference.java │ │ ├── GoTypeUtil.java │ │ ├── GoVarProcessor.java │ │ ├── GoVarReference.java │ │ ├── ResolveUtil.java │ │ ├── imports/ │ │ │ ├── GoImportReference.java │ │ │ ├── GoImportReferenceSet.java │ │ │ └── GoReferenceImporter.java │ │ └── manipulator/ │ │ ├── GoImportStringManipulator.java │ │ └── GoStringManipulator.java │ ├── quickfix/ │ │ ├── GoConvertStringToByteQuickFix.java │ │ ├── GoCreateWrapperTypeQuickFix.java │ │ ├── GoDeleteAmpersandAndTypeInCompositeLitQuickFix.java │ │ ├── GoDeleteConstDefinitionQuickFix.java │ │ ├── GoDeleteImportQuickFix.java │ │ ├── GoDeleteQuickFix.java │ │ ├── GoDeleteRangeQuickFix.java │ │ ├── GoDeleteVarDefinitionQuickFix.java │ │ ├── GoDisableVendoringInModuleQuickFix.java │ │ ├── GoEmptySignatureQuickFix.java │ │ ├── GoMultiplePackagesQuickFix.java │ │ ├── GoRenameQuickFix.java │ │ ├── GoRenameToBlankQuickFix.java │ │ ├── GoReplaceWithReturnStatementQuickFix.java │ │ ├── GoReplaceWithSelectStatementQuickFix.java │ │ └── GoSimplifyBoolExprQuickFix.java │ ├── refactor/ │ │ ├── GoAnonymousFieldProcessor.java │ │ ├── GoDescriptionProvider.java │ │ ├── GoIntroduceOperation.java │ │ ├── GoIntroduceVariableBase.java │ │ ├── GoIntroduceVariableDialog.java │ │ ├── GoIntroduceVariableHandler.java │ │ ├── GoRefactoringSupportProvider.java │ │ ├── GoRefactoringUtil.java │ │ └── GoRenameImportSpecProcessor.java │ ├── regexp/ │ │ ├── GoRegExpLanguage.java │ │ ├── GoRegExpParserDefinition.java │ │ ├── GoRegexHost.java │ │ └── GoRegexInjector.java │ ├── runconfig/ │ │ ├── GoBuildingRunner.java │ │ ├── GoConfigurationFactoryBase.java │ │ ├── GoConsoleFilter.java │ │ ├── GoModuleBasedConfiguration.java │ │ ├── GoRunConfigurationBase.java │ │ ├── GoRunConfigurationProducerBase.java │ │ ├── GoRunConfigurationWithMain.java │ │ ├── GoRunLineMarkerProvider.java │ │ ├── GoRunUtil.java │ │ ├── GoRunner.java │ │ ├── GoRunningState.java │ │ ├── application/ │ │ │ ├── GoApplicationConfiguration.java │ │ │ ├── GoApplicationRunConfigurationProducer.java │ │ │ ├── GoApplicationRunConfigurationType.java │ │ │ ├── GoApplicationRunningState.java │ │ │ └── GoNopProcessHandler.java │ │ ├── before/ │ │ │ ├── GoBeforeRunTaskProvider.java │ │ │ ├── GoCommandBeforeRunTask.java │ │ │ └── GoCommandConfigureDialog.java │ │ ├── file/ │ │ │ ├── GoRunFileConfiguration.java │ │ │ ├── GoRunFileConfigurationProducer.java │ │ │ ├── GoRunFileConfigurationType.java │ │ │ └── GoRunFileRunningState.java │ │ ├── testing/ │ │ │ ├── GoTestConfigurationFactoryBase.java │ │ │ ├── GoTestConsoleProperties.java │ │ │ ├── GoTestEventsConverterBase.java │ │ │ ├── GoTestFinder.java │ │ │ ├── GoTestFramework.java │ │ │ ├── GoTestFunctionType.java │ │ │ ├── GoTestLocator.java │ │ │ ├── GoTestRunConfiguration.java │ │ │ ├── GoTestRunConfigurationProducerBase.java │ │ │ ├── GoTestRunConfigurationType.java │ │ │ ├── GoTestRunLineMarkerProvider.java │ │ │ ├── GoTestRunningState.java │ │ │ ├── coverage/ │ │ │ │ ├── GoCoverageAnnotator.java │ │ │ │ ├── GoCoverageEnabledConfiguration.java │ │ │ │ ├── GoCoverageEngine.java │ │ │ │ ├── GoCoverageProgramRunner.java │ │ │ │ ├── GoCoverageProjectData.java │ │ │ │ ├── GoCoverageRunner.java │ │ │ │ └── GoCoverageSuite.java │ │ │ ├── frameworks/ │ │ │ │ ├── gobench/ │ │ │ │ │ ├── GobenchEventsConverter.java │ │ │ │ │ ├── GobenchFramework.java │ │ │ │ │ ├── GobenchRunConfigurationProducer.java │ │ │ │ │ └── GobenchRunningState.java │ │ │ │ ├── gocheck/ │ │ │ │ │ ├── GocheckEventsConverter.java │ │ │ │ │ ├── GocheckFramework.java │ │ │ │ │ ├── GocheckRunConfigurationProducer.java │ │ │ │ │ └── GocheckRunningState.java │ │ │ │ └── gotest/ │ │ │ │ ├── GoTestEventsConverterBaseImpl.java │ │ │ │ ├── GotestEventsConverter.java │ │ │ │ ├── GotestFramework.java │ │ │ │ ├── GotestGenerateAction.java │ │ │ │ └── GotestRunConfigurationProducer.java │ │ │ └── ui/ │ │ │ ├── GoPackageFieldCompletionProvider.java │ │ │ ├── GoTestRunConfigurationEditorForm.form │ │ │ └── GoTestRunConfigurationEditorForm.java │ │ └── ui/ │ │ ├── GoApplicationConfigurationEditorForm.form │ │ ├── GoApplicationConfigurationEditorForm.java │ │ ├── GoCommonSettingsPanel.form │ │ ├── GoCommonSettingsPanel.java │ │ ├── GoRunFileConfigurationEditorForm.form │ │ └── GoRunFileConfigurationEditorForm.java │ ├── sdk/ │ │ ├── GoEnvironmentGoPathModificationTracker.java │ │ ├── GoIdeaSdkService.java │ │ ├── GoPackageUtil.java │ │ ├── GoSdkLibraryPresentationProvider.java │ │ ├── GoSdkService.java │ │ ├── GoSdkType.java │ │ ├── GoSdkUtil.java │ │ └── GoSmallIDEsSdkService.java │ ├── stubs/ │ │ ├── GoAnonymousFieldDefinitionStub.java │ │ ├── GoConstDefinitionStub.java │ │ ├── GoConstSpecStub.java │ │ ├── GoElementTypeFactory.java │ │ ├── GoFieldDefinitionStub.java │ │ ├── GoFileStub.java │ │ ├── GoFunctionDeclarationStub.java │ │ ├── GoFunctionOrMethodDeclarationStub.java │ │ ├── GoImportSpecStub.java │ │ ├── GoLabelDefinitionStub.java │ │ ├── GoMethodDeclarationStub.java │ │ ├── GoMethodSpecStub.java │ │ ├── GoNamedStub.java │ │ ├── GoPackageClauseStub.java │ │ ├── GoParamDefinitionStub.java │ │ ├── GoParameterDeclarationStub.java │ │ ├── GoParametersStub.java │ │ ├── GoReceiverStub.java │ │ ├── GoResultStub.java │ │ ├── GoSignatureStub.java │ │ ├── GoTypeSpecStub.java │ │ ├── GoTypeStub.java │ │ ├── GoVarDefinitionStub.java │ │ ├── GoVarSpecStub.java │ │ ├── StubWithText.java │ │ ├── TextHolder.java │ │ ├── index/ │ │ │ ├── GoAllPrivateNamesIndex.java │ │ │ ├── GoAllPublicNamesIndex.java │ │ │ ├── GoFunctionIndex.java │ │ │ ├── GoIdFilter.java │ │ │ ├── GoMethodFingerprintIndex.java │ │ │ ├── GoMethodIndex.java │ │ │ ├── GoPackagesIndex.java │ │ │ └── GoTypesIndex.java │ │ └── types/ │ │ ├── GoAnonymousFieldDefinitionStubElementType.java │ │ ├── GoConstDefinitionStubElementType.java │ │ ├── GoConstSpecStubElementType.java │ │ ├── GoFieldDefinitionStubElementType.java │ │ ├── GoFunctionDeclarationStubElementType.java │ │ ├── GoImportSpecStubElementType.java │ │ ├── GoLabelDefinitionStubElementType.java │ │ ├── GoMethodDeclarationStubElementType.java │ │ ├── GoMethodSpecStubElementType.java │ │ ├── GoNamedStubElementType.java │ │ ├── GoPackageClauseStubElementType.java │ │ ├── GoParamDefinitionStubElementType.java │ │ ├── GoParameterDeclarationStubElementType.java │ │ ├── GoParametersStubElementType.java │ │ ├── GoReceiverStubElementType.java │ │ ├── GoResultStubElementType.java │ │ ├── GoSignatureStubElementType.java │ │ ├── GoStubElementType.java │ │ ├── GoTypeSpecStubElementType.java │ │ ├── GoTypeStubElementType.java │ │ ├── GoVarDefinitionStubElementType.java │ │ └── GoVarSpecStubElementType.java │ ├── template/ │ │ ├── GoEverywhereContextType.java │ │ ├── GoFieldNameMacro.java │ │ ├── GoLiveTemplateContextType.java │ │ └── GoLiveTemplatesProvider.java │ ├── tree/ │ │ ├── ExportabilityComparator.java │ │ ├── ExportabilitySorter.java │ │ ├── GoPrivateMembersFilter.java │ │ └── GoStructureViewFactory.java │ ├── ui/ │ │ └── ProjectTutorialNotification.java │ ├── usages/ │ │ ├── GoFileStructureGroupRuleProvider.java │ │ ├── GoFindUsagesProvider.java │ │ └── GoReadWriteAccessDetector.java │ └── util/ │ ├── GoBuildMatcher.java │ ├── GoExecutor.java │ ├── GoHistoryProcessListener.java │ ├── GoPathResolveScope.java │ ├── GoPathScopeHelper.java │ ├── GoPathUseScope.java │ ├── GoStringLiteralEscaper.java │ ├── GoTargetSystem.java │ └── GoUtil.java ├── testData/ │ ├── colorHighlighting/ │ │ ├── builtinFunctions.go │ │ ├── funcAndMethod.go │ │ ├── label.go │ │ ├── octAndHex.go │ │ ├── receiver.go │ │ ├── simple.go │ │ ├── structFields.go │ │ └── types.go │ ├── completion/ │ │ ├── addSpaceAfterKeyword.go │ │ ├── addSpaceAfterKeyword_after.go │ │ ├── blockKeywords.go │ │ ├── blockKeywordsInsideCaseStatement.go │ │ ├── blockKeywordsInsideOneLineFunction.go │ │ ├── chanKeyword.go │ │ ├── chanKeyword_2.go │ │ ├── chanKeyword_2_after.go │ │ ├── chanKeyword_3.go │ │ ├── chanKeyword_3_after.go │ │ ├── chanKeyword_after.go │ │ ├── doNotCompleteKeywordsInsideConstSpec.go │ │ ├── doNotCompleteKeywordsInsideSelectorExpression.go │ │ ├── doNotRunAutoImportCompletionAfterDot.go │ │ ├── doNotRunAutoImportCompletionAfterDotAndSpace.go │ │ ├── doNotRunAutoImportCompletionAfterDotAndSpace_after.go │ │ ├── doNotRunAutoImportCompletionAfterDot_after.go │ │ ├── elseKeyword.go │ │ ├── elseKeywordRegression.go │ │ ├── elseKeyword_after.go │ │ ├── expressionCaseKeywordCompletion.go │ │ ├── expressionCaseKeywordCompletion_after.go │ │ ├── expressionDefaultKeywordCompletion.go │ │ ├── expressionDefaultKeywordCompletion_after.go │ │ ├── expressionKeywords.go │ │ ├── forStatementKeywords.go │ │ ├── forStatementKeywordsDoNotInsertSpace.go │ │ ├── forStatementKeywordsDoNotInsertSpace_after.go │ │ ├── forStatementKeywordsInsideFuncLit.go │ │ ├── functionAsFunctionArgument.go │ │ ├── functionAsFunctionArgument_after.go │ │ ├── functionAsVariableValue.go │ │ ├── functionAsVariableValue_after.go │ │ ├── functionInDefer.go │ │ ├── functionInDefer_after.go │ │ ├── functionInGo.go │ │ ├── functionInGo_after.go │ │ ├── ifKeywordAfterElse.go │ │ ├── ifKeywordAfterElse_after.go │ │ ├── interfaceKeywordAsFunctionParameter.go │ │ ├── interfaceKeywordAsFunctionParameter_after.go │ │ ├── localFunctionInDifferentFiles.go │ │ ├── localFunctionInDifferentFiles_after.go │ │ ├── localFunctionInDifferentFiles_context.go │ │ ├── mapKeyword.go │ │ ├── mapKeywordInsertHandler.go │ │ ├── mapKeywordInsertHandlerDoNotInsertBrackets.go │ │ ├── mapKeywordInsertHandlerDoNotInsertBrackets_after.go │ │ ├── mapKeywordInsertHandler_after.go │ │ ├── mapKeyword_2.go │ │ ├── mapKeyword_2_after.go │ │ ├── mapKeyword_after.go │ │ ├── packageKeyword.go │ │ ├── packageKeywordInEmptyFile.go │ │ ├── packageKeywordInEmptyFile_after.go │ │ ├── packageKeyword_after.go │ │ ├── rangeKeyword_1.go │ │ ├── rangeKeyword_1_after.go │ │ ├── rangeKeyword_2.go │ │ ├── rangeKeyword_2_after.go │ │ ├── rangeKeyword_3.go │ │ ├── rangeKeyword_3_after.go │ │ ├── selectKeywordInsertHandler.go │ │ ├── selectKeywordInsertHandler_after.go │ │ ├── structKeywordAsFunctionParameter.go │ │ ├── structKeywordAsFunctionParameter_after.go │ │ ├── topLevelKeywords.go │ │ ├── topLevelKeywords_2.go │ │ ├── typeCaseKeywordCompletion.go │ │ ├── typeCaseKeywordCompletion_after.go │ │ ├── typeDefaultKeywordCompletion.go │ │ ├── typeDefaultKeywordCompletion_after.go │ │ ├── typeKeywordDoNotInsertBraces.go │ │ ├── typeKeywordDoNotInsertBraces_after.go │ │ ├── typeKeywordInsertBraces.go │ │ ├── typeKeywordInsertBraces_after.go │ │ ├── typeKeywords.go │ │ └── typeKeywordsInsideParentheses.go │ ├── coverage/ │ │ ├── coverage.out │ │ └── coverage_for_merge.out │ ├── doc/ │ │ ├── commentEndsWithIndentedBlock_after.txt │ │ ├── commentEndsWithIndentedBlock_source.txt │ │ ├── constants.go │ │ ├── constants.txt │ │ ├── escape.go │ │ ├── escape.txt │ │ ├── escapeReturnValues.go │ │ ├── escapeReturnValues.txt │ │ ├── fieldDeclaration.go │ │ ├── fieldDeclaration.txt │ │ ├── fprintln.go │ │ ├── fprintln.txt │ │ ├── functionType.go │ │ ├── functionType.txt │ │ ├── indentedBlock_after.txt │ │ ├── indentedBlock_source.txt │ │ ├── links_after.txt │ │ ├── links_source.txt │ │ ├── method.go │ │ ├── method.txt │ │ ├── multiBlockDoc_after.txt │ │ ├── multiBlockDoc_source.txt │ │ ├── multilineTypeListDefinition.go │ │ ├── multilineTypeListDefinition.txt │ │ ├── multilineVariable_1.go │ │ ├── multilineVariable_1.txt │ │ ├── multilineVariable_2.go │ │ ├── multilineVariable_2.txt │ │ ├── multilineVariable_3.go │ │ ├── multilineVariable_3.txt │ │ ├── multilineVariable_4.go │ │ ├── multilineVariable_4.txt │ │ ├── multilineVariable_5.go │ │ ├── multilineVariable_5.txt │ │ ├── package.go │ │ ├── package.txt │ │ ├── packageOnImportAlias.go │ │ ├── packageOnImportAlias.txt │ │ ├── packageOnQualifier.go │ │ ├── packageOnQualifier.txt │ │ ├── packageWithDoc.go │ │ ├── packageWithDoc.txt │ │ ├── parameter.go │ │ ├── parameter.txt │ │ ├── pointer.go │ │ ├── pointer.txt │ │ ├── println.go │ │ ├── println.txt │ │ ├── quotedStrings_after.txt │ │ ├── quotedStrings_source.txt │ │ ├── receiver.go │ │ ├── receiver.txt │ │ ├── resultParameter.go │ │ ├── resultParameter.txt │ │ ├── signature.go │ │ ├── signature.txt │ │ ├── specType.go │ │ ├── specType.txt │ │ ├── struct.go │ │ ├── struct.txt │ │ ├── structWithAnon.go │ │ ├── structWithAnon.txt │ │ ├── typeInnerDefinitionWithoutComment.go │ │ ├── typeInnerDefinitionWithoutComment.txt │ │ ├── typeResultDefinition.go │ │ ├── typeResultDefinition.txt │ │ ├── typeSpec.go │ │ ├── typeSpec.txt │ │ ├── typeTopDefinition.go │ │ ├── typeTopDefinition.txt │ │ ├── varShortDefinition.go │ │ ├── varShortDefinition.txt │ │ ├── variable.go │ │ ├── variable.txt │ │ ├── variableInSwitch.go │ │ └── variableInSwitch.txt │ ├── editor/ │ │ └── statement-mover/ │ │ ├── anonymousFunction-afterDown.go │ │ ├── anonymousFunction-afterUp.go │ │ ├── anonymousFunction.go │ │ ├── anonymousFunctionAtAssignment-afterDown.go │ │ ├── anonymousFunctionAtAssignment-afterUp.go │ │ ├── anonymousFunctionAtAssignment.go │ │ ├── functionDeclaration-afterDown.go │ │ ├── functionDeclaration-afterUp.go │ │ ├── functionDeclaration.go │ │ ├── functionDeclarationWithFewTopLevelDeclarations-afterUp.go │ │ ├── functionDeclarationWithFewTopLevelDeclarations.go │ │ ├── functionDeclarationWithFewTopLevelDeclarationsDown-afterDown.go │ │ ├── functionDeclarationWithFewTopLevelDeclarationsDown.go │ │ ├── import-afterUp.go │ │ ├── import.go │ │ ├── importDown-afterDown.go │ │ ├── importDown.go │ │ ├── importWithCaretAtImportString-afterDown.go │ │ ├── importWithCaretAtImportString-afterUp.go │ │ ├── importWithCaretAtImportString.go │ │ ├── importWithCaretAtLastImport-afterUp.go │ │ ├── importWithCaretAtLastImport.go │ │ ├── insertedStatement-afterUp.go │ │ ├── insertedStatement.go │ │ ├── insertedStatementDown-afterDown.go │ │ ├── insertedStatementDown.go │ │ ├── package-afterDown.go │ │ ├── package-afterUp.go │ │ ├── package.go │ │ ├── simpleStatement-afterDown.go │ │ ├── simpleStatement-afterUp.go │ │ ├── simpleStatement.go │ │ ├── statementInEndOfBlock-afterDown.go │ │ ├── statementInEndOfBlock-afterUp.go │ │ ├── statementInEndOfBlock.go │ │ ├── twoFunc-afterDown.go │ │ ├── twoFunc-afterUp.go │ │ ├── twoFunc.go │ │ ├── twoStatements-afterUp.go │ │ ├── twoStatements.go │ │ ├── twoStatementsDown-afterDown.go │ │ ├── twoStatementsDown.go │ │ ├── varSpecTopLevelDeclaration-afterDown.go │ │ └── varSpecTopLevelDeclaration.go │ ├── folding/ │ │ ├── compositeLiteral.go │ │ ├── constDeclaration.go │ │ ├── emptyImportList.go │ │ ├── forStatement.go │ │ ├── ifStatement.go │ │ ├── importList.go │ │ ├── importListWithJustSingleImportKeyword.go │ │ ├── importListWithNewLineAfterKeyword.go │ │ ├── importListWithOnlyThreeSymbolsToFold.go │ │ ├── importListWithoutSpaceBetweenKeywordAndParen.go │ │ ├── importListWithoutSpaceBetweenKeywordAndString.go │ │ ├── simple.go │ │ ├── switchSelectCaseStatement.go │ │ ├── typeDeclaration.go │ │ ├── typeSwitchStatement.go │ │ └── varDeclaration.go │ ├── formatting/ │ │ ├── breakLines-after.go │ │ ├── breakLines.go │ │ ├── case2Enter-after.go │ │ ├── case2Enter.go │ │ ├── caseE-after.go │ │ ├── caseE.go │ │ ├── caseEnter-after.go │ │ ├── caseEnter.go │ │ ├── commentIndentation-after.go │ │ ├── commentIndentation.go │ │ ├── constDeclaration-after.go │ │ ├── constDeclaration.go │ │ ├── elseStatement-after.go │ │ ├── elseStatement.go │ │ ├── emptyStatementInForClause-after.go │ │ ├── emptyStatementInForClause.go │ │ ├── expressionsContinuationIndent-after.go │ │ ├── expressionsContinuationIndent.go │ │ ├── simple-after.go │ │ ├── simple.go │ │ ├── spacesInArithmeticExpressions-after.go │ │ ├── spacesInArithmeticExpressions.go │ │ ├── switchEnter-after.go │ │ ├── switchEnter.go │ │ ├── typeEnter-after.go │ │ ├── typeEnter.go │ │ ├── varDeclaration-after.go │ │ └── varDeclaration.go │ ├── highlighting/ │ │ ├── anonymousFieldDefinition.go │ │ ├── assignToStructFieldInMap.go │ │ ├── assignUsages.go │ │ ├── assignmentToReceiver.go │ │ ├── avoidDuplicatedUnusedImportReports.go │ │ ├── backticks.go │ │ ├── blankFields.go │ │ ├── blankImport.go │ │ ├── boxes.go │ │ ├── break.go │ │ ├── builtinFuncCalls.go │ │ ├── cgotest.go │ │ ├── chan.go │ │ ├── check.go │ │ ├── checkSamePackage_test.go │ │ ├── check_test.go │ │ ├── commentStart.go │ │ ├── composite.go │ │ ├── consts.go │ │ ├── continue.go │ │ ├── cyclicDefinition.go │ │ ├── deferGo.go │ │ ├── deferInLoop.go │ │ ├── doNotReportNonLastMultiResolvedImport.go │ │ ├── embeddedInterfacePointer.go │ │ ├── equalinif.go │ │ ├── exportedOwnDeclaration.go │ │ ├── fields.go │ │ ├── fileRead.go │ │ ├── forRange.go │ │ ├── funcCall.go │ │ ├── funcLiteral.go │ │ ├── funcType.go │ │ ├── functionTypes.go │ │ ├── gh2147.go │ │ ├── githubIssue2099.go │ │ ├── importIgnoringDirectories.go │ │ ├── importUsedAsName.go │ │ ├── indexedStringAssign.go │ │ ├── infiniteFor.go │ │ ├── init.go │ │ ├── innerTypesFromTestDataPackage.go │ │ ├── interfaces.go │ │ ├── iota.go │ │ ├── iota2.go │ │ ├── labels.go │ │ ├── literalValues.go │ │ ├── mainWithWrongSignature.go │ │ ├── methodExpr.go │ │ ├── methodOnNonLocalType.go │ │ ├── mismatch.go │ │ ├── mixedNamedUnnamedParameters.go │ │ ├── nil.go │ │ ├── placeholderCount.go │ │ ├── placeholderCountVet.go │ │ ├── pointers.go │ │ ├── rangeIterationOnIllegalType.go │ │ ├── ranges.go │ │ ├── receiverType.go │ │ ├── recv.go │ │ ├── redeclaredImportAsFunction.go │ │ ├── relativeImportIgnoringDirectories.go │ │ ├── request.go │ │ ├── reservedWordUsedAsName.go │ │ ├── returns.go │ │ ├── selector.go │ │ ├── shortVars.go │ │ ├── simple.go │ │ ├── sliceWithThirdIndex.go │ │ ├── slices.go │ │ ├── specTypes.go │ │ ├── stop.go │ │ ├── stringInStructSliceWithThirdIndex.go │ │ ├── stringIndexIsByte.go │ │ ├── stringSliceWithThirdIndex.go │ │ ├── struct.go │ │ ├── structTags.go │ │ ├── stubParams.go │ │ ├── templates.go │ │ ├── typeConversion.go │ │ ├── typeLiterals.go │ │ ├── unaryMinus.go │ │ ├── unaryPointer.go │ │ ├── underscoreUsedAsValue.go │ │ ├── unusedParameter.go │ │ ├── unusedParameter_test.go │ │ ├── varBlocks.go │ │ ├── varToImport.go │ │ ├── variadic.go │ │ ├── vars.go │ │ ├── vendoringImportPaths.go │ │ └── voidFunctionUsedAsValue.go │ ├── imports/ │ │ └── optimize/ │ │ ├── doNotOptimizeSideEffectImports.go │ │ ├── doNotOptimizeSideEffectImports_after.go │ │ ├── duplicatedImportsWithDifferentString.go │ │ ├── duplicatedImportsWithDifferentString_after.go │ │ ├── duplicatedImportsWithSameString.go │ │ ├── duplicatedImportsWithSameStringAndDifferentQuotes.go │ │ ├── duplicatedImportsWithSameStringAndDifferentQuotes_after.go │ │ ├── duplicatedImportsWithSameString_after.go │ │ ├── importDirectoryWithoutPackages.go │ │ ├── importDirectoryWithoutPackages_after.go │ │ ├── importPackageWithMainFiles.go │ │ ├── importPackageWithMainFiles_after.go │ │ ├── importWithMultiplePackages.go │ │ ├── importWithMultiplePackages_after.go │ │ ├── importWithSameIdentifier.go │ │ ├── importWithSameIdentifier_after.go │ │ ├── redundantImportQualifier.go │ │ ├── redundantImportQualifier_after.go │ │ ├── unusedDuplicatedImports.go │ │ ├── unusedDuplicatedImports_after.go │ │ ├── unusedImplicitImports.go │ │ ├── unusedImplicitImports_after.go │ │ ├── unusedImports.go │ │ ├── unusedImportsQuickFix.go │ │ ├── unusedImportsQuickFix_after.go │ │ ├── unusedImportsWithBacktick.go │ │ ├── unusedImportsWithBacktick_after.go │ │ ├── unusedImportsWithSemicolon.go │ │ ├── unusedImportsWithSemicolon_after.go │ │ ├── unusedImports_after.go │ │ ├── usedDuplicatedImports.go │ │ ├── usedDuplicatedImports_after.go │ │ ├── usedImplicitImports.go │ │ └── usedImplicitImports_after.go │ ├── inspections/ │ │ ├── anon-field/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── go-defer-function-call/ │ │ │ ├── conversions.go │ │ │ ├── deferRecover-after.go │ │ │ ├── deferRecover.go │ │ │ ├── funcLiteral-after.go │ │ │ ├── funcLiteral.go │ │ │ ├── literal.go │ │ │ ├── parens-after.go │ │ │ ├── parens.go │ │ │ ├── parensFunctionType-after.go │ │ │ ├── parensFunctionType.go │ │ │ ├── twiceParens-after.go │ │ │ ├── twiceParens.go │ │ │ └── valid.go │ │ ├── go-empty-declaration/ │ │ │ ├── constVoidDeclaration-after.go │ │ │ ├── constVoidDeclaration.go │ │ │ ├── importVoidDeclarationWithUpperComment.go │ │ │ ├── notVoidImportDeclaration.go │ │ │ ├── twoVoidImportsWithOneComment-after.go │ │ │ ├── twoVoidImportsWithOneComment.go │ │ │ ├── typeVoidDeclaration-after.go │ │ │ ├── typeVoidDeclaration.go │ │ │ ├── varVoidDeclarationInFunction.go │ │ │ ├── varVoidDeclarationNotInFunction-after.go │ │ │ ├── varVoidDeclarationNotInFunction.go │ │ │ └── varVoidDeclarationWithInnerComment.go │ │ ├── go-simplify/ │ │ │ ├── compositeLitWithArrays-after.go │ │ │ ├── compositeLitWithArrays.go │ │ │ ├── compositeLitWithArraysInBrackets.go │ │ │ ├── compositeLitWithInsertedArrays-after.go │ │ │ ├── compositeLitWithInsertedArrays.go │ │ │ ├── compositeLitWithInterface.go │ │ │ ├── compositeLitWithKeysAndSimpleRedundantTypeDecl-after.go │ │ │ ├── compositeLitWithKeysAndSimpleRedundantTypeDecl.go │ │ │ ├── compositeLitWithMap-after.go │ │ │ ├── compositeLitWithMap.go │ │ │ ├── compositeLitWithMapOfStruct-after.go │ │ │ ├── compositeLitWithMapOfStruct.go │ │ │ ├── compositeLitWithMapWithPointerAndStruct-after.go │ │ │ ├── compositeLitWithMapWithPointerAndStruct.go │ │ │ ├── compositeLitWithOneSimpleRedundantTypeDecl-after.go │ │ │ ├── compositeLitWithOneSimpleRedundantTypeDecl.go │ │ │ ├── compositeLitWithPointerAndStructAndInsertedElement-after.go │ │ │ ├── compositeLitWithPointerAndStructAndInsertedElement.go │ │ │ ├── compositeLitWithPointers-after.go │ │ │ ├── compositeLitWithPointers.go │ │ │ ├── compositeLitWithPointersNoFix.go │ │ │ ├── compositeLitWithStruct-after.go │ │ │ ├── compositeLitWithStruct.go │ │ │ ├── compositeLitWithTwoDimensionalArray-after.go │ │ │ ├── compositeLitWithTwoDimensionalArray.go │ │ │ ├── rangeSimplifyWithOneArg.go │ │ │ ├── rangeSimplifyWithOneBlankAndOneNotBlankArgs.go │ │ │ ├── rangeSimplifyWithOneBlankArg-after.go │ │ │ ├── rangeSimplifyWithOneBlankArg.go │ │ │ ├── rangeSimplifyWithOneNotBlankAndOneBlankArgs-after.go │ │ │ ├── rangeSimplifyWithOneNotBlankAndOneBlankArgs.go │ │ │ ├── rangeSimplifyWithTwoArgs.go │ │ │ ├── rangeSimplifyWithTwoBlankArgs-after.go │ │ │ ├── rangeSimplifyWithTwoBlankArgs.go │ │ │ ├── rangeSimplifyWithVarAssign-after.go │ │ │ ├── rangeSimplifyWithVarAssign.go │ │ │ ├── slice-after.go │ │ │ ├── slice.go │ │ │ ├── sliceWithLenAnotherArray.go │ │ │ ├── sliceWithOnlySecondIndex-after.go │ │ │ ├── sliceWithOnlySecondIndex.go │ │ │ ├── sliceWithRedeclaredLen.go │ │ │ ├── sliceWithStructIndex.go │ │ │ └── sliceWithThreeIndexes.go │ │ ├── go-struct-initialization/ │ │ │ ├── quickFix-after.go │ │ │ ├── quickFix.go │ │ │ ├── uninitializedStructImportedOnly.go │ │ │ └── uninitializedStructWithLocal.go │ │ ├── suppression/ │ │ │ └── fix/ │ │ │ ├── commClauseStatementSuppressionFix-after-highlighting.go │ │ │ ├── commClauseStatementSuppressionFix-after.go │ │ │ ├── commClauseStatementSuppressionFix.go │ │ │ ├── firstImportStatement-after-highlighting.go │ │ │ ├── firstImportStatement-after.go │ │ │ ├── firstImportStatement.go │ │ │ ├── functionAllSuppressionFix-after-highlighting.go │ │ │ ├── functionAllSuppressionFix-after.go │ │ │ ├── functionAllSuppressionFix.go │ │ │ ├── functionAllSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── functionAllSuppressionFixWithExistingComment-after.go │ │ │ ├── functionAllSuppressionFixWithExistingComment.go │ │ │ ├── functionSuppressionFix-after-highlighting.go │ │ │ ├── functionSuppressionFix-after.go │ │ │ ├── functionSuppressionFix.go │ │ │ ├── functionSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── functionSuppressionFixWithExistingComment-after.go │ │ │ ├── functionSuppressionFixWithExistingComment.go │ │ │ ├── importStatement-after-highlighting.go │ │ │ ├── importStatement-after.go │ │ │ ├── importStatement.go │ │ │ ├── innerVariableDeclarationSuppressionFix.go │ │ │ ├── innerVariableDeclarationSuppressionFix2-after-highlighting.go │ │ │ ├── innerVariableDeclarationSuppressionFix2-after.go │ │ │ ├── innerVariableDeclarationSuppressionFix2.go │ │ │ ├── innerVariableDeclarationSuppressionFix3-after-highlighting.go │ │ │ ├── innerVariableDeclarationSuppressionFix3-after.go │ │ │ ├── innerVariableDeclarationSuppressionFix3.go │ │ │ ├── packageClause-after-highlighting.go │ │ │ ├── packageClause-after.go │ │ │ ├── packageClause.go │ │ │ ├── packageClauseSuppressAll-after-highlighting.go │ │ │ ├── packageClauseSuppressAll-after.go │ │ │ ├── packageClauseSuppressAll.go │ │ │ ├── selectCaseAllSuppressionFix-after-highlighting.go │ │ │ ├── selectCaseAllSuppressionFix-after.go │ │ │ ├── selectCaseAllSuppressionFix.go │ │ │ ├── selectCaseAllSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── selectCaseAllSuppressionFixWithExistingComment-after.go │ │ │ ├── selectCaseAllSuppressionFixWithExistingComment.go │ │ │ ├── selectCaseSuppressionFix-after-highlighting.go │ │ │ ├── selectCaseSuppressionFix-after.go │ │ │ ├── selectCaseSuppressionFix.go │ │ │ ├── selectCaseSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── selectCaseSuppressionFixWithExistingComment-after.go │ │ │ ├── selectCaseSuppressionFixWithExistingComment.go │ │ │ ├── statementAllSuppressionFix-after-highlighting.go │ │ │ ├── statementAllSuppressionFix-after.go │ │ │ ├── statementAllSuppressionFix.go │ │ │ ├── statementAllSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── statementAllSuppressionFixWithExistingComment-after.go │ │ │ ├── statementAllSuppressionFixWithExistingComment.go │ │ │ ├── statementSuppressionFix-after-highlighting.go │ │ │ ├── statementSuppressionFix-after.go │ │ │ ├── statementSuppressionFix.go │ │ │ ├── statementSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── statementSuppressionFixWithExistingComment-after.go │ │ │ ├── statementSuppressionFixWithExistingComment.go │ │ │ ├── suppressedNestedSelect.go │ │ │ ├── switchCaseAllSuppressionFix-after-highlighting.go │ │ │ ├── switchCaseAllSuppressionFix-after.go │ │ │ ├── switchCaseAllSuppressionFix.go │ │ │ ├── switchCaseAllSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── switchCaseAllSuppressionFixWithExistingComment-after.go │ │ │ ├── switchCaseAllSuppressionFixWithExistingComment.go │ │ │ ├── switchCaseSuppressionFix-after-highlighting.go │ │ │ ├── switchCaseSuppressionFix-after.go │ │ │ ├── switchCaseSuppressionFix.go │ │ │ ├── switchCaseSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── switchCaseSuppressionFixWithExistingComment-after.go │ │ │ ├── switchCaseSuppressionFixWithExistingComment.go │ │ │ ├── variableDeclarationAllSuppressionFix-after-highlighting.go │ │ │ ├── variableDeclarationAllSuppressionFix-after.go │ │ │ ├── variableDeclarationAllSuppressionFix.go │ │ │ ├── variableDeclarationAllSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── variableDeclarationAllSuppressionFixWithExistingComment-after.go │ │ │ ├── variableDeclarationAllSuppressionFixWithExistingComment.go │ │ │ ├── variableDeclarationSuppressionFix-after-highlighting.go │ │ │ ├── variableDeclarationSuppressionFix-after.go │ │ │ ├── variableDeclarationSuppressionFix.go │ │ │ ├── variableDeclarationSuppressionFixWithExistingComment-after-highlighting.go │ │ │ ├── variableDeclarationSuppressionFixWithExistingComment-after.go │ │ │ └── variableDeclarationSuppressionFixWithExistingComment.go │ │ ├── test-signatures/ │ │ │ ├── benchmark_test-after.go │ │ │ ├── benchmark_test.go │ │ │ ├── exampleNonEmptySignature_test-after.go │ │ │ ├── exampleNonEmptySignature_test.go │ │ │ ├── exampleWithReturnValue_test-after.go │ │ │ ├── exampleWithReturnValue_test.go │ │ │ ├── testLocalTestingImport_test-after.go │ │ │ ├── testLocalTestingImport_test.go │ │ │ ├── testMain_test-after.go │ │ │ ├── testMain_test.go │ │ │ ├── testNoTestingImport_test-after.go │ │ │ ├── testNoTestingImport_test.go │ │ │ ├── testWithReturnValue_test-after.go │ │ │ ├── testWithReturnValue_test.go │ │ │ ├── testWrongTestingAlias_test-after.go │ │ │ └── testWrongTestingAlias_test.go │ │ └── unused-label/ │ │ ├── deleteLabelFix-after.go │ │ ├── deleteLabelFix.go │ │ ├── renameToBlankFix-after.go │ │ ├── renameToBlankFix.go │ │ └── simple.go │ ├── intentions/ │ │ ├── add-missing-body/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ └── move-to-struct-initialization/ │ │ ├── anonymousField-after.go │ │ ├── anonymousField.go │ │ ├── caretAtValue-after.go │ │ ├── caretAtValue.go │ │ ├── duplicateFields-after.go │ │ ├── duplicateFields.go │ │ ├── existingDeclaration.go │ │ ├── existingField-after.go │ │ ├── existingField.go │ │ ├── fieldExchange-after.go │ │ ├── fieldExchange.go │ │ ├── fieldExtractedFromParens-after.go │ │ ├── fieldExtractedFromParens.go │ │ ├── invalidAssignment-after.go │ │ ├── invalidAssignment.go │ │ ├── justAssignedFieldParens.go │ │ ├── justAssignedVar-after.go │ │ ├── justAssignedVar.go │ │ ├── justAssignedVarBothParens.go │ │ ├── justAssignedVarWrongCaret.go │ │ ├── justAssignedVarWrongCaretWithParens.go │ │ ├── justInitializedVar-after.go │ │ ├── justInitializedVar.go │ │ ├── justInitializedVarWrongCaret.go │ │ ├── multiReturnFunction.go │ │ ├── multipleAssignmentsLeftmost-after.go │ │ ├── multipleAssignmentsLeftmost.go │ │ ├── multipleAssignmentsMiddle-after.go │ │ ├── multipleAssignmentsMiddle.go │ │ ├── multipleAssignmentsRightmost-after.go │ │ ├── multipleAssignmentsRightmost.go │ │ ├── multipleFields-after.go │ │ ├── multipleFields.go │ │ ├── multipleFieldsPartlyAssigned-after.go │ │ ├── multipleFieldsPartlyAssigned.go │ │ ├── multipleFieldsSameStructureCaretAtValue-after.go │ │ ├── multipleFieldsSameStructureCaretAtValue.go │ │ ├── notExistingField.go │ │ ├── oneLineFieldDeclaration-after.go │ │ ├── oneLineFieldDeclaration.go │ │ ├── simple-after.go │ │ ├── simple.go │ │ ├── structAssignment-after.go │ │ ├── structAssignment.go │ │ ├── structAssignmentMultipleAssignee-after.go │ │ ├── structAssignmentMultipleAssignee.go │ │ ├── twoSameStructures-after.go │ │ ├── twoSameStructures.go │ │ ├── twoSameStructuresAssignment-after.go │ │ ├── twoSameStructuresAssignment.go │ │ ├── withParens-after.go │ │ ├── withParens.go │ │ └── wrongStruct.go │ ├── lexer/ │ │ ├── basicTypes.go │ │ ├── basicTypes.txt │ │ ├── constants.go │ │ ├── constants.txt │ │ ├── couldNotMatch.go │ │ ├── couldNotMatch.txt │ │ ├── escapedQuote.go │ │ ├── escapedQuote.txt │ │ ├── for.go │ │ ├── for.txt │ │ ├── functionArguments.go │ │ ├── functionArguments.txt │ │ ├── helloWorld.go │ │ ├── helloWorld.txt │ │ ├── if.go │ │ ├── if.txt │ │ ├── imports.go │ │ ├── imports.txt │ │ ├── multipleResult.go │ │ ├── multipleResult.txt │ │ ├── namedResult.go │ │ ├── namedResult.txt │ │ ├── pointers.go │ │ ├── pointers.txt │ │ ├── rangeFor.go │ │ ├── rangeFor.txt │ │ ├── slices.go │ │ ├── slices.txt │ │ ├── structs.go │ │ ├── structs.txt │ │ ├── utf16.go │ │ ├── utf16.txt │ │ ├── variables.go │ │ └── variables.txt │ ├── marker/ │ │ ├── Go.go │ │ └── Recursive.go │ ├── mockSdk-1.1.2/ │ │ └── src/ │ │ └── pkg/ │ │ ├── bufio/ │ │ │ └── scan.go │ │ ├── builtin/ │ │ │ └── builtin.go │ │ ├── dirName/ │ │ │ ├── doesNotMatchDirectory.go │ │ │ └── packageMatchesDirectory.go │ │ ├── doc/ │ │ │ ├── dirs.go │ │ │ ├── doc_test.go │ │ │ ├── main.go │ │ │ ├── pkg.go │ │ │ └── testdata/ │ │ │ └── pkg.go │ │ ├── docs/ │ │ │ └── docs.go │ │ ├── emptyDirectory/ │ │ │ └── .doNotDelete │ │ ├── fmt/ │ │ │ ├── doc.go │ │ │ ├── format.go │ │ │ ├── print.go │ │ │ ├── scan.go │ │ │ └── stringer_test.go │ │ ├── go/ │ │ │ └── ast/ │ │ │ └── ast.go │ │ ├── gopkg.in/ │ │ │ └── check.v1/ │ │ │ └── gocheck_stub.go │ │ ├── idea_io/ │ │ │ └── io.go │ │ ├── io/ │ │ │ └── io.go │ │ ├── log/ │ │ │ └── log.go │ │ ├── math/ │ │ │ └── abs.go │ │ ├── net/ │ │ │ ├── http/ │ │ │ │ └── request.go │ │ │ ├── internal/ │ │ │ │ └── internal.go │ │ │ └── url/ │ │ │ └── url.go │ │ ├── os/ │ │ │ └── file.go │ │ ├── regexp/ │ │ │ └── regexp.go │ │ ├── sync/ │ │ │ ├── mutex.go │ │ │ └── rwmutex.go │ │ ├── testing/ │ │ │ └── testing.go │ │ ├── text/ │ │ │ └── template/ │ │ │ ├── helper.go │ │ │ └── template.go │ │ ├── time/ │ │ │ ├── tick.go │ │ │ └── time.go │ │ ├── unsafe/ │ │ │ └── unsafe.go │ │ └── withmain/ │ │ ├── main_package.go │ │ └── not_main_package.go │ ├── parameterInfo/ │ │ ├── chainedCall.go │ │ ├── closure.go │ │ ├── fieldMethCall.go │ │ ├── funcEmbedInner.go │ │ ├── funcEmbedOuter.go │ │ ├── funcParam.go │ │ ├── funcParamEllipsis.go │ │ ├── funcParamMulti.go │ │ ├── funcParamNone.go │ │ ├── funcTypes.go │ │ ├── functionTypeByRef.go │ │ ├── methParam.go │ │ ├── methParamEllipsis.go │ │ ├── methParamNone.go │ │ ├── unnamedAndNamedParameters.go │ │ └── unnamedParameters.go │ ├── parser/ │ │ ├── ArrayTypes.go │ │ ├── ArrayTypes.txt │ │ ├── ArrayTypesInRanges.go │ │ ├── ArrayTypesInRanges.txt │ │ ├── BlockRecover.go │ │ ├── BlockRecover.txt │ │ ├── Cars.go │ │ ├── Cars.txt │ │ ├── ChanRecover.go │ │ ├── ChanRecover.txt │ │ ├── ElementRecover.go │ │ ├── ElementRecover.txt │ │ ├── Error.go │ │ ├── Error.txt │ │ ├── ExpressionPerformance.go │ │ ├── ExpressionPerformance.txt │ │ ├── If.go │ │ ├── If.txt │ │ ├── IfComposite.go │ │ ├── IfComposite.txt │ │ ├── IfWithNew.go │ │ ├── IfWithNew.txt │ │ ├── IncDec.go │ │ ├── IncDec.txt │ │ ├── IncompleteRanges.go │ │ ├── IncompleteRanges.txt │ │ ├── IncompleteTypeDeclaration.go │ │ ├── IncompleteTypeDeclaration.txt │ │ ├── IncompleteVarDeclaration.go │ │ ├── IncompleteVarDeclaration.txt │ │ ├── Labels.go │ │ ├── Labels.txt │ │ ├── LiteralValues.go │ │ ├── LiteralValues.txt │ │ ├── LiteralValuesElse.go │ │ ├── LiteralValuesElse.txt │ │ ├── MapLiteralRecover.go │ │ ├── MapLiteralRecover.txt │ │ ├── MethodExpr.go │ │ ├── MethodExpr.txt │ │ ├── MethodWithoutReceiverIdentifier.go │ │ ├── MethodWithoutReceiverIdentifier.txt │ │ ├── PlusPlusRecover.go │ │ ├── PlusPlusRecover.txt │ │ ├── Primer.go │ │ ├── Primer.txt │ │ ├── Ranges.go │ │ ├── Ranges.txt │ │ ├── Recover.go │ │ ├── Recover.txt │ │ ├── Recover2.go │ │ ├── Recover2.txt │ │ ├── Recover3.go │ │ ├── Recover3.txt │ │ ├── Simple.go │ │ ├── Simple.txt │ │ ├── Str2Num.go │ │ ├── Str2Num.txt │ │ ├── Torture.go │ │ ├── Torture.txt │ │ ├── TypeComma.go │ │ ├── TypeComma.txt │ │ ├── TypeInBlock.go │ │ ├── TypeInBlock.txt │ │ ├── Types.go │ │ ├── Types.txt │ │ ├── Writer.go │ │ └── Writer.txt │ ├── performance/ │ │ ├── GoUnresolvedReference/ │ │ │ └── expected.xml │ │ ├── GoUnusedExportedFunction/ │ │ │ └── expected.xml │ │ ├── GoUnusedFunction/ │ │ │ └── expected.xml │ │ ├── GoUnusedGlobalVariable/ │ │ │ └── expected.xml │ │ ├── GoUnusedImport/ │ │ │ └── expected.xml │ │ ├── GoUnusedVariable/ │ │ │ └── expected.xml │ │ ├── performanceA.go │ │ └── performanceA2.go │ ├── psi/ │ │ ├── importDeclaration/ │ │ │ ├── addImportBeforeFunction.go │ │ │ ├── addImportBeforeFunction_after.go │ │ │ ├── addImportToEmptyList.go │ │ │ ├── addImportToEmptyListBeforeFunction.go │ │ │ ├── addImportToEmptyListBeforeFunction_after.go │ │ │ ├── addImportToEmptyList_after.go │ │ │ ├── addImportToListWithMultiSpecDeclaration.go │ │ │ ├── addImportToListWithMultiSpecDeclaration_after.go │ │ │ ├── addImportToListWithSingleSpecDeclaration.go │ │ │ ├── addImportToListWithSingleSpecDeclarationWithParens.go │ │ │ ├── addImportToListWithSingleSpecDeclarationWithParens_after.go │ │ │ ├── addImportToListWithSingleSpecDeclaration_after.go │ │ │ ├── doNotModifyCImport_1.go │ │ │ ├── doNotModifyCImport_1_after.go │ │ │ ├── doNotModifyCImport_2.go │ │ │ ├── doNotModifyCImport_2_after.go │ │ │ ├── invalidImport.go │ │ │ ├── invalidImport2.go │ │ │ ├── invalidImport2_after.go │ │ │ └── invalidImport_after.go │ │ └── resolve/ │ │ ├── builtin/ │ │ │ ├── BuiltinConversion.go │ │ │ ├── BuiltinTypes.go │ │ │ ├── MethodName.go │ │ │ ├── ParameterType.go │ │ │ ├── VarBuiltinType.go │ │ │ └── VarMethodType.go │ │ ├── calls/ │ │ │ ├── CallFromTestToMethodDefinedInTestFile/ │ │ │ │ ├── main2_test.go │ │ │ │ └── main_test.go │ │ │ ├── CallToDifferentBuildTargetFiles/ │ │ │ │ ├── disabledFile.go │ │ │ │ ├── enabledFile.go │ │ │ │ └── main.go │ │ │ ├── CallToEmbeddedInterfaceMethod.go │ │ │ ├── CallToFunctionLiteral.go │ │ │ ├── CallToFunctionVariable.go │ │ │ ├── CallToFunctionWithSameNameAsMethod.go │ │ │ ├── CallToFunctionWithSameNameAsMethodAcrossPackages/ │ │ │ │ ├── main.go │ │ │ │ └── p1/ │ │ │ │ └── p1.go │ │ │ ├── CallToLocalFunction.go │ │ │ ├── CallToLocalInterfaceMethod.go │ │ │ ├── CallToLocalInterfaceMethodNested.go │ │ │ ├── CallToLocalInterfaceMethodViaMap.go │ │ │ ├── CallToLocalInterfaceMethodViaSlice.go │ │ │ ├── CallToLocalInterfaceMethodViaTypeAssert.go │ │ │ ├── CallToLocalMethod.go │ │ │ ├── CallToLocalMethodByPointer.go │ │ │ ├── CallToLocalMethodNested.go │ │ │ ├── CallToLocalMethodViaMap.go │ │ │ ├── CallToLocalMethodViaShortVarDeclaration.go │ │ │ ├── CallToLocalMethodViaSlice.go │ │ │ ├── CallToLocalMethodViaTypeAssert.go │ │ │ ├── CallToMethodDefinedInTestFile/ │ │ │ │ ├── main.go │ │ │ │ └── main_test.go │ │ │ ├── CallToMethodParameter.go │ │ │ ├── CallToMethodViaShortVar/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── test.go │ │ │ ├── CallToMethodWithTheSameNameAsFunction.go │ │ │ ├── CallToMethodWithTheSameNameAsFunctionAcrossPackages/ │ │ │ │ ├── main.go │ │ │ │ └── p1/ │ │ │ │ └── p1.go │ │ │ ├── ConversionToImportedFunction/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── test.go │ │ │ ├── ConversionToImportedType/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── test.go │ │ │ ├── ConversionToLocallyImportedType/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── test.go │ │ │ ├── DirectlyInheritedMethodSet.go │ │ │ ├── FunctionInSamePackageDifferentFile/ │ │ │ │ ├── callee.go │ │ │ │ └── caller.go │ │ │ ├── GrandParentDirectlyInheritedMethodSet.go │ │ │ ├── ImportedEmbeddedTypeMethod/ │ │ │ │ ├── main.go │ │ │ │ └── p/ │ │ │ │ └── p.go │ │ │ ├── NoConversionToBlankImportedType/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── test.go │ │ │ ├── RecursiveMethodCall.go │ │ │ ├── RelativePackageReference/ │ │ │ │ ├── main/ │ │ │ │ │ └── main.go │ │ │ │ └── test2/ │ │ │ │ └── test2.go │ │ │ ├── RelativePackageReferenceDeep/ │ │ │ │ └── level1/ │ │ │ │ ├── level2/ │ │ │ │ │ └── level2.go │ │ │ │ └── main/ │ │ │ │ └── main.go │ │ │ └── TypeConversionToLocalType.go │ │ ├── composite/ │ │ │ ├── ExpressionKey.go │ │ │ ├── KeyAsConstantExpression.go │ │ │ ├── NestedNamedStruct.go │ │ │ ├── NestedStruct.go │ │ │ ├── PromotedAnonymousField1.go │ │ │ ├── PromotedAnonymousField2.go │ │ │ ├── PromotedAnonymousField3.go │ │ │ ├── PromotedAnonymousField4.go │ │ │ ├── TypeName.go │ │ │ ├── TypeNameArray.go │ │ │ ├── TypeNameMap.go │ │ │ ├── TypeNameSlice.go │ │ │ ├── TypeStruct.go │ │ │ ├── TypeStructArray.go │ │ │ ├── TypeStructMap.go │ │ │ ├── TypeStructSlice.go │ │ │ └── TypeSwitch.go │ │ ├── package/ │ │ │ └── ImportAlias.go │ │ ├── struct/ │ │ │ ├── AnonymousDirectStructField.go │ │ │ ├── DirectExportedFieldFromImportedPackage/ │ │ │ │ ├── main.go │ │ │ │ └── pack/ │ │ │ │ └── pack.go │ │ │ ├── DirectPrivateFieldFromImportedPackage/ │ │ │ │ ├── main.go │ │ │ │ └── pack/ │ │ │ │ └── pack.go │ │ │ ├── DirectStructField.go │ │ │ ├── FieldVsParam.go │ │ │ ├── FieldVsParam2.go │ │ │ ├── FieldVsParam3.go │ │ │ ├── FieldVsParam4.go │ │ │ ├── PromotedStructField.go │ │ │ └── StructFieldInMap.go │ │ ├── types/ │ │ │ ├── CompositeLiteralFromImportedPackage/ │ │ │ │ ├── datatier/ │ │ │ │ │ └── datatier.go │ │ │ │ └── main/ │ │ │ │ └── main.go │ │ │ ├── DontResolveIfImportedInAnotherFileSamePackage/ │ │ │ │ ├── imported/ │ │ │ │ │ └── imported.go │ │ │ │ ├── main1.go │ │ │ │ └── main2.go │ │ │ ├── FromCustomImportedPackage/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── packageTest.go │ │ │ ├── FromDefaultImportedPackage/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── packageTest.go │ │ │ ├── FromInjectedPackage/ │ │ │ │ ├── main.go │ │ │ │ └── test/ │ │ │ │ └── packageTest.go │ │ │ ├── FromLowerCasePackageInMixedCaseFolder/ │ │ │ │ ├── Gongo/ │ │ │ │ │ └── gongo.go │ │ │ │ └── main.go │ │ │ ├── FromMethodReceiver.go │ │ │ ├── FromMixedCaseImportedPackage/ │ │ │ │ ├── dataTier/ │ │ │ │ │ └── dataTier.go │ │ │ │ └── main.go │ │ │ ├── FromMultipleImportedPackage/ │ │ │ │ ├── imported/ │ │ │ │ │ ├── imported1.go │ │ │ │ │ └── imported2.go │ │ │ │ └── main.go │ │ │ ├── FunctionTypeByRef.go │ │ │ ├── IgnoreBlankImportedPackage/ │ │ │ │ ├── main.go │ │ │ │ ├── packageTest.go │ │ │ │ └── packageTest2.go │ │ │ ├── LocalType.go │ │ │ ├── MethodsOrder.go │ │ │ ├── ResolveArrayInRange.go │ │ │ ├── ResolveTypeInCast.go │ │ │ └── ResolveTypeNameInTypeSpec.go │ │ └── vars/ │ │ ├── AnonymousFunctionInvocation.go │ │ ├── ChainedSelector.go │ │ ├── DeclarationInsideLabeledStatement.go │ │ ├── DeclaredInForClause.go │ │ ├── DeclaredInForRange1.go │ │ ├── DeclaredInForRange2.go │ │ ├── DeclaredInForRangeAsValue.go │ │ ├── DefaultImportDifferentPackage/ │ │ │ ├── main.go │ │ │ └── test/ │ │ │ └── file.go │ │ ├── DontProcessExpressions.go │ │ ├── FromCustomImportedPackage/ │ │ │ ├── main.go │ │ │ └── test/ │ │ │ └── test.go │ │ ├── FromDefaultImportedPackage/ │ │ │ ├── main.go │ │ │ └── test/ │ │ │ └── test.go │ │ ├── FromInjectedImportedPackage/ │ │ │ ├── main.go │ │ │ └── test/ │ │ │ └── test.go │ │ ├── GlobalConstDeclaration.go │ │ ├── GlobalShadowedVarDeclaration.go │ │ ├── GlobalVarDeclaration.go │ │ ├── GlobalVarDeclarationFromBlock.go │ │ ├── LocalConstDeclaration.go │ │ ├── LocalPackageDefinitionsShouldBeResolvedFirst/ │ │ │ ├── package1/ │ │ │ │ └── package1.go │ │ │ └── package2/ │ │ │ ├── package21.go │ │ │ └── package22.go │ │ ├── MethodReturn.go │ │ ├── MethodReturn2.go │ │ ├── MultipleApplications/ │ │ │ ├── Application1/ │ │ │ │ ├── main.go │ │ │ │ └── test.go │ │ │ └── Application2/ │ │ │ ├── main.go │ │ │ └── test.go │ │ ├── MultipleGlobalConsts.go │ │ ├── MultipleGlobalVars.go │ │ ├── RangeExpressionVarsShouldNotResolveToRangeVars.go │ │ ├── ResolveMethodReceiver.go │ │ ├── ResolveToFunctionName.go │ │ ├── ResolveToMethodName.go │ │ ├── ShortAssignToReturnVar.go │ │ ├── ShortVarDeclaration.go │ │ ├── ShortVarDeclarationFromBlock.go │ │ ├── ShortVarDeclarationFromSelectClause.go │ │ ├── ShortVarRedeclaration.go │ │ ├── SimpleMethodParameter.go │ │ ├── StructFieldViaChannel.go │ │ ├── VarDeclarationInSelectCommClauseDefault.go │ │ ├── VarDeclarationInSelectCommClauseRecv.go │ │ ├── VarDeclarationInSelectCommClauseSend.go │ │ ├── VarDeclarationOutsideSwitch.go │ │ ├── VarDereferenceAsTypeCast.go │ │ ├── VarInSwitchExpr.go │ │ ├── VarInSwitchExprInitialization.go │ │ ├── VarInSwitchType.go │ │ ├── VarInSwitchTypeInitialization.go │ │ ├── VarInSwitchTypeWithNamedSwitchGuard.go │ │ ├── VarTypeGuard.go │ │ └── VarVsInnerTypes.go │ ├── quickfixes/ │ │ ├── add-comma/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── add-missing-return/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── assignment-to-comparison/ │ │ │ ├── assignment-after.go │ │ │ ├── assignment.go │ │ │ ├── shortVar-after.go │ │ │ └── shortVar.go │ │ ├── continue-outside-loop/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── create-type/ │ │ │ ├── global-after.go │ │ │ ├── global.go │ │ │ ├── prohibited.go │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── exported-own-declaration/ │ │ │ ├── multiLineMultipleConstsWithType-after.go │ │ │ ├── multiLineMultipleConstsWithType.go │ │ │ ├── multiLineMultipleConstsWithoutType-after.go │ │ │ ├── multiLineMultipleConstsWithoutType.go │ │ │ ├── multiLineMultipleVarsOnlyType-after.go │ │ │ ├── multiLineMultipleVarsOnlyType.go │ │ │ ├── multiLineMultipleVarsOnlyValues-after.go │ │ │ ├── multiLineMultipleVarsOnlyValues.go │ │ │ ├── multiLineMultipleVarsWithTypeAndValues-after.go │ │ │ ├── multiLineMultipleVarsWithTypeAndValues.go │ │ │ ├── singleLineMultipleConsts-after.go │ │ │ ├── singleLineMultipleConsts.go │ │ │ ├── singleLineMultipleExportedAndPrivateConsts-after.go │ │ │ ├── singleLineMultipleExportedAndPrivateConsts.go │ │ │ ├── singleLineMultipleVars-after.go │ │ │ └── singleLineMultipleVars.go │ │ ├── global-constant/ │ │ │ ├── doNotSuggestCreatingConstOnAssignment.go │ │ │ ├── doNotSuggestCreatingConstOnChanRead.go │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── global-variable/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── introduce-function/ │ │ │ ├── asFunctionArg-after.go │ │ │ ├── asFunctionArg.go │ │ │ ├── asFunctionArg2-after.go │ │ │ ├── asFunctionArg2.go │ │ │ ├── asFunctionArgWithoutReference-after.go │ │ │ ├── asFunctionArgWithoutReference.go │ │ │ ├── dontCreate.go │ │ │ ├── funcWithOneParam-after.go │ │ │ ├── funcWithOneParam.go │ │ │ ├── funcWithResultType-after.go │ │ │ ├── funcWithResultType.go │ │ │ ├── funcWithThreeParams-after.go │ │ │ ├── funcWithThreeParams.go │ │ │ ├── funcWithThreeResultValues-after.go │ │ │ ├── funcWithThreeResultValues.go │ │ │ ├── funcWithUnknownResultType-after.go │ │ │ ├── funcWithUnknownResultType.go │ │ │ ├── funcWithUnknownTypeParam-after.go │ │ │ ├── funcWithUnknownTypeParam.go │ │ │ ├── inConstDeclaration.go │ │ │ ├── shortVarDecl-after.go │ │ │ ├── shortVarDecl.go │ │ │ ├── simpleFunction-after.go │ │ │ ├── simpleFunction.go │ │ │ ├── varSpec-after.go │ │ │ ├── varSpec.go │ │ │ ├── withChan-after.go │ │ │ └── withChan.go │ │ ├── local-constant/ │ │ │ ├── if-after.go │ │ │ ├── if.go │ │ │ ├── onAssignment.go │ │ │ ├── onChanRead.go │ │ │ ├── onTopLevel.go │ │ │ ├── resolved-after.go │ │ │ ├── resolved.go │ │ │ ├── simple-after.go │ │ │ ├── simple.go │ │ │ ├── unresolved-after.go │ │ │ └── unresolved.go │ │ ├── local-variable/ │ │ │ ├── if-after.go │ │ │ ├── if.go │ │ │ ├── onTopLevel.go │ │ │ ├── resolved-after.go │ │ │ ├── resolved.go │ │ │ ├── simple-after.go │ │ │ ├── simple.go │ │ │ ├── unresolved-after.go │ │ │ └── unresolved.go │ │ ├── multiple-packages/ │ │ │ ├── a-after.go │ │ │ ├── a.go │ │ │ ├── b-after.go │ │ │ ├── b.go │ │ │ ├── b_test-after.go │ │ │ ├── b_test.go │ │ │ ├── c_test-after.go │ │ │ └── c_test.go │ │ ├── rename-function/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── rename-var/ │ │ │ ├── prohibited.go │ │ │ ├── renameAndReplaceWithAssignmentOnRange-after.go │ │ │ ├── renameAndReplaceWithAssignmentOnRange.go │ │ │ ├── renameAndReplaceWithAssignment_1-after.go │ │ │ ├── renameAndReplaceWithAssignment_1.go │ │ │ ├── renameAndReplaceWithAssignment_2-after.go │ │ │ ├── renameAndReplaceWithAssignment_2.go │ │ │ ├── renameAndReplaceWithAssignment_3-after.go │ │ │ ├── renameAndReplaceWithAssignment_3.go │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── replace-with-assignment/ │ │ │ ├── rangeClause-after.go │ │ │ ├── rangeClause.go │ │ │ ├── recvStatement-after.go │ │ │ ├── recvStatement.go │ │ │ ├── recvStatementInSelect-after.go │ │ │ ├── recvStatementInSelect.go │ │ │ ├── severalAssignments-after.go │ │ │ ├── severalAssignments.go │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ ├── replace-with-declaration/ │ │ │ ├── onAssignment-after.go │ │ │ ├── onAssignment.go │ │ │ ├── onChanRead.go │ │ │ ├── onRange-after.go │ │ │ ├── onRange.go │ │ │ ├── onRecv-after.go │ │ │ ├── onRecv.go │ │ │ └── onTopLevel.go │ │ ├── replace-with-select/ │ │ │ ├── simple-after.go │ │ │ └── simple.go │ │ └── string-index-is-byte/ │ │ ├── equalsCondition-after.go │ │ ├── equalsCondition.go │ │ ├── greaterCondition-after.go │ │ ├── greaterCondition.go │ │ ├── greaterOrEqualsCondition-after.go │ │ ├── greaterOrEqualsCondition.go │ │ ├── lessCondition-after.go │ │ ├── lessCondition.go │ │ ├── lessOrEqualsCondition-after.go │ │ ├── lessOrEqualsCondition.go │ │ ├── literals-after.go │ │ ├── literals.go │ │ ├── longLiteral-after.go │ │ ├── longLiteral.go │ │ ├── moreThanOneCharInString.go │ │ ├── notEqualsCondition-after.go │ │ ├── notEqualsCondition.go │ │ ├── reverse-after.go │ │ ├── reverse.go │ │ ├── sliceFromLeft.go │ │ ├── sliceFromRight.go │ │ └── sliceUnbound.go │ ├── refactor/ │ │ └── introduce-variable/ │ │ ├── caretAfterRightParenthesis-after.go │ │ ├── caretAfterRightParenthesis.go │ │ ├── caretOnCallParenthesis-after.go │ │ ├── caretOnCallParenthesis.go │ │ ├── caretOnRightParenthesis-after.go │ │ ├── caretOnRightParenthesis.go │ │ ├── compositeLiteral-after.go │ │ ├── compositeLiteral.go │ │ ├── conversion-after.go │ │ ├── conversion.go │ │ ├── doNotSuggestKeywordBasedOnCallName-after.go │ │ ├── doNotSuggestKeywordBasedOnCallName.go │ │ ├── doNotSuggestKeywordBasedOnType-after.go │ │ ├── doNotSuggestKeywordBasedOnType.go │ │ ├── doNotSuggestNameEqualsToType-after.go │ │ ├── doNotSuggestNameEqualsToType.go │ │ ├── extractFunctionLiteral-after.go │ │ ├── extractFunctionLiteral.go │ │ ├── extractSingleExpressionStatement_1-after.go │ │ ├── extractSingleExpressionStatement_1.go │ │ ├── extractSingleExpressionStatement_2-after.go │ │ ├── extractSingleExpressionStatement_2.go │ │ ├── extractSingleExpressionStatement_3-after.go │ │ ├── extractSingleExpressionStatement_3.go │ │ ├── indexedExpression-after.go │ │ ├── indexedExpression.go │ │ ├── nameSuggestOnArrayType-after.go │ │ ├── nameSuggestOnArrayType.go │ │ ├── nameSuggestOnDefaultName-after.go │ │ ├── nameSuggestOnDefaultName.go │ │ ├── nameSuggestOnGetterFunction-after.go │ │ ├── nameSuggestOnGetterFunction.go │ │ ├── nameSuggestOnParamName-after.go │ │ ├── nameSuggestOnParamName.go │ │ ├── nameSuggestOnType-after.go │ │ ├── nameSuggestOnType.go │ │ ├── replaceAll-after.go │ │ ├── replaceAll.go │ │ ├── replaceOnly-after.go │ │ ├── replaceOnly.go │ │ ├── topLevelExpression.go │ │ ├── twoOccurrences-after.go │ │ ├── twoOccurrences.go │ │ ├── voidCallExpression.go │ │ ├── voidExpression.go │ │ └── wrongSelection.go │ ├── regexp/ │ │ └── injectingAndHighlighting.go │ ├── running/ │ │ └── producer/ │ │ ├── directory.xml │ │ ├── fileWithMain.go │ │ ├── fileWithMain.xml │ │ ├── fileWithMainButNotMainPackage.go │ │ ├── fileWithMainButNotMainPackage.xml │ │ ├── fileWithoutMain.go │ │ ├── fileWithoutMain.xml │ │ ├── packageClause.go │ │ ├── packageClause.xml │ │ ├── testFile_test.go │ │ └── testFile_test.xml │ ├── selectWord/ │ │ ├── arguments/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ ├── after5.go │ │ │ └── before.go │ │ ├── block/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ ├── after5.go │ │ │ └── before.go │ │ ├── functionName/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ └── before.go │ │ ├── importString/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ └── before.go │ │ ├── multipleImportString/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ ├── after5.go │ │ │ ├── after6.go │ │ │ └── before.go │ │ ├── parameters/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ ├── after5.go │ │ │ ├── after6.go │ │ │ ├── after7.go │ │ │ └── before.go │ │ ├── resultParameters/ │ │ │ ├── after1.go │ │ │ ├── after2.go │ │ │ ├── after3.go │ │ │ ├── after4.go │ │ │ ├── after5.go │ │ │ ├── after6.go │ │ │ └── before.go │ │ └── stringLiteral/ │ │ ├── after1.go │ │ ├── after2.go │ │ ├── after3.go │ │ ├── after4.go │ │ ├── after5.go │ │ └── before.go │ ├── smartEnter/ │ │ ├── deferStatement-after.go │ │ ├── deferStatement.go │ │ ├── deferStatementOnNonFunctionType-after.go │ │ ├── deferStatementOnNonFunctionType.go │ │ ├── for-after.go │ │ ├── for.go │ │ ├── forWithBlock-after.go │ │ ├── forWithBlock.go │ │ ├── function-after.go │ │ ├── function.go │ │ ├── functionLiteral-after.go │ │ ├── functionLiteral.go │ │ ├── functionLiteralWithBlock-after.go │ │ ├── functionLiteralWithBlock.go │ │ ├── functionWithBlock-after.go │ │ ├── functionWithBlock.go │ │ ├── goStatement-after.go │ │ ├── goStatement.go │ │ ├── goStatementOnNonFunctionType-after.go │ │ ├── goStatementOnNonFunctionType.go │ │ ├── if-after.go │ │ ├── if.go │ │ ├── ifWithBlock-after.go │ │ └── ifWithBlock.go │ ├── spellchecker/ │ │ ├── functionName.go │ │ ├── suppressed.go │ │ └── variableName.go │ ├── stubs/ │ │ ├── stub.go │ │ ├── stub.txt │ │ ├── stubMismatch2540.go │ │ └── stubMismatch2540.txt │ ├── testing/ │ │ ├── gobench/ │ │ │ ├── benchmarkWithoutSuffix-expected.txt │ │ │ ├── benchmarkWithoutSuffix.txt │ │ │ ├── failedBenchmark-expected.txt │ │ │ ├── failedBenchmark.txt │ │ │ ├── failedCompilation-expected.txt │ │ │ ├── failedCompilation.txt │ │ │ ├── mixedBenchmark-expected.txt │ │ │ ├── mixedBenchmark.txt │ │ │ ├── successBenchmark-expected.txt │ │ │ └── successBenchmark.txt │ │ ├── gocheck/ │ │ │ ├── assertions-expected.txt │ │ │ ├── assertions.txt │ │ │ ├── assertionsInvalidFormat-expected.txt │ │ │ ├── assertionsInvalidFormat.txt │ │ │ ├── fixtureStdOut-expected.txt │ │ │ ├── fixtureStdOut.txt │ │ │ ├── panic-expected.txt │ │ │ ├── panic.txt │ │ │ ├── panicInvalidFormat-expected.txt │ │ │ ├── panicInvalidFormat.txt │ │ │ ├── pass-expected.txt │ │ │ ├── pass.txt │ │ │ ├── skippingTests-expected.txt │ │ │ ├── skippingTests.txt │ │ │ ├── suiteSetUpError-expected.txt │ │ │ ├── suiteSetUpError.txt │ │ │ ├── suiteTearDownError-expected.txt │ │ │ ├── suiteTearDownError.txt │ │ │ ├── testAndTestTearDownError-expected.txt │ │ │ ├── testAndTestTearDownError.txt │ │ │ ├── testBothFixturesError-expected.txt │ │ │ ├── testBothFixturesError.txt │ │ │ ├── testErrorWithFixtures-expected.txt │ │ │ ├── testErrorWithFixtures.txt │ │ │ ├── testSetUpError-expected.txt │ │ │ ├── testSetUpError.txt │ │ │ ├── testTearDownError-expected.txt │ │ │ └── testTearDownError.txt │ │ ├── gotest/ │ │ │ ├── multipleTestsFailed-expected.txt │ │ │ ├── multipleTestsFailed.txt │ │ │ ├── multipleTestsOk-expected.txt │ │ │ ├── multipleTestsOk.txt │ │ │ ├── oneLineEvents-expected.txt │ │ │ ├── oneLineEvents.txt │ │ │ ├── singleTestFailed-expected.txt │ │ │ ├── singleTestFailed.txt │ │ │ ├── singleTestLeadingSpaceOk-expected.txt │ │ │ ├── singleTestLeadingSpaceOk.txt │ │ │ ├── singleTestOk-expected.txt │ │ │ ├── singleTestOk.txt │ │ │ ├── skipTest-expected.txt │ │ │ ├── skipTest.txt │ │ │ ├── stdOut-expected.txt │ │ │ ├── stdOut.txt │ │ │ ├── subTests-expected.txt │ │ │ ├── subTests.txt │ │ │ ├── unicodeTestName-expected.txt │ │ │ └── unicodeTestName.txt │ │ └── producer/ │ │ ├── benchmarkFunction_test.go │ │ ├── benchmarkFunction_test.xml │ │ ├── directory.xml │ │ ├── exampleFunction_test.go │ │ ├── exampleFunction_test.xml │ │ ├── fileWithBenchmarksOnly_test.go │ │ ├── fileWithBenchmarksOnly_test.xml │ │ ├── fileWithGocheckTestsOnly_test.go │ │ ├── fileWithGocheckTestsOnly_test.xml │ │ ├── fileWithTestsAndBenchmarks_test.go │ │ ├── fileWithTestsAndBenchmarks_test.xml │ │ ├── fileWithTestsOnly_test.go │ │ ├── fileWithTestsOnly_test.xml │ │ ├── fileWithoutTest_test.go │ │ ├── fileWithoutTest_test.xml │ │ ├── gocheckMethod_test.go │ │ ├── gocheckMethod_test.xml │ │ ├── nonTestFile.go │ │ ├── nonTestFile.xml │ │ ├── package_test.xml │ │ ├── simpleFunctionInFileWithTests_test.go │ │ ├── simpleFunctionInFileWithTests_test.xml │ │ ├── simpleFunction_test.go │ │ ├── simpleFunction_test.xml │ │ ├── testFunctionNonTestFile.go │ │ ├── testFunctionNonTestFile.xml │ │ ├── testFunction_test.go │ │ └── testFunction_test.xml │ └── usages/ │ ├── method.go │ └── type.go ├── tests/ │ └── com/ │ └── goide/ │ ├── GoCodeInsightFixtureTestCase.java │ ├── GoDocumentationProviderTest.java │ ├── GoFindUsageTest.java │ ├── GoParametrizedTestBase.java │ ├── GoPerformanceTest.java │ ├── GoSdkServiceTest.java │ ├── SdkAware.java │ ├── actions/ │ │ └── GoCreateFileActionTest.java │ ├── categories/ │ │ └── Performance.java │ ├── codeInsight/ │ │ ├── imports/ │ │ │ ├── GoImportOptimizerTest.java │ │ │ └── GoReferenceImporterTest.java │ │ └── unwrap/ │ │ ├── GoBracesUnwrapperTest.java │ │ ├── GoElseRemoverTest.java │ │ ├── GoElseUnwrapperTest.java │ │ ├── GoForUnwrapperTest.java │ │ ├── GoFunctionArgumentUnwrapperTest.java │ │ ├── GoIfUnwrapperTest.java │ │ └── GoUnwrapTestCase.java │ ├── completion/ │ │ ├── GoCompletionSdkAwareTest.java │ │ ├── GoCompletionTest.java │ │ ├── GoCompletionTestBase.java │ │ ├── GoExcludedPackagesTest.java │ │ └── GoTestNameCompletionTest.java │ ├── coverage/ │ │ └── GoCoverageCalculationTest.java │ ├── editor/ │ │ ├── GoBraceMatcherTest.java │ │ ├── GoExitPointsHighlightingTest.java │ │ ├── GoFoldingBuilderTest.java │ │ ├── GoHighlightingAnnotatorTest.java │ │ ├── GoLiveTemplateTest.java │ │ ├── GoParameterInfoHandlerTest.java │ │ ├── GoQuoteHandlerTest.java │ │ ├── GoSelectWordTest.java │ │ ├── GoSmartEnterTest.java │ │ ├── GoStatementMoverTest.java │ │ └── surround/ │ │ ├── GoSurrounderTestBase.java │ │ ├── GoWithBlockSurrounderTest.java │ │ ├── GoWithForSurrounderTest.java │ │ ├── GoWithIfElseExpressionSurrounderTest.java │ │ ├── GoWithIfElseSurrounderTest.java │ │ ├── GoWithIfExpressionSurrounderTest.java │ │ ├── GoWithIfSurrounderTest.java │ │ ├── GoWithNotExpressionSurrounderTest.java │ │ └── GoWithParenthesisSurrounderTest.java │ ├── formatter/ │ │ └── GoFormatterTest.java │ ├── generate/ │ │ └── GoGenerateTestActionTest.java │ ├── highlighting/ │ │ └── GoColorsAndFontsPageTest.java │ ├── inspections/ │ │ ├── GoAnonymousFieldDefinitionTypeInspectionTest.java │ │ ├── GoAssignmentToReceiverInspectionTest.java │ │ ├── GoDeferGoInspectionTest.java │ │ ├── GoEmptyDeclarationInspectionTest.java │ │ ├── GoHighlightingTest.java │ │ ├── GoInspectionUtilTest.java │ │ ├── GoInvalidPackageImportInspectionTest.java │ │ ├── GoReceiverNamesInspectionTest.java │ │ ├── GoRedundantBlankArgInRangeInspectionTest.java │ │ ├── GoRedundantSecondIndexInSlicesInspectionTest.java │ │ ├── GoRedundantTypeDeclInCompositeLitTest.java │ │ ├── GoSelfImportInspectionTest.java │ │ ├── GoSpellcheckingTest.java │ │ ├── GoStructInitializationInspectionTest.java │ │ ├── GoTestSignaturesInspectionTest.java │ │ ├── GoUnusedLabelInspectionTest.java │ │ └── suppression/ │ │ └── GoSuppressionFixTest.java │ ├── intentions/ │ │ └── GoAddFunctionBlockIntentionTest.java │ ├── lexer/ │ │ └── GoLexerTest.java │ ├── marker/ │ │ └── GoRecursiveMethodCallMarkerInfoTest.java │ ├── parser/ │ │ ├── GoParseAndConsumeTest.java │ │ ├── GoParserTest.java │ │ └── GoParserTestBase.java │ ├── psi/ │ │ ├── GoFileTest.java │ │ ├── GoImportListTest.java │ │ ├── GoReadWriteAccessTest.java │ │ ├── impl/ │ │ │ ├── GoNamedElementTest.java │ │ │ └── GoPsiImplUtilTest.java │ │ └── legacy/ │ │ ├── GoLegacyResolveBuiltinTest.java │ │ ├── GoLegacyResolveCallsTest.java │ │ ├── GoLegacyResolveCompositeTest.java │ │ ├── GoLegacyResolvePackageTest.java │ │ ├── GoLegacyResolveStructTest.java │ │ ├── GoLegacyResolveTestBase.java │ │ ├── GoLegacyResolveTypesTest.java │ │ └── GoLegacyResolveVarsTest.java │ ├── quickfix/ │ │ ├── GoAddMissingReturnQuickFixTest.java │ │ ├── GoAddTrailingCommaQuickFixTest.java │ │ ├── GoAssignmentToComparisonQuickFixTest.java │ │ ├── GoBoolExpressionsInspectionTest.java │ │ ├── GoContinueNotInLoopQuickFixTest.java │ │ ├── GoConvertStringToByteQuickFixTest.java │ │ ├── GoCreateGlobalConstQuickFixTest.java │ │ ├── GoCreateGlobalVariableQuickFixTest.java │ │ ├── GoCreateLocalConstantQuickFixTest.java │ │ ├── GoCreateLocalVariableQuickFixTest.java │ │ ├── GoCreateWrapperTypeQuickFixTest.java │ │ ├── GoDeleteConstDefinitionQuickFixTest.java │ │ ├── GoDeleteVarDefinitionQuickFixTest.java │ │ ├── GoEmptySignatureQuickFixTest.java │ │ ├── GoExportedOwnDeclarationQuickFixTest.java │ │ ├── GoIntroduceFunctionFixTest.java │ │ ├── GoMoveToStructInitializationIntentionTest.java │ │ ├── GoMultiplePackagesQuickFixTest.java │ │ ├── GoQuickFixTestBase.java │ │ ├── GoRenameFunctionQuickFixTest.java │ │ ├── GoRenameVarQuickFixTest.java │ │ ├── GoReplaceWithAssignmentStatementQuickFixTest.java │ │ ├── GoReplaceWithDeclarationQuickFixTest.java │ │ ├── GoReplaceWithImportForSideEffectsQuickFixTest.java │ │ └── GoReplaceWithSelectStatementQuickFixTest.java │ ├── refactor/ │ │ └── GoIntroduceVariableTest.java │ ├── regexp/ │ │ └── GoRegExpLanguageTest.java │ ├── rename/ │ │ └── GoRenameTest.java │ ├── runconfig/ │ │ ├── GoConsoleFilterTest.java │ │ ├── GoRunConfigurationProducerTest.java │ │ ├── GoRunConfigurationTestCase.java │ │ └── testing/ │ │ ├── GoEventsConverterTestCase.java │ │ ├── GoRunLineMarkerTest.java │ │ ├── GoTestRunConfigurationProducerTest.java │ │ ├── GobenchEventsConverterTest.java │ │ ├── GocheckEventsConverterTest.java │ │ ├── GotestEventsConverterTest.java │ │ └── LoggingServiceMessageVisitor.java │ ├── sdk/ │ │ ├── GoPathLibraryTest.java │ │ └── GoSdkUtilTest.java │ ├── stubs/ │ │ ├── GoPackageClauseStubTest.java │ │ └── GoStubTest.java │ ├── type/ │ │ ├── GoExpectedTypesTest.java │ │ ├── GoTypeResolveTest.java │ │ └── GoUnderlyingTypeTest.java │ ├── usages/ │ │ └── GoFileStructureGroupRuleTest.java │ └── util/ │ ├── GoBuildMatcherTest.java │ ├── GoExpressionUtilTest.java │ ├── GoPackageUtilTest.java │ ├── GoStringLiteralEscaperEscapeStringTest.java │ └── GoStringLiteralEscaperTest.java └── utils/ └── src/ └── com/ └── goide/ ├── GoConstants.java ├── GoEnvironmentUtil.java └── GoLibrariesState.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ *.bat eol=crlf ================================================ FILE: .gitignore ================================================ /build/ /google-app-engine/build/ /google-app-engine/google-app-engine-yaml/build/ /utils/build/ /plan9/build/ .gradle .idea/workspace.xml .idea/modules.xml .idea/misc.xml .idea/gradle.xml .idea/compiler.xml .idea/shelf/ .idea/libraries/ .idea/.name .idea/*.png *.iml /testData/performance/docker/ /testData/performance/go/ ================================================ FILE: .idea/ant.xml ================================================ ================================================ FILE: .idea/codeStyleSettings.xml ================================================ ================================================ FILE: .idea/copyright/apache.xml ================================================ ================================================ FILE: .idea/copyright/no_copyright.xml ================================================ ================================================ FILE: .idea/copyright/profiles_settings.xml ================================================ ================================================ FILE: .idea/dictionaries/ignatov.xml ================================================ exprs goroutine mihai modificator patan structs toader uintptr unescapes unescaping variadic vendoring zolotov ================================================ FILE: .idea/dictionaries/zolotov.xml ================================================ autoimport backticks consts covermode coverprofile devel gcloud gobench gocheck goide goimports gopath goroot gotest hgap nacl netbsd notwin openbsd recv redeclared runconfig solaris vendored vgap vspacer ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/externalDependencies.xml ================================================ ================================================ FILE: .idea/inspectionProfiles/Project_Default.xml ================================================ ================================================ FILE: .idea/inspectionProfiles/idea_default.xml ================================================ ================================================ FILE: .idea/inspectionProfiles/profiles_settings.xml ================================================ ================================================ FILE: .idea/runConfigurations/All_tests.xml ================================================ ================================================ FILE: .idea/runConfigurations/Build_plugin.xml ================================================ ================================================ FILE: .idea/runConfigurations/Go.xml ================================================ ================================================ FILE: .idea/runConfigurations/Local_IDE.xml ================================================ ================================================ FILE: .idea/runConfigurations/Performance_tests.xml ================================================ ================================================ FILE: .idea/scopes/scope_settings.xml ================================================ ================================================ FILE: .idea/scopes/testdata.xml ================================================ ================================================ FILE: .idea/uiDesigner.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: CONTRIBUTING.md ================================================ # How to contribute [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-lang-plugin-org/go-lang-idea-plugin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ## Contents + [Reporting errors](#reporting-errors) + [Contributing to the code](#contributing-to-the-code) + [Submitting test cases](#submitting-test-cases) + [Building and running the unit tests](#building-and-running-the-unit-tests) + [Configuring and debugging in IntelliJ](#configuring-and-debugging-in-IntelliJ) + [Code Style](#code-style) + [Delve integration](#delve-integration) + [Useful links](#useful-links) ## Reporting errors Before reporting an error, please read the [FAQ](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/wiki/FAQ) and search for the issue in the issue tracker. Also, please don't bump, +1 or "me too" issues. Thank you. The simplest way to contribute to the plugin is to report issues you encounter in your day to day use. As a rule of thumb, always keep in mind that we are developers just like you. So, whenever you are going to report an issue, think of how you'd like to receive issues for your projects. Also, we are doing this in our spare time, so the more information we have in the report, the faster we can replicate the problem and get on solving it rather that just doing a bunch of ping-pong in comments trying to extract the needed details from you. This information applies also when you don't have an error that is caught by the built-in facility but it's something that happens and shouldn't happen (say for example, a formatting issue). When filing an issue, please answer these questions: - What version of Go plugin are you using? - What version of IDEA are you using? - What version of Java are you using? - What did you do? - What did you expect to see? - What did you see instead? Also, every time you can, submit the piece of code that's generating the issue. As it might be some proprietary code, take some time and write the smallest code sample that can reproduce it and paste it in the issue (or send it as a link to [Go Playground](http://play.golang.org/). Screenshots are useful, but, just like you, we can't copy paste code from screenshots either. Please ensure that the bug is not reported already, this helps us focusing on working on bug fixes not triage work. ## Contributing to the code If you want to contribute to the code, go to GitHub and check out the latest version and follow the instructions on how to build the plugin from source. After that, you can start picking some [pending tasks](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues) on the issue tracker. Make sure you look for issues tags with [up for grabs](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/labels/up%20for%20grabs) as these are some of the easier ones to get started with. ### CLA requirement Contributing to the plugin requires a signed CLA with JetBrains. You can view the steps necessary for this at [this page](http://www.jetbrains.org/display/IJOS/Contribute#Contribute-ContributeCode). ### Submitting test cases Submitting test cases is the next best thing you can do to developing on this project. In fact, you'll actually develop on it since the test code you are going to contribute is still code. Whenever your time or knowledge allows, submitting good test cases for either for existing issues or for issues that you come across will make a huge difference in the way we spend time to understand the problems and thus solve them. ### Building and running the unit tests All code can be checked out from our Github repository in the usual way. That is, clone the repository with HTTPS or SSH: ``` $ git clone https://github.com/go-lang-plugin-org/go-lang-idea-plugin.git Cloning into 'go-lang-idea-plugin'... ``` On Linux/Mac OS X we use gradle as our build system. Gradle is self-installing. This one command ``` $ ./gradlew buildPlugin ``` compiles everything, runs the tests, and builds the plugins. The output appears in `build/distributions`. ### Configuring and debugging in IntelliJ 1. [Download](http://www.jetbrains.com/idea/) IDEA Community or Ultimate 1. Setup the right version of [Grammar-Kit](https://github.com/JetBrains/Grammar-Kit/releases/download/1.4.1/GrammarKit.zip) 1. Make sure that **UI Designer** and **Gradle** plugins are turned on 1. Checkout plugin repo and open the project 1. Open the copy of go-lang-idea-plugin repository (`File | New | Project from Existing Sources...`) with it. Then import Gradle project. The default project module config should work with a recent IDEA 15 version 1. Git revert changes to the .idea folder because IDEA Gradle import blows it away (https://youtrack.jetbrains.com/issue/IDEA-146295) 1. Open `File -> Project Settings`, go to the SDKs entry, click the `+` and select JDK 1.6 1. Go to the Project entry and make sure that the Project SDK is set to selected SDK 1. Wait until the source files of the SDK are indexed 1. Run or debug the **Go** run configuration If you use Mac, you may check follow path while looking for SDK: ``` /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/ /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/ ``` Now you can use the run configurations provided by the plugin source code to run and play. There are multiple branches of the plugin which correspond to different versions of the IntelliJ Platform: - 141 -> can be used for IDEA 14.1 - 144 -> can be used for IDEA 16 The master branch will follow the current stable release of IDEA (currently IDEA 15). Going to ``` Run -> Run... ``` will provide you with the following run configurations: + `Go` will spawn a new IDEA with the latest version of the plugin enabled. + `All tests` will run all the test cases available in the project. Please make sure that all the test cases pass before committing anything (or making a pull request). + `Performance tests` will run all performance test cases available in the project. + `Build plugin` will build plugin distribution archive. All artifacts are stored in `gradle/distributions` directory. You can also have a look at some [useful links](#useful-links) for getting started with plugin development on IntelliJ IDEA platform. ##### IMPORTANT: MacOS X users note You might get the following error ```Unsupported major.minor version 52``` in the logs or the plugin might not work at all. Check the version of Java your IDE is running on. Since in 99.9% of the cases it will be Java 6, this means that you compiled the plugin with a different version of Java, for example Java 8. To fix the error, please use Java JDK 6 to compile the plugin and everything should work. To get the log files, you can go to ```Help | Show Log in File Manager``` and then the log will be displayed to you. ### Code Style * Please don't use class comments with information about author or date and time creation. * Please don't commit anything from `.idea/` directory if you're not very sure what you doing. ### Delve integration We're syncing the plugin source with the [Delve](https://github.com/derekparker/delve) debugger. If you want to customize delve distribution that's used in the plugin you can use `-Dorg.gradle.project.customDlvPath` for setting up the path to your local version of dlv. ### Useful links For further information please see [the official plugin development page](http://confluence.jetbrains.net/display/IDEADEV/PluginDevelopment). Also, you can read some [tips and tricks](http://tomaszdziurko.pl/2011/09/developing-plugin-intellij-idea-some-tips-and-links/). For all development questions and proposals, you can mail to our [Open API and Plugin Development forum](https://devnet.jetbrains.com/community/idea/open_api_and_plugin_development). Happy hacking! ================================================ FILE: ISSUE_TEMPLATE.md ================================================ If you are using [GoLand](https://jetbrains.com/go) or [IntelliJ IDEA Ultimate](https://jetbrains.com/idea) 2017.3 or later, please report your issue at the official tracker: https://youtrack.jetbrains.com/issues/Go This repository is not maintained anymore. - Plugin version (or commit hash): - IDE name and version: - Java version: - OS name and version: - What are you trying to do? - What would you expect to happen? - What happens? Your issue description goes here. Please be as detailed as possible ```go Please include a go sample to reproduce the issue ``` Or include a screenshot / video of the issue. ================================================ FILE: LICENCE ================================================ Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan 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. ================================================ FILE: README.md ================================================ # Go plugin for IntelliJ # Deprecation notice This project is officially not maintained anymore. If you are using [GoLand](https://jetbrains.com/go) or [IntelliJ IDEA Ultimate](https://jetbrains.com/idea) 2017.3 or later, please report your issue at the official tracker: https://youtrack.jetbrains.com/issues/Go [![Build Status](https://teamcity.jetbrains.com/app/rest/builds/buildType:(id:IntellijIdeaPlugins_Go_Test)/statusIcon.svg?guest=1)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=IntellijIdeaPlugins_Go_Test&guest=1) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-lang-plugin-org/go-lang-idea-plugin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ## Pre-release builds Please note, that the following features are available in [GoLand, JetBrains's official IDE](https://www.jetbrains.com/go/), or [JetBrains maintained plugin](https://plugins.jetbrains.com/plugin/9568-go), but **not in this plugin**: - Navigation - Go to inheritor structures - Go to super interfaces - Type-aware completion (aka Smart completion) - Extract function refactoring - Implement type - Inspections and quick-fixes - Introduce method - Introduce field - Delete unused parameter - Show symbol duplicates - Add/delete missing/redundant expressions in case of assignment count mismatch - Properly implemented Duplicated symbols inspection - Recursive type detection - Invalid const initialization - Tests and coverage - Sub-tests support (runner, navigation, gutter actions) - Debugging tests - Debugger - Step out - 100x faster performance - General - Highlighting of go:generate comments - Quick documentation for struct fields - Semantic highlighting - Parameter name hints - SQL auto-injection - Support for Go 1.9+ - Support for AppEngine 1.9.54+ **Supported IDEs** The plugin can be installed on following IntelliJ-based: - IntelliJ 2016.1+ (Ultimate or Community) - WebStorm 2016.1+ - PhpStorm 2016.1+ - PyCharm 2016.1+ - RubyMine 2016.1+ - CLion 2016.1+ - Android Studio 1.2.1+ Pre-release builds are available in two forms: nightly and alphas. Alpha builds are usually released at the beginning of every week while nightly builds are released every night. To use them do the following: 1. Use [the instructions](https://www.jetbrains.com/idea/help/managing-enterprise-plugin-repositories.html) 1. Paste the URL for the version you need: - alpha: https://plugins.jetbrains.com/plugins/alpha/5047 - nightly: https://plugins.jetbrains.com/plugins/nightly/5047 **NOTE** The above links are not meant to be used in browsers, so don't report issues about them not working or being inaccessible unless there's an error in the IDE itself. Since these are not stable releases, some things might not work as expected. ### Release versions schema Bellow you can see the versions of the plugin which correspond to the versions of the IntelliJ Platfom (IntelliJ IDEA, WebStorm, PyCharm etc.): | Plugin version number | Platform number | | ---- | --- | | 0.12.x | IntelliJ 2016.2 (IntelliJ IDEA 2016.2) | | 0.11.x | IntelliJ 2016.1 (IntelliJ IDEA 2016.1) | | 0.10.x | IntelliJ 143.1180 - 143.9999 (IntelliJ IDEA 15.0.2+) | | 0.9.x | IntelliJ 141.1532 - 141.9999 (IntelliJ IDEA 14.1) | If you are not using IntelliJ IDEA, then please check the build number of your IDE as that will correspond to the IntelliJ Platform version. Reporting issues is very important for us as such, please see the section below on how to submit a proper bug report. ## FAQ Here's a list of the most frequently asked questions: [FAQ](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/wiki/FAQ) ## Bugs If you've found a bug, which is not a duplicate, [report it](http://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues). When reporting a bug, please include the following: - IDEA version - OS version - JDK version - Plugin version (or commit hash, if you built the plugin yourself) - Detailed steps to reproduce (please include sample code) ## Bumping or +1 comments Please don't comment with "bump", "+1", "same for me" or other irrelevant comments as they're useless for identifying the issue and finding the solution. Contributions are always welcome and we'll do our best to make the most of them. ## Contributing We encourage you to contribute to the plugin if you find any issues or missing functionality that you'd like to see. In order to get started, see the [contribution](CONTRIBUTING.md) guide. ## [People who helped](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/graphs/contributors) ## License The Gopher icons are based on the Go mascot designed by [Renée French](http://reneefrench.blogspot.com/) and copyrighted under the [Creative Commons Attribution 3.0 license](http://creativecommons.org/licenses/by/3.0/us/). The plugin is distributed under Apache License, version 2.0. For full license terms, see [LICENCE](https://github.com/go-lang-plugin-org/go-lang-idea-plugin/blob/master/LICENCE). ================================================ FILE: build.gradle ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ buildscript { repositories { maven { url 'http://dl.bintray.com/jetbrains/intellij-plugin-service' } maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } dependencies { classpath "org.jetbrains.intellij.plugins:gradle-intellij-plugin:0.2.0-SNAPSHOT" } } plugins { id "de.undercouch.download" version "3.1.0" } apply plugin: 'de.undercouch.download' version = "${version}.$buildNumber" allprojects { apply plugin: 'java' sourceCompatibility = javaVersion targetCompatibility = javaTargetVersion tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } sourceSets { main { java.srcDirs 'src', 'gen' resources.srcDirs 'resources', 'pluginResources' } test { java.srcDir 'tests' } } apply plugin: 'org.jetbrains.intellij' intellij { version ideaVersion pluginName 'Go' plugins 'coverage' downloadSources Boolean.valueOf(sources) sameSinceUntilBuild Boolean.valueOf(isEAP) alternativeIdePath localIdePath systemProperty 'dlv.path', customDlvPath } } publishPlugin { username publishUsername password publishPassword channels publishChannel } patchPluginXml { if (customSinceBuild) { sinceBuild customSinceBuild } } apply plugin: 'idea' idea { project { jdkName = javaVersion languageLevel = javaVersion vcs = 'Git' } module { generatedSourceDirs += file('gen') } } repositories { maven { url "http://dl.bintray.com/jetbrains/golang" } } dependencies { compile project(':utils'), project(':google-app-engine'), project(':google-app-engine:google-app-engine-yaml'), project(':plan9') runtime "com.jetbrains:delve:$delveVersion@zip" } // delve packing project.afterEvaluate { prepareSandbox.doLast { def libraries = "$it.destinationDir/$intellij.pluginName/lib/" def delveFile = fileTree(dir: libraries, include: 'delve*').singleFile copy { from zipTree(delveFile) into libraries } delveFile.delete() } } test { useJUnit { excludeCategories 'com.goide.categories.Performance' } testLogging { exceptionFormat = 'full' } } task preparePerformanceTestData << { downloadAndUnzip('https://storage.googleapis.com/golang/go1.5.1.src.tar.gz', 'go', 'go') downloadAndUnzip('https://github.com/docker/docker/archive/v1.9.1.tar.gz', 'docker-1.9.1', 'docker') } task performanceTest(type: Test, group: 'Verification', dependsOn: [classes, testClasses, preparePerformanceTestData]) { maxHeapSize = '512m' minHeapSize = '256m' useJUnit { includeCategories 'com.goide.categories.Performance' reports.html.destination = "$buildDir/reports/performanceTests" } testLogging { exceptionFormat = 'full' } } check.dependsOn performanceTest private void downloadAndUnzip(url, sourceDir, targetDir) { def testDataPath = "$projectDir/testData/performance/" def markerFile = file("$testDataPath/$targetDir/markerFile") def tmpPath = "$testDataPath/tmp/" def tar = file("$tmpPath/${targetDir}.tar.gz") if (!markerFile.exists()) { download { src url dest tar } copy { from tarTree(tar) into tmpPath } copy { from "$tmpPath/$sourceDir" into "$testDataPath/$targetDir" } markerFile.createNewFile() } delete file(tmpPath) } ================================================ FILE: cloneToWt.sh ================================================ #!/bin/bash # Creates new worktrees for all IntelliJ IDEA repositories pointing to a new release branch. # Usage: ./cloneToWt.sh # Restrictions: # None of the given Git repositories should have the branch with name . # There should be a remote branch origin/ from which a new local branch will be created by this script. # You must use Git 2.5.0 or later. set -e # Any command which returns non-zero exit code will cause this shell script to exit immediately if [[ -z "$1" || -z "$2" ]] ; then echo " Usage: ./cloneToWt.sh Example: ./cloneToWt.sh ~/intellij-go-143 143" exit 1 fi NEW_REPO="$1" BRANCH="$2" if [[ "$BRANCH" == origin/* ]]; then BRANCH="${BRANCH/origin\//}" fi # Absolute path to directory containing existing IntelliJ IDEA repo (and this script as well) OLD_REPO="$(cd "`dirname "$0"`"; pwd)" ROOTS=("/") if [ -d "$NEW_REPO" ]; then echo "Directory '$NEW_REPO' already exists" exit 2 fi for ROOT in ${ROOTS[@]}; do if [[ ! -z `git --git-dir="${OLD_REPO}${ROOT}/.git" --work-tree="${OLD_REPO}${ROOT}" branch --list $BRANCH` ]]; then echo "Branch '$BRANCH' already exists in $ROOT" exit 3 fi done for ROOT in ${ROOTS[@]}; do git --git-dir="${OLD_REPO}${ROOT}/.git" --work-tree="${OLD_REPO}${ROOT}" worktree add -b $BRANCH "${NEW_REPO}${ROOT}" origin/${BRANCH} done cp -a "$OLD_REPO/.idea/workspace.xml" "$NEW_REPO/.idea/" ================================================ FILE: gen/com/goide/GoTypes.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide; import com.intellij.psi.tree.IElementType; import com.intellij.psi.PsiElement; import com.intellij.lang.ASTNode; import com.goide.psi.GoCompositeElementType; import com.goide.stubs.GoElementTypeFactory; import com.goide.psi.GoTokenType; import com.goide.psi.impl.*; public interface GoTypes { IElementType ADD_EXPR = new GoCompositeElementType("ADD_EXPR"); IElementType AND_EXPR = new GoCompositeElementType("AND_EXPR"); IElementType ANONYMOUS_FIELD_DEFINITION = GoElementTypeFactory.stubFactory("ANONYMOUS_FIELD_DEFINITION"); IElementType ARGUMENT_LIST = new GoCompositeElementType("ARGUMENT_LIST"); IElementType ARRAY_OR_SLICE_TYPE = GoElementTypeFactory.stubFactory("ARRAY_OR_SLICE_TYPE"); IElementType ASSIGNMENT_STATEMENT = new GoCompositeElementType("ASSIGNMENT_STATEMENT"); IElementType ASSIGN_OP = new GoCompositeElementType("ASSIGN_OP"); IElementType BLOCK = new GoCompositeElementType("BLOCK"); IElementType BREAK_STATEMENT = new GoCompositeElementType("BREAK_STATEMENT"); IElementType BUILTIN_ARGUMENT_LIST = new GoCompositeElementType("BUILTIN_ARGUMENT_LIST"); IElementType BUILTIN_CALL_EXPR = new GoCompositeElementType("BUILTIN_CALL_EXPR"); IElementType CALL_EXPR = new GoCompositeElementType("CALL_EXPR"); IElementType CHANNEL_TYPE = GoElementTypeFactory.stubFactory("CHANNEL_TYPE"); IElementType COMM_CASE = new GoCompositeElementType("COMM_CASE"); IElementType COMM_CLAUSE = new GoCompositeElementType("COMM_CLAUSE"); IElementType COMPOSITE_LIT = new GoCompositeElementType("COMPOSITE_LIT"); IElementType CONDITIONAL_EXPR = new GoCompositeElementType("CONDITIONAL_EXPR"); IElementType CONST_DECLARATION = new GoCompositeElementType("CONST_DECLARATION"); IElementType CONST_DEFINITION = GoElementTypeFactory.stubFactory("CONST_DEFINITION"); IElementType CONST_SPEC = GoElementTypeFactory.stubFactory("CONST_SPEC"); IElementType CONTINUE_STATEMENT = new GoCompositeElementType("CONTINUE_STATEMENT"); IElementType CONVERSION_EXPR = new GoCompositeElementType("CONVERSION_EXPR"); IElementType DEFER_STATEMENT = new GoCompositeElementType("DEFER_STATEMENT"); IElementType ELEMENT = new GoCompositeElementType("ELEMENT"); IElementType ELSE_STATEMENT = new GoCompositeElementType("ELSE_STATEMENT"); IElementType EXPRESSION = new GoCompositeElementType("EXPRESSION"); IElementType EXPR_CASE_CLAUSE = new GoCompositeElementType("EXPR_CASE_CLAUSE"); IElementType EXPR_SWITCH_STATEMENT = new GoCompositeElementType("EXPR_SWITCH_STATEMENT"); IElementType FALLTHROUGH_STATEMENT = new GoCompositeElementType("FALLTHROUGH_STATEMENT"); IElementType FIELD_DECLARATION = new GoCompositeElementType("FIELD_DECLARATION"); IElementType FIELD_DEFINITION = GoElementTypeFactory.stubFactory("FIELD_DEFINITION"); IElementType FIELD_NAME = new GoCompositeElementType("FIELD_NAME"); IElementType FOR_CLAUSE = new GoCompositeElementType("FOR_CLAUSE"); IElementType FOR_STATEMENT = new GoCompositeElementType("FOR_STATEMENT"); IElementType FUNCTION_DECLARATION = GoElementTypeFactory.stubFactory("FUNCTION_DECLARATION"); IElementType FUNCTION_LIT = new GoCompositeElementType("FUNCTION_LIT"); IElementType FUNCTION_TYPE = GoElementTypeFactory.stubFactory("FUNCTION_TYPE"); IElementType GOTO_STATEMENT = new GoCompositeElementType("GOTO_STATEMENT"); IElementType GO_STATEMENT = new GoCompositeElementType("GO_STATEMENT"); IElementType IF_STATEMENT = new GoCompositeElementType("IF_STATEMENT"); IElementType IMPORT_DECLARATION = new GoCompositeElementType("IMPORT_DECLARATION"); IElementType IMPORT_LIST = new GoCompositeElementType("IMPORT_LIST"); IElementType IMPORT_SPEC = GoElementTypeFactory.stubFactory("IMPORT_SPEC"); IElementType IMPORT_STRING = new GoCompositeElementType("IMPORT_STRING"); IElementType INC_DEC_STATEMENT = new GoCompositeElementType("INC_DEC_STATEMENT"); IElementType INDEX_OR_SLICE_EXPR = new GoCompositeElementType("INDEX_OR_SLICE_EXPR"); IElementType INTERFACE_TYPE = GoElementTypeFactory.stubFactory("INTERFACE_TYPE"); IElementType KEY = new GoCompositeElementType("KEY"); IElementType LABELED_STATEMENT = new GoCompositeElementType("LABELED_STATEMENT"); IElementType LABEL_DEFINITION = GoElementTypeFactory.stubFactory("LABEL_DEFINITION"); IElementType LABEL_REF = new GoCompositeElementType("LABEL_REF"); IElementType LEFT_HAND_EXPR_LIST = new GoCompositeElementType("LEFT_HAND_EXPR_LIST"); IElementType LITERAL = new GoCompositeElementType("LITERAL"); IElementType LITERAL_TYPE_EXPR = new GoCompositeElementType("LITERAL_TYPE_EXPR"); IElementType LITERAL_VALUE = new GoCompositeElementType("LITERAL_VALUE"); IElementType MAP_TYPE = GoElementTypeFactory.stubFactory("MAP_TYPE"); IElementType METHOD_DECLARATION = GoElementTypeFactory.stubFactory("METHOD_DECLARATION"); IElementType METHOD_SPEC = GoElementTypeFactory.stubFactory("METHOD_SPEC"); IElementType MUL_EXPR = new GoCompositeElementType("MUL_EXPR"); IElementType OR_EXPR = new GoCompositeElementType("OR_EXPR"); IElementType PACKAGE_CLAUSE = GoElementTypeFactory.stubFactory("PACKAGE_CLAUSE"); IElementType PARAMETERS = GoElementTypeFactory.stubFactory("PARAMETERS"); IElementType PARAMETER_DECLARATION = GoElementTypeFactory.stubFactory("PARAMETER_DECLARATION"); IElementType PARAM_DEFINITION = GoElementTypeFactory.stubFactory("PARAM_DEFINITION"); IElementType PARENTHESES_EXPR = new GoCompositeElementType("PARENTHESES_EXPR"); IElementType PAR_TYPE = GoElementTypeFactory.stubFactory("PAR_TYPE"); IElementType POINTER_TYPE = GoElementTypeFactory.stubFactory("POINTER_TYPE"); IElementType RANGE_CLAUSE = GoElementTypeFactory.stubFactory("RANGE_CLAUSE"); IElementType RECEIVER = GoElementTypeFactory.stubFactory("RECEIVER"); IElementType RECV_STATEMENT = GoElementTypeFactory.stubFactory("RECV_STATEMENT"); IElementType REFERENCE_EXPRESSION = new GoCompositeElementType("REFERENCE_EXPRESSION"); IElementType RESULT = GoElementTypeFactory.stubFactory("RESULT"); IElementType RETURN_STATEMENT = new GoCompositeElementType("RETURN_STATEMENT"); IElementType SELECTOR_EXPR = new GoCompositeElementType("SELECTOR_EXPR"); IElementType SELECT_STATEMENT = new GoCompositeElementType("SELECT_STATEMENT"); IElementType SEND_STATEMENT = new GoCompositeElementType("SEND_STATEMENT"); IElementType SHORT_VAR_DECLARATION = GoElementTypeFactory.stubFactory("SHORT_VAR_DECLARATION"); IElementType SIGNATURE = GoElementTypeFactory.stubFactory("SIGNATURE"); IElementType SIMPLE_STATEMENT = new GoCompositeElementType("SIMPLE_STATEMENT"); IElementType SPEC_TYPE = GoElementTypeFactory.stubFactory("SPEC_TYPE"); IElementType STATEMENT = new GoCompositeElementType("STATEMENT"); IElementType STRING_LITERAL = new GoCompositeElementType("STRING_LITERAL"); IElementType STRUCT_TYPE = GoElementTypeFactory.stubFactory("STRUCT_TYPE"); IElementType SWITCH_START = new GoCompositeElementType("SWITCH_START"); IElementType SWITCH_STATEMENT = new GoCompositeElementType("SWITCH_STATEMENT"); IElementType TAG = new GoCompositeElementType("TAG"); IElementType TYPE = GoElementTypeFactory.stubFactory("TYPE"); IElementType TYPE_ASSERTION_EXPR = new GoCompositeElementType("TYPE_ASSERTION_EXPR"); IElementType TYPE_CASE_CLAUSE = new GoCompositeElementType("TYPE_CASE_CLAUSE"); IElementType TYPE_DECLARATION = new GoCompositeElementType("TYPE_DECLARATION"); IElementType TYPE_GUARD = new GoCompositeElementType("TYPE_GUARD"); IElementType TYPE_LIST = GoElementTypeFactory.stubFactory("TYPE_LIST"); IElementType TYPE_REFERENCE_EXPRESSION = new GoCompositeElementType("TYPE_REFERENCE_EXPRESSION"); IElementType TYPE_SPEC = GoElementTypeFactory.stubFactory("TYPE_SPEC"); IElementType TYPE_SWITCH_GUARD = new GoCompositeElementType("TYPE_SWITCH_GUARD"); IElementType TYPE_SWITCH_STATEMENT = new GoCompositeElementType("TYPE_SWITCH_STATEMENT"); IElementType UNARY_EXPR = new GoCompositeElementType("UNARY_EXPR"); IElementType VALUE = new GoCompositeElementType("VALUE"); IElementType VAR_DECLARATION = new GoCompositeElementType("VAR_DECLARATION"); IElementType VAR_DEFINITION = GoElementTypeFactory.stubFactory("VAR_DEFINITION"); IElementType VAR_SPEC = GoElementTypeFactory.stubFactory("VAR_SPEC"); IElementType ASSIGN = new GoTokenType("="); IElementType BIT_AND = new GoTokenType("&"); IElementType BIT_AND_ASSIGN = new GoTokenType("&="); IElementType BIT_CLEAR = new GoTokenType("&^"); IElementType BIT_CLEAR_ASSIGN = new GoTokenType("&^="); IElementType BIT_OR = new GoTokenType("|"); IElementType BIT_OR_ASSIGN = new GoTokenType("|="); IElementType BIT_XOR = new GoTokenType("^"); IElementType BIT_XOR_ASSIGN = new GoTokenType("^="); IElementType BREAK = new GoTokenType("break"); IElementType CASE = new GoTokenType("case"); IElementType CHAN = new GoTokenType("chan"); IElementType CHAR = new GoTokenType("char"); IElementType COLON = new GoTokenType(":"); IElementType COMMA = new GoTokenType(","); IElementType COND_AND = new GoTokenType("&&"); IElementType COND_OR = new GoTokenType("||"); IElementType CONST = new GoTokenType("const"); IElementType CONTINUE = new GoTokenType("continue"); IElementType DECIMALI = new GoTokenType("decimali"); IElementType DEFAULT = new GoTokenType("default"); IElementType DEFER = new GoTokenType("defer"); IElementType DOT = new GoTokenType("."); IElementType ELSE = new GoTokenType("else"); IElementType EQ = new GoTokenType("=="); IElementType FALLTHROUGH = new GoTokenType("fallthrough"); IElementType FLOAT = new GoTokenType("float"); IElementType FLOATI = new GoTokenType("floati"); IElementType FOR = new GoTokenType("for"); IElementType FUNC = new GoTokenType("func"); IElementType GO = new GoTokenType("go"); IElementType GOTO = new GoTokenType("goto"); IElementType GREATER = new GoTokenType(">"); IElementType GREATER_OR_EQUAL = new GoTokenType(">="); IElementType HEX = new GoTokenType("hex"); IElementType IDENTIFIER = new GoTokenType("identifier"); IElementType IF = new GoTokenType("if"); IElementType IMPORT = new GoTokenType("import"); IElementType INT = new GoTokenType("int"); IElementType INTERFACE = new GoTokenType("interface"); IElementType LBRACE = new GoTokenType("{"); IElementType LBRACK = new GoTokenType("["); IElementType LESS = new GoTokenType("<"); IElementType LESS_OR_EQUAL = new GoTokenType("<="); IElementType LPAREN = new GoTokenType("("); IElementType MAP = new GoTokenType("map"); IElementType MINUS = new GoTokenType("-"); IElementType MINUS_ASSIGN = new GoTokenType("-="); IElementType MINUS_MINUS = new GoTokenType("--"); IElementType MUL = new GoTokenType("*"); IElementType MUL_ASSIGN = new GoTokenType("*="); IElementType NOT = new GoTokenType("!"); IElementType NOT_EQ = new GoTokenType("!="); IElementType OCT = new GoTokenType("oct"); IElementType PACKAGE = new GoTokenType("package"); IElementType PLUS = new GoTokenType("+"); IElementType PLUS_ASSIGN = new GoTokenType("+="); IElementType PLUS_PLUS = new GoTokenType("++"); IElementType QUOTIENT = new GoTokenType("/"); IElementType QUOTIENT_ASSIGN = new GoTokenType("/="); IElementType RANGE = new GoTokenType("range"); IElementType RAW_STRING = new GoTokenType("raw_string"); IElementType RBRACE = new GoTokenType("}"); IElementType RBRACK = new GoTokenType("]"); IElementType REMAINDER = new GoTokenType("%"); IElementType REMAINDER_ASSIGN = new GoTokenType("%="); IElementType RETURN = new GoTokenType("return"); IElementType RPAREN = new GoTokenType(")"); IElementType SELECT = new GoTokenType("select"); IElementType SEMICOLON = new GoTokenType(";"); IElementType SEMICOLON_SYNTHETIC = new GoTokenType(""); IElementType SEND_CHANNEL = new GoTokenType("<-"); IElementType SHIFT_LEFT = new GoTokenType("<<"); IElementType SHIFT_LEFT_ASSIGN = new GoTokenType("<<="); IElementType SHIFT_RIGHT = new GoTokenType(">>"); IElementType SHIFT_RIGHT_ASSIGN = new GoTokenType(">>="); IElementType STRING = new GoTokenType("string"); IElementType STRUCT = new GoTokenType("struct"); IElementType SWITCH = new GoTokenType("switch"); IElementType TRIPLE_DOT = new GoTokenType("..."); IElementType TYPE_ = new GoTokenType("type"); IElementType VAR = new GoTokenType("var"); IElementType VAR_ASSIGN = new GoTokenType(":="); class Factory { public static PsiElement createElement(ASTNode node) { IElementType type = node.getElementType(); if (type == ADD_EXPR) { return new GoAddExprImpl(node); } else if (type == AND_EXPR) { return new GoAndExprImpl(node); } else if (type == ANONYMOUS_FIELD_DEFINITION) { return new GoAnonymousFieldDefinitionImpl(node); } else if (type == ARGUMENT_LIST) { return new GoArgumentListImpl(node); } else if (type == ARRAY_OR_SLICE_TYPE) { return new GoArrayOrSliceTypeImpl(node); } else if (type == ASSIGNMENT_STATEMENT) { return new GoAssignmentStatementImpl(node); } else if (type == ASSIGN_OP) { return new GoAssignOpImpl(node); } else if (type == BLOCK) { return new GoBlockImpl(node); } else if (type == BREAK_STATEMENT) { return new GoBreakStatementImpl(node); } else if (type == BUILTIN_ARGUMENT_LIST) { return new GoBuiltinArgumentListImpl(node); } else if (type == BUILTIN_CALL_EXPR) { return new GoBuiltinCallExprImpl(node); } else if (type == CALL_EXPR) { return new GoCallExprImpl(node); } else if (type == CHANNEL_TYPE) { return new GoChannelTypeImpl(node); } else if (type == COMM_CASE) { return new GoCommCaseImpl(node); } else if (type == COMM_CLAUSE) { return new GoCommClauseImpl(node); } else if (type == COMPOSITE_LIT) { return new GoCompositeLitImpl(node); } else if (type == CONDITIONAL_EXPR) { return new GoConditionalExprImpl(node); } else if (type == CONST_DECLARATION) { return new GoConstDeclarationImpl(node); } else if (type == CONST_DEFINITION) { return new GoConstDefinitionImpl(node); } else if (type == CONST_SPEC) { return new GoConstSpecImpl(node); } else if (type == CONTINUE_STATEMENT) { return new GoContinueStatementImpl(node); } else if (type == CONVERSION_EXPR) { return new GoConversionExprImpl(node); } else if (type == DEFER_STATEMENT) { return new GoDeferStatementImpl(node); } else if (type == ELEMENT) { return new GoElementImpl(node); } else if (type == ELSE_STATEMENT) { return new GoElseStatementImpl(node); } else if (type == EXPRESSION) { return new GoExpressionImpl(node); } else if (type == EXPR_CASE_CLAUSE) { return new GoExprCaseClauseImpl(node); } else if (type == EXPR_SWITCH_STATEMENT) { return new GoExprSwitchStatementImpl(node); } else if (type == FALLTHROUGH_STATEMENT) { return new GoFallthroughStatementImpl(node); } else if (type == FIELD_DECLARATION) { return new GoFieldDeclarationImpl(node); } else if (type == FIELD_DEFINITION) { return new GoFieldDefinitionImpl(node); } else if (type == FIELD_NAME) { return new GoFieldNameImpl(node); } else if (type == FOR_CLAUSE) { return new GoForClauseImpl(node); } else if (type == FOR_STATEMENT) { return new GoForStatementImpl(node); } else if (type == FUNCTION_DECLARATION) { return new GoFunctionDeclarationImpl(node); } else if (type == FUNCTION_LIT) { return new GoFunctionLitImpl(node); } else if (type == FUNCTION_TYPE) { return new GoFunctionTypeImpl(node); } else if (type == GOTO_STATEMENT) { return new GoGotoStatementImpl(node); } else if (type == GO_STATEMENT) { return new GoGoStatementImpl(node); } else if (type == IF_STATEMENT) { return new GoIfStatementImpl(node); } else if (type == IMPORT_DECLARATION) { return new GoImportDeclarationImpl(node); } else if (type == IMPORT_LIST) { return new GoImportListImpl(node); } else if (type == IMPORT_SPEC) { return new GoImportSpecImpl(node); } else if (type == IMPORT_STRING) { return new GoImportStringImpl(node); } else if (type == INC_DEC_STATEMENT) { return new GoIncDecStatementImpl(node); } else if (type == INDEX_OR_SLICE_EXPR) { return new GoIndexOrSliceExprImpl(node); } else if (type == INTERFACE_TYPE) { return new GoInterfaceTypeImpl(node); } else if (type == KEY) { return new GoKeyImpl(node); } else if (type == LABELED_STATEMENT) { return new GoLabeledStatementImpl(node); } else if (type == LABEL_DEFINITION) { return new GoLabelDefinitionImpl(node); } else if (type == LABEL_REF) { return new GoLabelRefImpl(node); } else if (type == LEFT_HAND_EXPR_LIST) { return new GoLeftHandExprListImpl(node); } else if (type == LITERAL) { return new GoLiteralImpl(node); } else if (type == LITERAL_TYPE_EXPR) { return new GoLiteralTypeExprImpl(node); } else if (type == LITERAL_VALUE) { return new GoLiteralValueImpl(node); } else if (type == MAP_TYPE) { return new GoMapTypeImpl(node); } else if (type == METHOD_DECLARATION) { return new GoMethodDeclarationImpl(node); } else if (type == METHOD_SPEC) { return new GoMethodSpecImpl(node); } else if (type == MUL_EXPR) { return new GoMulExprImpl(node); } else if (type == OR_EXPR) { return new GoOrExprImpl(node); } else if (type == PACKAGE_CLAUSE) { return new GoPackageClauseImpl(node); } else if (type == PARAMETERS) { return new GoParametersImpl(node); } else if (type == PARAMETER_DECLARATION) { return new GoParameterDeclarationImpl(node); } else if (type == PARAM_DEFINITION) { return new GoParamDefinitionImpl(node); } else if (type == PARENTHESES_EXPR) { return new GoParenthesesExprImpl(node); } else if (type == PAR_TYPE) { return new GoParTypeImpl(node); } else if (type == POINTER_TYPE) { return new GoPointerTypeImpl(node); } else if (type == RANGE_CLAUSE) { return new GoRangeClauseImpl(node); } else if (type == RECEIVER) { return new GoReceiverImpl(node); } else if (type == RECV_STATEMENT) { return new GoRecvStatementImpl(node); } else if (type == REFERENCE_EXPRESSION) { return new GoReferenceExpressionImpl(node); } else if (type == RESULT) { return new GoResultImpl(node); } else if (type == RETURN_STATEMENT) { return new GoReturnStatementImpl(node); } else if (type == SELECTOR_EXPR) { return new GoSelectorExprImpl(node); } else if (type == SELECT_STATEMENT) { return new GoSelectStatementImpl(node); } else if (type == SEND_STATEMENT) { return new GoSendStatementImpl(node); } else if (type == SHORT_VAR_DECLARATION) { return new GoShortVarDeclarationImpl(node); } else if (type == SIGNATURE) { return new GoSignatureImpl(node); } else if (type == SIMPLE_STATEMENT) { return new GoSimpleStatementImpl(node); } else if (type == SPEC_TYPE) { return new GoSpecTypeImpl(node); } else if (type == STATEMENT) { return new GoStatementImpl(node); } else if (type == STRING_LITERAL) { return new GoStringLiteralImpl(node); } else if (type == STRUCT_TYPE) { return new GoStructTypeImpl(node); } else if (type == SWITCH_START) { return new GoSwitchStartImpl(node); } else if (type == SWITCH_STATEMENT) { return new GoSwitchStatementImpl(node); } else if (type == TAG) { return new GoTagImpl(node); } else if (type == TYPE) { return new GoTypeImpl(node); } else if (type == TYPE_ASSERTION_EXPR) { return new GoTypeAssertionExprImpl(node); } else if (type == TYPE_CASE_CLAUSE) { return new GoTypeCaseClauseImpl(node); } else if (type == TYPE_DECLARATION) { return new GoTypeDeclarationImpl(node); } else if (type == TYPE_GUARD) { return new GoTypeGuardImpl(node); } else if (type == TYPE_LIST) { return new GoTypeListImpl(node); } else if (type == TYPE_REFERENCE_EXPRESSION) { return new GoTypeReferenceExpressionImpl(node); } else if (type == TYPE_SPEC) { return new GoTypeSpecImpl(node); } else if (type == TYPE_SWITCH_GUARD) { return new GoTypeSwitchGuardImpl(node); } else if (type == TYPE_SWITCH_STATEMENT) { return new GoTypeSwitchStatementImpl(node); } else if (type == UNARY_EXPR) { return new GoUnaryExprImpl(node); } else if (type == VALUE) { return new GoValueImpl(node); } else if (type == VAR_DECLARATION) { return new GoVarDeclarationImpl(node); } else if (type == VAR_DEFINITION) { return new GoVarDefinitionImpl(node); } else if (type == VAR_SPEC) { return new GoVarSpecImpl(node); } throw new AssertionError("Unknown element type: " + type); } } } ================================================ FILE: gen/com/goide/lexer/_GoLexer.java ================================================ /* The following code was generated by JFlex 1.7.0-SNAPSHOT tweaked for IntelliJ platform */ package com.goide.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.tree.IElementType; import com.goide.GoTypes; import static com.intellij.psi.TokenType.BAD_CHARACTER; import static com.goide.GoParserDefinition.*; /** * This class is a scanner generated by * JFlex 1.7.0-SNAPSHOT * from the specification file go.flex */ public class _GoLexer implements FlexLexer, GoTypes { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; public static final int MAYBE_SEMICOLON = 2; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 }; /** * Translates characters to character classes * Chosen bits are [11, 6, 4] * Total runtime size is 13792 bytes */ public static int ZZ_CMAP(int ch) { return ZZ_CMAP_A[(ZZ_CMAP_Y[(ZZ_CMAP_Z[ch>>10]<<6)|((ch>>4)&0x3f)]<<4)|(ch&0xf)]; } /* The ZZ_CMAP_Z table has 1088 entries */ static final char ZZ_CMAP_Z[] = zzUnpackCMap( "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7\1\10\2\11\1\12\1\13\6\14\1\15\23\14\1\16"+ "\1\14\1\17\1\20\12\14\1\21\10\11\1\22\1\23\1\24\1\25\1\26\1\27\1\30\1\31\1"+ "\32\1\11\1\33\1\34\2\11\1\14\1\35\3\11\1\36\10\11\1\37\1\40\20\11\1\41\2\11"+ "\1\42\5\11\1\43\4\11\1\44\1\45\4\11\51\14\1\46\3\14\1\47\1\50\4\14\1\51\12"+ "\11\1\52\u0381\11"); /* The ZZ_CMAP_Y table has 2752 entries */ static final char ZZ_CMAP_Y[] = zzUnpackCMap( "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\1\1\11\1\12\1\13\1\14\1\13\1\14\34"+ "\13\1\15\1\16\1\17\10\1\1\20\1\21\1\13\1\22\4\13\1\23\10\13\1\24\12\13\1\25"+ "\1\13\1\26\1\25\1\13\1\27\4\1\1\13\1\30\1\31\2\1\2\13\1\30\1\1\1\32\1\25\5"+ "\13\1\33\1\34\1\35\1\1\1\36\1\13\1\1\1\37\5\13\1\40\1\41\1\42\1\13\1\30\1"+ "\43\1\13\1\44\1\45\1\1\1\13\1\46\4\1\1\13\1\47\4\1\1\50\2\13\1\51\1\1\1\52"+ "\1\53\1\25\1\54\1\55\1\56\1\57\1\60\1\61\1\53\1\16\1\62\1\55\1\56\1\63\1\1"+ "\1\64\1\65\1\66\1\67\1\22\1\56\1\70\1\1\1\71\1\53\1\72\1\73\1\55\1\56\1\70"+ "\1\1\1\61\1\53\1\41\1\74\1\75\1\76\1\77\1\1\1\71\1\65\1\1\1\100\1\36\1\56"+ "\1\51\1\1\1\101\1\53\1\1\1\100\1\36\1\56\1\102\1\1\1\60\1\53\1\103\1\100\1"+ "\36\1\13\1\104\1\60\1\105\1\53\1\106\1\107\1\110\1\13\1\111\1\112\1\1\1\65"+ "\1\1\1\25\2\13\1\113\1\112\1\114\2\1\1\115\1\116\1\117\1\120\1\121\1\122\2"+ "\1\1\71\1\1\1\114\1\1\1\123\1\13\1\124\1\1\1\125\7\1\2\13\1\30\1\105\1\114"+ "\1\126\1\127\1\130\1\131\1\114\2\13\1\132\2\13\1\133\24\13\1\134\1\135\2\13"+ "\1\134\2\13\1\136\1\137\1\14\3\13\1\137\3\13\1\30\2\1\1\13\1\1\5\13\1\140"+ "\1\25\45\13\1\141\1\13\1\25\1\30\4\13\1\30\1\142\1\143\1\16\1\13\1\16\1\13"+ "\1\16\1\143\1\71\3\13\1\144\1\1\1\145\1\114\2\1\1\114\5\13\1\27\2\13\1\146"+ "\4\13\1\40\1\13\1\147\2\1\1\65\1\13\1\150\1\47\2\13\1\151\1\13\1\77\1\114"+ "\2\1\1\13\1\112\3\13\1\47\2\1\2\114\1\152\5\1\1\107\2\13\1\144\1\153\1\114"+ "\2\1\1\154\1\13\1\155\1\42\2\13\1\40\1\1\2\13\1\144\1\1\1\156\1\42\1\13\1"+ "\150\6\1\1\157\1\160\14\13\4\1\21\13\1\140\2\13\1\140\1\161\1\13\1\150\3\13"+ "\1\162\1\163\1\164\1\124\1\163\2\1\1\165\4\1\1\166\1\1\1\124\6\1\1\167\1\170"+ "\1\171\1\172\1\173\3\1\1\174\147\1\2\13\1\147\2\13\1\147\10\13\1\175\1\176"+ "\2\13\1\132\3\13\1\177\1\1\1\13\1\112\4\200\4\1\1\105\35\1\1\201\2\1\1\202"+ "\1\25\4\13\1\203\1\25\4\13\1\133\1\107\1\13\1\150\1\25\4\13\1\147\1\1\1\13"+ "\1\30\3\1\1\13\40\1\133\13\1\40\4\1\135\13\1\40\2\1\10\13\1\124\4\1\2\13\1"+ "\150\20\13\1\124\1\13\1\204\1\1\2\13\1\147\1\105\1\13\1\150\4\13\1\40\2\1"+ "\1\205\1\206\5\13\1\207\1\13\1\150\1\27\3\1\1\205\1\210\1\13\1\31\1\1\3\13"+ "\1\144\1\206\2\13\1\144\1\1\1\114\1\1\1\211\1\42\1\13\1\40\1\13\1\112\1\1"+ "\1\13\1\124\1\50\2\13\1\31\1\105\1\114\1\212\1\213\2\13\1\46\1\1\1\214\1\114"+ "\1\13\1\215\3\13\1\216\1\217\1\220\1\30\1\66\1\221\1\222\1\200\2\13\1\133"+ "\1\40\7\13\1\31\1\114\72\13\1\144\1\13\1\223\2\13\1\151\20\1\26\13\1\150\6"+ "\13\1\77\2\1\1\112\1\224\1\56\1\225\1\226\6\13\1\16\1\1\1\154\25\13\1\150"+ "\1\1\4\13\1\206\2\13\1\27\2\1\1\151\7\1\1\212\7\13\1\124\1\1\1\114\1\25\1"+ "\30\1\25\1\30\1\227\4\13\1\147\1\230\1\231\2\1\1\232\1\13\1\14\1\233\2\150"+ "\2\1\7\13\1\30\30\1\1\13\1\124\3\13\1\71\2\1\2\13\1\1\1\13\1\234\2\13\1\40"+ "\1\13\1\150\2\13\1\235\3\1\11\13\1\150\1\114\5\1\2\13\1\27\3\13\1\144\11\1"+ "\23\13\1\112\1\13\1\40\1\27\11\1\1\236\2\13\1\237\1\13\1\40\1\13\1\112\1\13"+ "\1\147\4\1\1\13\1\240\1\13\1\40\1\13\1\77\4\1\3\13\1\241\4\1\1\71\1\242\1"+ "\13\1\144\2\1\1\13\1\124\1\13\1\124\2\1\1\123\1\13\1\47\1\1\3\13\1\40\1\13"+ "\1\40\1\13\1\31\1\13\1\16\6\1\4\13\1\46\3\1\3\13\1\31\3\13\1\31\60\1\1\154"+ "\2\13\1\27\2\1\1\65\1\1\1\154\2\13\2\1\1\13\1\46\1\114\1\154\1\13\1\112\1"+ "\65\1\1\2\13\1\243\1\154\2\13\1\31\1\244\1\245\2\1\1\13\1\22\1\151\5\1\1\246"+ "\1\247\1\46\2\13\1\147\1\1\1\114\1\73\1\55\1\56\1\70\1\1\1\250\1\16\21\1\3"+ "\13\1\1\1\251\1\114\12\1\2\13\1\147\2\1\1\252\2\1\3\13\1\1\1\253\1\114\2\1"+ "\2\13\1\30\1\1\1\114\3\1\1\13\1\77\1\1\1\114\26\1\4\13\1\114\1\105\34\1\3"+ "\13\1\46\20\1\71\13\1\77\16\1\14\13\1\144\53\1\2\13\1\147\75\1\44\13\1\112"+ "\33\1\43\13\1\46\1\13\1\147\1\114\6\1\1\13\1\150\1\1\3\13\1\1\1\144\1\114"+ "\1\154\1\254\1\13\67\1\4\13\1\47\1\71\3\1\1\154\6\1\1\16\77\1\6\13\1\30\1"+ "\124\1\46\1\77\66\1\5\13\1\212\3\13\1\143\1\255\1\256\1\257\3\13\1\260\1\261"+ "\1\13\1\262\1\263\1\36\24\13\1\264\1\13\1\36\1\133\1\13\1\133\1\13\1\212\1"+ "\13\1\212\1\147\1\13\1\147\1\13\1\56\1\13\1\56\1\13\1\265\3\266\14\13\1\47"+ "\123\1\1\257\1\13\1\267\1\270\1\271\1\272\1\273\1\274\1\275\1\151\1\276\1"+ "\151\24\1\55\13\1\112\2\1\103\13\1\47\15\13\1\150\150\13\1\16\25\1\41\13\1"+ "\150\36\1"); /* The ZZ_CMAP_A table has 3056 entries */ static final char ZZ_CMAP_A[] = zzUnpackCMap( "\11\0\1\4\1\2\1\1\1\5\1\3\22\0\1\4\1\47\1\23\2\0\1\54\1\51\1\31\1\41\1\42"+ "\1\7\1\50\1\45\1\21\1\22\1\6\1\15\7\14\1\26\1\13\1\43\1\44\1\53\1\46\1\55"+ "\2\0\4\12\1\20\1\12\16\10\1\25\2\10\1\17\2\10\1\37\1\24\1\40\1\52\1\10\1\33"+ "\1\61\1\56\1\71\1\73\1\60\1\30\1\67\1\65\1\72\1\10\1\62\1\63\1\76\1\70\1\66"+ "\1\74\1\10\1\57\1\75\1\64\1\32\1\27\1\77\1\16\1\100\1\10\1\35\1\34\1\36\7"+ "\0\1\1\24\0\1\10\12\0\1\10\4\0\1\10\5\0\27\10\1\0\12\10\4\0\14\10\16\0\5\10"+ "\7\0\1\10\1\0\1\10\1\0\5\10\1\0\2\10\2\0\4\10\1\0\1\10\6\0\1\10\1\0\3\10\1"+ "\0\1\10\1\0\4\10\1\0\23\10\1\0\13\10\10\0\6\10\1\0\26\10\2\0\1\10\6\0\10\10"+ "\10\0\13\10\5\0\3\10\15\0\12\11\4\0\6\10\1\0\1\10\17\0\2\10\7\0\2\10\12\11"+ "\3\10\2\0\2\10\1\0\16\10\15\0\11\10\13\0\1\10\16\0\12\11\6\10\4\0\2\10\4\0"+ "\1\10\5\0\6\10\4\0\1\10\11\0\1\10\3\0\1\10\7\0\11\10\7\0\5\10\17\0\26\10\3"+ "\0\1\10\2\0\1\10\7\0\12\10\4\0\12\11\1\10\4\0\10\10\2\0\2\10\2\0\26\10\1\0"+ "\7\10\1\0\1\10\3\0\4\10\3\0\1\10\20\0\1\10\15\0\2\10\1\0\1\10\5\0\6\10\4\0"+ "\2\10\1\0\2\10\1\0\2\10\1\0\2\10\17\0\4\10\1\0\1\10\7\0\12\11\2\0\3\10\20"+ "\0\11\10\1\0\2\10\1\0\2\10\1\0\5\10\3\0\1\10\2\0\1\10\30\0\1\10\13\0\10\10"+ "\2\0\1\10\3\0\1\10\1\0\6\10\3\0\3\10\1\0\4\10\3\0\2\10\1\0\1\10\1\0\2\10\3"+ "\0\2\10\3\0\3\10\3\0\14\10\13\0\10\10\1\0\2\10\10\0\3\10\5\0\4\10\1\0\5\10"+ "\3\0\1\10\3\0\2\10\15\0\13\10\2\0\1\10\21\0\1\10\12\0\6\10\5\0\22\10\3\0\10"+ "\10\1\0\11\10\1\0\1\10\2\0\7\10\11\0\1\10\1\0\2\10\14\0\12\11\7\0\2\10\1\0"+ "\1\10\2\0\2\10\1\0\1\10\2\0\1\10\6\0\4\10\1\0\7\10\1\0\3\10\1\0\1\10\1\0\1"+ "\10\2\0\2\10\1\0\4\10\1\0\2\10\11\0\1\10\2\0\5\10\1\0\1\10\11\0\12\11\2\0"+ "\14\10\1\0\24\10\13\0\5\10\3\0\6\10\4\0\4\10\3\0\1\10\3\0\2\10\7\0\3\10\4"+ "\0\15\10\14\0\1\10\1\0\6\10\1\0\1\10\5\0\1\10\2\0\13\10\1\0\15\10\1\0\4\10"+ "\2\0\7\10\1\0\1\10\1\0\4\10\2\0\1\10\1\0\4\10\2\0\7\10\1\0\1\10\1\0\4\10\2"+ "\0\16\10\2\0\6\10\2\0\15\10\2\0\1\10\1\0\10\10\7\0\15\10\1\0\6\10\23\0\1\10"+ "\4\0\1\10\3\0\11\10\1\0\1\10\5\0\17\10\1\0\16\10\2\0\14\10\13\0\1\10\15\0"+ "\7\10\7\0\16\10\15\0\2\10\12\11\3\0\3\10\11\0\4\10\1\0\4\10\3\0\2\10\11\0"+ "\10\10\1\0\1\10\1\0\1\10\1\0\1\10\1\0\6\10\1\0\7\10\1\0\1\10\3\0\3\10\1\0"+ "\7\10\3\0\4\10\2\0\6\10\14\0\2\1\7\0\1\10\15\0\1\10\2\0\1\10\4\0\1\10\2\0"+ "\12\10\1\0\1\10\3\0\5\10\6\0\1\10\1\0\1\10\1\0\1\10\1\0\4\10\1\0\13\10\2\0"+ "\4\10\5\0\5\10\4\0\1\10\4\0\2\10\13\0\5\10\6\0\4\10\3\0\2\10\14\0\10\10\7"+ "\0\10\10\1\0\7\10\6\0\2\10\12\0\5\10\5\0\2\10\3\0\7\10\6\0\3\10\12\11\2\10"+ "\13\0\11\10\2\0\27\10\2\0\7\10\1\0\3\10\1\0\4\10\1\0\4\10\2\0\6\10\3\0\1\10"+ "\1\0\1\10\2\0\5\10\1\0\12\10\12\11\5\10\1\0\3\10\1\0\10\10\4\0\7\10\3\0\1"+ "\10\3\0\2\10\1\0\1\10\3\0\2\10\2\0\5\10\2\0\1\10\1\0\1\10\30\0\3\10\3\0\6"+ "\10\2\0\6\10\2\0\6\10\11\0\7\10\4\0\5\10\3\0\5\10\5\0\1\10\1\0\10\10\1\0\5"+ "\10\1\0\1\10\1\0\2\10\1\0\2\10\1\0\12\10\6\0\12\10\2\0\6\10\2\0\6\10\2\0\6"+ "\10\2\0\3\10\3\0\14\10\1\0\16\10\1\0\2\10\1\0\2\10\1\0\10\10\6\0\4\10\4\0"+ "\16\10\2\0\1\10\1\0\14\10\1\0\2\10\3\0\1\10\2\0\4\10\1\0\2\10\12\0\10\10\6"+ "\0\6\10\1\0\3\10\1\0\12\10\3\0\1\10\12\0\4\10\13\0\12\11\1\10\1\0\1\10\3\0"+ "\7\10\1\0\1\10\1\0\4\10\1\0\17\10\1\0\2\10\14\0\3\10\4\0\2\10\1\0\1\10\20"+ "\0\4\10\10\0\1\10\13\0\10\10\5\0\3\10\2\0\1\10\2\0\2\10\2\0\4\10\1\0\14\10"+ "\1\0\1\10\1\0\7\10\1\0\21\10\1\0\4\10\2\0\10\10\1\0\7\10\1\0\14\10\1\0\4\10"+ "\1\0\5\10\1\0\1\10\3\0\14\10\2\0\13\10\1\0\10\10\2\0\22\11\1\0\2\10\1\0\1"+ "\10\2\0\1\10\1\0\12\10\1\0\4\10\1\0\1\10\1\0\1\10\6\0\1\10\4\0\1\10\1\0\1"+ "\10\1\0\1\10\1\0\3\10\1\0\2\10\1\0\1\10\2\0\1\10\1\0\1\10\1\0\1\10\1\0\1\10"+ "\1\0\1\10\1\0\2\10\1\0\1\10\2\0\4\10\1\0\7\10\1\0\4\10\1\0\4\10\1\0\1\10\1"+ "\0\12\10\1\0\5\10\1\0\3\10\1\0\5\10\1\0\5\10"); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\1\1\1\2\2\3\1\4\1\5\1\6\1\1"+ "\2\7\1\10\1\11\1\12\2\6\1\1\1\13\1\14"+ "\1\15\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ "\1\25\1\26\1\27\1\30\1\31\1\32\1\33\1\34"+ "\1\35\13\6\1\36\2\37\1\36\1\40\1\41\1\42"+ "\1\43\2\0\1\44\1\45\1\46\1\0\1\47\1\50"+ "\1\0\1\12\1\0\4\6\1\51\1\0\1\13\1\52"+ "\1\53\1\54\1\55\1\56\1\57\1\60\1\61\1\62"+ "\1\63\1\64\1\65\1\66\1\67\1\70\1\71\1\72"+ "\5\6\1\73\3\6\1\74\10\6\1\41\1\44\1\0"+ "\1\75\1\76\1\77\1\100\2\6\1\101\1\51\3\0"+ "\1\102\1\0\1\103\1\104\1\105\20\6\1\106\1\41"+ "\1\0\1\107\1\6\4\0\3\6\1\110\1\111\1\112"+ "\1\113\1\114\13\6\1\0\1\115\1\6\1\116\1\6"+ "\1\117\2\6\1\120\6\6\1\0\1\121\2\6\1\122"+ "\2\6\1\123\1\124\1\125\3\6\1\126\1\127\1\6"+ "\1\130\2\6\1\131\1\6\1\132"; private static int [] zzUnpackAction() { int [] result = new int[209]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\101\0\202\0\303\0\202\0\303\0\u0104\0\u0145"+ "\0\u0186\0\u01c7\0\u0208\0\u0249\0\u028a\0\u02cb\0\u030c\0\u034d"+ "\0\u038e\0\u03cf\0\u0410\0\u0451\0\202\0\202\0\202\0\202"+ "\0\202\0\202\0\u0492\0\202\0\202\0\u04d3\0\u0514\0\u0555"+ "\0\u0596\0\u05d7\0\u0618\0\u0659\0\u069a\0\u06db\0\u071c\0\u075d"+ "\0\u079e\0\u07df\0\u0820\0\u0861\0\u08a2\0\u08e3\0\u0924\0\u0965"+ "\0\202\0\202\0\u09a6\0\u09e7\0\u0a28\0\u0a69\0\202\0\202"+ "\0\u01c7\0\u0aaa\0\u0aeb\0\202\0\u0b2c\0\u0b6d\0\202\0\202"+ "\0\u0bae\0\202\0\u0bef\0\u0c30\0\u0c71\0\u0cb2\0\u0cf3\0\u0d34"+ "\0\u0d75\0\202\0\202\0\202\0\202\0\202\0\202\0\202"+ "\0\202\0\202\0\202\0\u0db6\0\202\0\202\0\202\0\u0df7"+ "\0\202\0\202\0\u0e38\0\u0e79\0\u0eba\0\u0efb\0\u0f3c\0\u0f7d"+ "\0\u0fbe\0\u0fff\0\u1040\0\u1081\0\u0186\0\u10c2\0\u1103\0\u1144"+ "\0\u1185\0\u11c6\0\u1207\0\u1248\0\u1289\0\u12ca\0\u130b\0\u134c"+ "\0\202\0\u0b6d\0\202\0\u0186\0\u138d\0\u13ce\0\u0186\0\202"+ "\0\u140f\0\u1450\0\u1491\0\u0d34\0\u14d2\0\202\0\202\0\202"+ "\0\u1513\0\u1554\0\u1595\0\u15d6\0\u1617\0\u1658\0\u1699\0\u16da"+ "\0\u171b\0\u175c\0\u179d\0\u17de\0\u181f\0\u1860\0\u18a1\0\u18e2"+ "\0\u0186\0\202\0\u12ca\0\u0186\0\u1923\0\u1964\0\u19a5\0\u19e6"+ "\0\u1a27\0\u1a68\0\u1aa9\0\u1aea\0\u0186\0\u0186\0\u0186\0\u0186"+ "\0\u0186\0\u1b2b\0\u1b6c\0\u1bad\0\u1bee\0\u1c2f\0\u1c70\0\u1cb1"+ "\0\u1cf2\0\u1d33\0\u1d74\0\u1db5\0\u1df6\0\u0186\0\u1e37\0\u0186"+ "\0\u1e78\0\u0186\0\u1eb9\0\u1efa\0\u0186\0\u1f3b\0\u1f7c\0\u1fbd"+ "\0\u1ffe\0\u203f\0\u2080\0\u20c1\0\u0186\0\u2102\0\u2143\0\u0186"+ "\0\u2184\0\u21c5\0\u0186\0\u0186\0\u0186\0\u2206\0\u2247\0\u2288"+ "\0\u0186\0\u0186\0\u22c9\0\u0186\0\u230a\0\u234b\0\u0186\0\u238c"+ "\0\u0186"; private static int [] zzUnpackRowMap() { int [] result = new int[209]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\3\3\4\1\5\1\6\1\7\1\10\1\11\1\12"+ "\1\11\2\13\1\14\3\11\1\15\1\16\1\17\1\3"+ "\1\11\1\13\1\20\1\21\1\22\1\11\1\23\1\24"+ "\1\25\1\26\1\27\1\30\1\31\1\32\1\33\1\34"+ "\1\35\1\36\1\37\1\40\1\41\1\42\1\43\1\44"+ "\1\45\1\46\1\47\1\50\3\11\1\51\2\11\1\52"+ "\1\11\1\53\1\54\1\55\1\56\1\57\1\60\2\11"+ "\1\61\2\62\1\63\2\5\1\64\72\61\102\0\3\4"+ "\1\0\1\4\101\0\1\65\1\66\36\0\1\67\100\0"+ "\1\70\42\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\23\11\11\0\1\71\1\0\3\71\2\0\1\72\1\0"+ "\1\73\3\0\1\71\31\0\1\72\11\0\1\74\17\0"+ "\1\71\1\0\3\13\2\0\1\72\1\0\1\73\3\0"+ "\1\13\31\0\1\72\11\0\1\74\17\0\1\71\1\0"+ "\1\71\2\75\2\76\1\72\1\0\1\73\3\0\1\71"+ "\31\0\1\72\11\0\1\74\27\0\1\77\24\0\1\100"+ "\43\0\1\73\1\0\3\73\4\0\1\101\3\0\1\73"+ "\52\0\2\17\2\0\17\17\1\102\1\103\54\17\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\3\11\1\104"+ "\17\11\10\0\11\11\4\0\4\11\1\0\1\105\23\0"+ "\3\11\1\106\4\11\1\107\12\11\24\110\1\111\54\110"+ "\33\23\1\112\45\23\34\0\1\113\11\0\1\114\100\0"+ "\1\115\100\0\1\116\100\0\1\117\100\0\1\120\1\0"+ "\1\121\76\0\1\122\2\0\1\123\1\124\74\0\1\125"+ "\53\0\1\126\24\0\1\127\4\0\1\130\73\0\1\131"+ "\100\0\1\132\6\0\1\133\33\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\1\11\1\134\21\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\2\11\1\135\1\136"+ "\17\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\5\11\1\137\15\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\22\11\1\140\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\10\11\1\141\12\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\3\11\1\142\3\11"+ "\1\143\1\144\12\11\10\0\11\11\4\0\3\11\1\145"+ "\1\0\1\11\23\0\12\11\1\146\5\11\1\147\2\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\2\11"+ "\1\150\20\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\3\11\1\151\17\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\2\11\1\152\3\11\1\153\12\11"+ "\1\154\1\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\3\11\1\155\17\11\2\0\1\62\104\0\1\65"+ "\1\66\71\0\2\65\2\0\75\65\7\66\1\156\71\66"+ "\11\0\1\157\1\0\3\157\3\0\1\160\4\0\1\157"+ "\21\0\1\160\41\0\1\73\1\0\3\73\2\0\1\72"+ "\5\0\1\73\31\0\1\72\11\0\1\161\17\0\1\71"+ "\1\0\1\71\2\75\2\0\1\72\1\0\1\73\3\0"+ "\1\71\31\0\1\72\11\0\1\74\20\0\4\162\2\0"+ "\1\162\5\0\1\162\1\0\1\162\25\0\1\162\1\0"+ "\2\162\7\0\1\162\1\0\1\162\27\0\1\163\72\0"+ "\3\17\4\0\6\17\1\0\1\17\23\0\2\17\1\0"+ "\1\17\2\0\1\17\3\0\1\17\20\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\1\11\1\164\21\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\12\11\1\165"+ "\10\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\5\11\1\166\15\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\1\11\1\167\21\11\31\0\1\170\63\0"+ "\2\171\1\172\5\0\1\110\1\173\1\0\2\110\1\174"+ "\1\175\23\0\2\110\1\0\1\110\2\0\1\110\3\0"+ "\1\110\56\0\1\176\100\0\1\177\100\0\1\200\42\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\2\11\1\201"+ "\20\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\6\11\1\202\14\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\12\11\1\203\10\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\17\11\1\204\3\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\16\11\1\205"+ "\4\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\6\11\1\206\14\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\17\11\1\207\3\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\3\11\1\210\17\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\12\11\1\211"+ "\10\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\6\11\1\212\14\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\16\11\1\213\4\11\10\0\11\11\4\0"+ "\3\11\1\214\1\0\1\11\23\0\23\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\13\11\1\215\7\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\5\11"+ "\1\216\15\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\1\11\1\217\21\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\14\11\1\220\6\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\16\11\1\221\4\11"+ "\6\66\1\222\1\223\71\66\11\0\1\157\1\0\3\157"+ "\10\0\1\157\43\0\1\161\17\0\1\157\1\0\3\157"+ "\10\0\1\157\62\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\13\11\1\224\7\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\5\11\1\225\15\11\14\0\2\226"+ "\75\0\4\227\2\0\1\227\5\0\1\227\1\0\1\227"+ "\25\0\1\227\1\0\2\227\7\0\1\227\1\0\1\227"+ "\17\0\4\230\2\0\1\230\5\0\1\230\1\0\1\230"+ "\25\0\1\230\1\0\2\230\7\0\1\230\1\0\1\230"+ "\17\0\4\231\2\0\1\231\5\0\1\231\1\0\1\231"+ "\25\0\1\231\1\0\2\231\7\0\1\231\1\0\1\231"+ "\15\0\11\11\4\0\4\11\1\0\1\11\23\0\3\11"+ "\1\232\17\11\10\0\11\11\4\0\4\11\1\0\1\233"+ "\23\0\23\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\11\11\1\234\11\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\2\11\1\235\20\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\2\11\1\236\20\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\10\11"+ "\1\237\12\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\2\11\1\240\20\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\12\11\1\241\10\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\6\11\1\242\10\11"+ "\1\243\3\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\2\11\1\244\20\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\10\11\1\245\12\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\2\11\1\246\1\247"+ "\17\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\4\11\1\250\16\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\2\11\1\251\20\11\10\0\11\11\4\0"+ "\4\11\1\0\1\252\23\0\23\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\6\11\1\253\14\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\6\11\1\254"+ "\14\11\14\0\2\110\75\0\4\110\2\0\1\110\5\0"+ "\1\110\1\0\1\110\25\0\1\110\1\0\2\110\7\0"+ "\1\110\1\0\1\110\17\0\4\255\2\0\1\255\5\0"+ "\1\255\1\0\1\255\25\0\1\255\1\0\2\255\7\0"+ "\1\255\1\0\1\255\17\0\4\172\2\0\1\172\5\0"+ "\1\172\1\0\1\172\25\0\1\172\1\0\2\172\7\0"+ "\1\172\1\0\1\172\15\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\4\11\1\256\16\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\1\11\1\257\21\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\2\11\1\260"+ "\20\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\14\11\1\261\6\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\6\11\1\262\14\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\1\11\1\263\21\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\1\11\1\264"+ "\21\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\1\11\1\265\21\11\10\0\11\11\4\0\4\11\1\0"+ "\1\266\23\0\23\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\3\11\1\267\17\11\10\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\13\11\1\270\7\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\13\11\1\271"+ "\7\11\10\0\11\11\4\0\4\11\1\0\1\11\23\0"+ "\13\11\1\272\7\11\10\0\11\11\4\0\4\11\1\0"+ "\1\11\23\0\7\11\1\273\13\11\12\0\4\274\2\0"+ "\1\274\5\0\1\274\1\0\1\274\25\0\1\274\1\0"+ "\2\274\7\0\1\274\1\0\1\274\15\0\11\11\4\0"+ "\4\11\1\0\1\11\23\0\12\11\1\275\10\11\10\0"+ "\11\11\4\0\4\11\1\0\1\11\23\0\12\11\1\276"+ "\10\11\10\0\11\11\4\0\3\11\1\277\1\0\1\11"+ "\23\0\23\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\6\11\1\300\14\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\5\11\1\301\15\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\11\11\1\302\11\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\6\11"+ "\1\303\14\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\6\11\1\304\14\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\7\11\1\305\13\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\1\11\1\306\21\11"+ "\12\0\4\175\2\0\1\175\5\0\1\175\1\0\1\175"+ "\25\0\1\175\1\0\2\175\7\0\1\175\1\0\1\175"+ "\15\0\11\11\4\0\4\11\1\0\1\307\23\0\23\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\3\11"+ "\1\310\17\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\6\11\1\311\14\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\2\11\1\312\20\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\10\11\1\313\12\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\2\11"+ "\1\314\20\11\10\0\11\11\4\0\4\11\1\0\1\11"+ "\23\0\13\11\1\315\7\11\10\0\11\11\4\0\4\11"+ "\1\0\1\316\23\0\23\11\10\0\11\11\4\0\4\11"+ "\1\0\1\11\23\0\2\11\1\317\20\11\10\0\11\11"+ "\4\0\4\11\1\0\1\11\23\0\11\11\1\320\11\11"+ "\10\0\11\11\4\0\4\11\1\0\1\11\23\0\7\11"+ "\1\321\13\11"; private static int [] zzUnpackTrans() { int [] result = new int[9165]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String[] ZZ_ERROR_MSG = { "Unknown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state aState */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\0\1\11\1\1\1\11\17\1\6\11\1\1\2\11"+ "\23\1\2\11\4\1\2\11\2\0\1\1\1\11\1\1"+ "\1\0\2\11\1\0\1\11\1\0\5\1\1\0\12\11"+ "\1\1\3\11\1\1\2\11\25\1\1\0\1\11\1\1"+ "\1\11\4\1\1\11\3\0\1\1\1\0\3\11\21\1"+ "\1\11\1\0\2\1\4\0\23\1\1\0\16\1\1\0"+ "\25\1"; private static int [] zzUnpackAttribute() { int [] result = new int[209]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /* user code: */ public _GoLexer() { this((java.io.Reader)null); } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public _GoLexer(java.io.Reader in) { this.zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { int size = 0; for (int i = 0, length = packed.length(); i < length; i += 2) { size += packed.charAt(i); } char[] map = new char[size]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < packed.length()) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } public final int getTokenStart() { return zzStartRead; } public final int getTokenEnd() { return getTokenStart() + yylength(); } public void reset(CharSequence buffer, int start, int end, int initialState) { zzBuffer = buffer; zzCurrentPos = zzMarkedPos = zzStartRead = start; zzAtEOF = false; zzAtBOL = true; zzEndRead = end; yybegin(initialState); } /** * Refills the input buffer. * * @return false, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { return true; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position pos from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; // set up zzAction for empty match case: int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; } zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL/*, zzEndReadL*/); zzCurrentPosL += Character.charCount(zzInput); } else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL/*, zzEndReadL*/); zzCurrentPosL += Character.charCount(zzInput); } } int zzNext = zzTransL[ zzRowMapL[zzState] + ZZ_CMAP(zzInput) ]; if (zzNext == -1) break zzForAction; zzState = zzNext; zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; return null; } else { switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 1: { return BAD_CHARACTER; } case 91: break; case 2: { return NLS; } case 92: break; case 3: { return WS; } case 93: break; case 4: { return QUOTIENT; } case 94: break; case 5: { return MUL; } case 95: break; case 6: { yybegin(MAYBE_SEMICOLON); return IDENTIFIER; } case 96: break; case 7: { yybegin(MAYBE_SEMICOLON); return INT; } case 97: break; case 8: { return MINUS; } case 98: break; case 9: { return DOT; } case 99: break; case 10: { yybegin(MAYBE_SEMICOLON); return STRING; } case 100: break; case 11: { yybegin(MAYBE_SEMICOLON); return RAW_STRING; } case 101: break; case 12: { return BIT_OR; } case 102: break; case 13: { return LBRACE; } case 103: break; case 14: { yybegin(MAYBE_SEMICOLON); return RBRACE; } case 104: break; case 15: { return LBRACK; } case 105: break; case 16: { yybegin(MAYBE_SEMICOLON); return RBRACK; } case 106: break; case 17: { return LPAREN; } case 107: break; case 18: { yybegin(MAYBE_SEMICOLON); return RPAREN; } case 108: break; case 19: { return COLON; } case 109: break; case 20: { return SEMICOLON; } case 110: break; case 21: { return COMMA; } case 111: break; case 22: { return ASSIGN; } case 112: break; case 23: { return NOT; } case 113: break; case 24: { return PLUS; } case 114: break; case 25: { return BIT_AND; } case 115: break; case 26: { return BIT_XOR; } case 116: break; case 27: { return LESS; } case 117: break; case 28: { return REMAINDER; } case 118: break; case 29: { return GREATER; } case 119: break; case 30: { yybegin(YYINITIAL); yypushback(yytext().length()); } case 120: break; case 31: { yybegin(YYINITIAL); yypushback(yytext().length()); return SEMICOLON_SYNTHETIC; } case 121: break; case 32: { return LINE_COMMENT; } case 122: break; case 33: { return MULTILINE_COMMENT; } case 123: break; case 34: { return QUOTIENT_ASSIGN; } case 124: break; case 35: { return MUL_ASSIGN; } case 125: break; case 36: { yybegin(MAYBE_SEMICOLON); return FLOAT; } case 126: break; case 37: { yybegin(MAYBE_SEMICOLON); return DECIMALI; } case 127: break; case 38: { yybegin(MAYBE_SEMICOLON); return OCT; } case 128: break; case 39: { yybegin(MAYBE_SEMICOLON); return MINUS_MINUS; } case 129: break; case 40: { return MINUS_ASSIGN; } case 130: break; case 41: { yybegin(MAYBE_SEMICOLON); return CHAR; } case 131: break; case 42: { return COND_OR; } case 132: break; case 43: { return BIT_OR_ASSIGN; } case 133: break; case 44: { return VAR_ASSIGN; } case 134: break; case 45: { return EQ; } case 135: break; case 46: { return NOT_EQ; } case 136: break; case 47: { return PLUS_ASSIGN; } case 137: break; case 48: { yybegin(MAYBE_SEMICOLON); return PLUS_PLUS; } case 138: break; case 49: { return BIT_AND_ASSIGN; } case 139: break; case 50: { return COND_AND; } case 140: break; case 51: { return BIT_CLEAR; } case 141: break; case 52: { return BIT_XOR_ASSIGN; } case 142: break; case 53: { return SEND_CHANNEL; } case 143: break; case 54: { return LESS_OR_EQUAL; } case 144: break; case 55: { return SHIFT_LEFT; } case 145: break; case 56: { return REMAINDER_ASSIGN; } case 146: break; case 57: { return GREATER_OR_EQUAL; } case 147: break; case 58: { return SHIFT_RIGHT; } case 148: break; case 59: { return GO; } case 149: break; case 60: { return IF ; } case 150: break; case 61: { yybegin(MAYBE_SEMICOLON); return FLOATI; } case 151: break; case 62: { yybegin(MAYBE_SEMICOLON); return HEX; } case 152: break; case 63: { return TRIPLE_DOT; } case 153: break; case 64: { return VAR; } case 154: break; case 65: { return FOR ; } case 155: break; case 66: { yybegin(MAYBE_SEMICOLON); return BAD_CHARACTER; } case 156: break; case 67: { return BIT_CLEAR_ASSIGN; } case 157: break; case 68: { return SHIFT_LEFT_ASSIGN; } case 158: break; case 69: { return SHIFT_RIGHT_ASSIGN; } case 159: break; case 70: { return MAP; } case 160: break; case 71: { return FUNC; } case 161: break; case 72: { return ELSE; } case 162: break; case 73: { return TYPE_; } case 163: break; case 74: { return GOTO; } case 164: break; case 75: { return CASE; } case 165: break; case 76: { return CHAN; } case 166: break; case 77: { yybegin(MAYBE_SEMICOLON); return BREAK; } case 167: break; case 78: { return RANGE; } case 168: break; case 79: { return CONST; } case 169: break; case 80: { return DEFER; } case 170: break; case 81: { yybegin(MAYBE_SEMICOLON); return RETURN ; } case 171: break; case 82: { return IMPORT ; } case 172: break; case 83: { return SELECT; } case 173: break; case 84: { return STRUCT; } case 174: break; case 85: { return SWITCH; } case 175: break; case 86: { return DEFAULT; } case 176: break; case 87: { return PACKAGE; } case 177: break; case 88: { yybegin(MAYBE_SEMICOLON); return CONTINUE ; } case 178: break; case 89: { return INTERFACE; } case 179: break; case 90: { yybegin(MAYBE_SEMICOLON); return FALLTHROUGH; } case 180: break; default: zzScanError(ZZ_NO_MATCH); } } } } } ================================================ FILE: gen/com/goide/parser/GoParser.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.parser; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiBuilder.Marker; import static com.goide.GoTypes.*; import static com.goide.parser.GoParserUtil.*; import com.intellij.psi.tree.IElementType; import com.intellij.lang.ASTNode; import com.intellij.psi.tree.TokenSet; import com.intellij.lang.PsiParser; import com.intellij.lang.LightPsiParser; @SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"}) public class GoParser implements PsiParser, LightPsiParser { public ASTNode parse(IElementType t, PsiBuilder b) { parseLight(t, b); return b.getTreeBuilt(); } public void parseLight(IElementType t, PsiBuilder b) { boolean r; b = adapt_builder_(t, b, this, EXTENDS_SETS_); Marker m = enter_section_(b, 0, _COLLAPSE_, null); if (t == ANONYMOUS_FIELD_DEFINITION) { r = AnonymousFieldDefinition(b, 0); } else if (t == ARGUMENT_LIST) { r = ArgumentList(b, 0); } else if (t == ARRAY_OR_SLICE_TYPE) { r = ArrayOrSliceType(b, 0); } else if (t == ASSIGNMENT_STATEMENT) { r = AssignmentStatement(b, 0); } else if (t == BLOCK) { r = Block(b, 0); } else if (t == BREAK_STATEMENT) { r = BreakStatement(b, 0); } else if (t == BUILTIN_ARGUMENT_LIST) { r = BuiltinArgumentList(b, 0); } else if (t == CHANNEL_TYPE) { r = ChannelType(b, 0); } else if (t == COMM_CASE) { r = CommCase(b, 0); } else if (t == COMM_CLAUSE) { r = CommClause(b, 0); } else if (t == CONST_DECLARATION) { r = ConstDeclaration(b, 0); } else if (t == CONST_DEFINITION) { r = ConstDefinition(b, 0); } else if (t == CONST_SPEC) { r = ConstSpec(b, 0); } else if (t == CONTINUE_STATEMENT) { r = ContinueStatement(b, 0); } else if (t == DEFER_STATEMENT) { r = DeferStatement(b, 0); } else if (t == ELEMENT) { r = Element(b, 0); } else if (t == ELSE_STATEMENT) { r = ElseStatement(b, 0); } else if (t == EXPR_CASE_CLAUSE) { r = ExprCaseClause(b, 0); } else if (t == EXPR_SWITCH_STATEMENT) { r = ExprSwitchStatement(b, 0); } else if (t == EXPRESSION) { r = Expression(b, 0, -1); } else if (t == FALLTHROUGH_STATEMENT) { r = FallthroughStatement(b, 0); } else if (t == FIELD_DECLARATION) { r = FieldDeclaration(b, 0); } else if (t == FIELD_DEFINITION) { r = FieldDefinition(b, 0); } else if (t == FIELD_NAME) { r = FieldName(b, 0); } else if (t == FOR_CLAUSE) { r = ForClause(b, 0); } else if (t == FOR_STATEMENT) { r = ForStatement(b, 0); } else if (t == FUNCTION_DECLARATION) { r = FunctionDeclaration(b, 0); } else if (t == FUNCTION_TYPE) { r = FunctionType(b, 0); } else if (t == GO_STATEMENT) { r = GoStatement(b, 0); } else if (t == GOTO_STATEMENT) { r = GotoStatement(b, 0); } else if (t == IF_STATEMENT) { r = IfStatement(b, 0); } else if (t == IMPORT_DECLARATION) { r = ImportDeclaration(b, 0); } else if (t == IMPORT_LIST) { r = ImportList(b, 0); } else if (t == IMPORT_SPEC) { r = ImportSpec(b, 0); } else if (t == IMPORT_STRING) { r = ImportString(b, 0); } else if (t == INC_DEC_STATEMENT) { r = IncDecStatement(b, 0); } else if (t == INTERFACE_TYPE) { r = InterfaceType(b, 0); } else if (t == KEY) { r = Key(b, 0); } else if (t == LABEL_DEFINITION) { r = LabelDefinition(b, 0); } else if (t == LABEL_REF) { r = LabelRef(b, 0); } else if (t == LABELED_STATEMENT) { r = LabeledStatement(b, 0); } else if (t == LEFT_HAND_EXPR_LIST) { r = LeftHandExprList(b, 0); } else if (t == LITERAL_TYPE_EXPR) { r = LiteralTypeExpr(b, 0); } else if (t == LITERAL_VALUE) { r = LiteralValue(b, 0); } else if (t == MAP_TYPE) { r = MapType(b, 0); } else if (t == METHOD_DECLARATION) { r = MethodDeclaration(b, 0); } else if (t == METHOD_SPEC) { r = MethodSpec(b, 0); } else if (t == PACKAGE_CLAUSE) { r = PackageClause(b, 0); } else if (t == PAR_TYPE) { r = ParType(b, 0); } else if (t == PARAM_DEFINITION) { r = ParamDefinition(b, 0); } else if (t == PARAMETER_DECLARATION) { r = ParameterDeclaration(b, 0); } else if (t == PARAMETERS) { r = Parameters(b, 0); } else if (t == POINTER_TYPE) { r = PointerType(b, 0); } else if (t == RANGE_CLAUSE) { r = RangeClause(b, 0); } else if (t == RECEIVER) { r = Receiver(b, 0); } else if (t == RECV_STATEMENT) { r = RecvStatement(b, 0); } else if (t == REFERENCE_EXPRESSION) { r = ReferenceExpression(b, 0); } else if (t == RESULT) { r = Result(b, 0); } else if (t == RETURN_STATEMENT) { r = ReturnStatement(b, 0); } else if (t == SELECT_STATEMENT) { r = SelectStatement(b, 0); } else if (t == SEND_STATEMENT) { r = SendStatement(b, 0); } else if (t == SHORT_VAR_DECLARATION) { r = ShortVarDeclaration(b, 0); } else if (t == SIGNATURE) { r = Signature(b, 0); } else if (t == SIMPLE_STATEMENT) { r = SimpleStatement(b, 0); } else if (t == SPEC_TYPE) { r = SpecType(b, 0); } else if (t == STATEMENT) { r = Statement(b, 0); } else if (t == STRING_LITERAL) { r = StringLiteral(b, 0); } else if (t == STRUCT_TYPE) { r = StructType(b, 0); } else if (t == SWITCH_START) { r = SwitchStart(b, 0); } else if (t == SWITCH_STATEMENT) { r = SwitchStatement(b, 0); } else if (t == TAG) { r = Tag(b, 0); } else if (t == TYPE) { r = Type(b, 0); } else if (t == TYPE_CASE_CLAUSE) { r = TypeCaseClause(b, 0); } else if (t == TYPE_DECLARATION) { r = TypeDeclaration(b, 0); } else if (t == TYPE_GUARD) { r = TypeGuard(b, 0); } else if (t == TYPE_LIST) { r = TypeList(b, 0); } else if (t == TYPE_REFERENCE_EXPRESSION) { r = TypeReferenceExpression(b, 0); } else if (t == TYPE_SPEC) { r = TypeSpec(b, 0); } else if (t == TYPE_SWITCH_GUARD) { r = TypeSwitchGuard(b, 0); } else if (t == TYPE_SWITCH_STATEMENT) { r = TypeSwitchStatement(b, 0); } else if (t == VALUE) { r = Value(b, 0); } else if (t == VAR_DECLARATION) { r = VarDeclaration(b, 0); } else if (t == VAR_DEFINITION) { r = VarDefinition(b, 0); } else if (t == VAR_SPEC) { r = VarSpec(b, 0); } else if (t == ASSIGN_OP) { r = assign_op(b, 0); } else { r = parse_root_(t, b, 0); } exit_section_(b, 0, m, t, r, true, TRUE_CONDITION); } protected boolean parse_root_(IElementType t, PsiBuilder b, int l) { return File(b, l + 1); } public static final TokenSet[] EXTENDS_SETS_ = new TokenSet[] { create_token_set_(ARGUMENT_LIST, BUILTIN_ARGUMENT_LIST), create_token_set_(RANGE_CLAUSE, RECV_STATEMENT, SHORT_VAR_DECLARATION, VAR_SPEC), create_token_set_(ARRAY_OR_SLICE_TYPE, CHANNEL_TYPE, FUNCTION_TYPE, INTERFACE_TYPE, MAP_TYPE, PAR_TYPE, POINTER_TYPE, STRUCT_TYPE, TYPE, TYPE_LIST), create_token_set_(ASSIGNMENT_STATEMENT, BREAK_STATEMENT, CONTINUE_STATEMENT, DEFER_STATEMENT, ELSE_STATEMENT, EXPR_SWITCH_STATEMENT, FALLTHROUGH_STATEMENT, FOR_STATEMENT, GOTO_STATEMENT, GO_STATEMENT, IF_STATEMENT, INC_DEC_STATEMENT, LABELED_STATEMENT, RETURN_STATEMENT, SELECT_STATEMENT, SEND_STATEMENT, SIMPLE_STATEMENT, STATEMENT, SWITCH_STATEMENT, TYPE_SWITCH_STATEMENT), create_token_set_(ADD_EXPR, AND_EXPR, BUILTIN_CALL_EXPR, CALL_EXPR, COMPOSITE_LIT, CONDITIONAL_EXPR, CONVERSION_EXPR, EXPRESSION, FUNCTION_LIT, INDEX_OR_SLICE_EXPR, LITERAL, LITERAL_TYPE_EXPR, MUL_EXPR, OR_EXPR, PARENTHESES_EXPR, REFERENCE_EXPRESSION, SELECTOR_EXPR, STRING_LITERAL, TYPE_ASSERTION_EXPR, UNARY_EXPR), }; /* ********************************************************** */ // '+' | '-' | '|' | '^' static boolean AddOp(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "AddOp")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, PLUS); if (!r) r = consumeToken(b, MINUS); if (!r) r = consumeToken(b, BIT_OR); if (!r) r = consumeToken(b, BIT_XOR); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Type public static boolean AnonymousFieldDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "AnonymousFieldDefinition")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, ANONYMOUS_FIELD_DEFINITION, ""); r = Type(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // '(' [ ExpressionArgList '...'? ','? ] ')' public static boolean ArgumentList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArgumentList")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ARGUMENT_LIST, null); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, ArgumentList_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // [ ExpressionArgList '...'? ','? ] private static boolean ArgumentList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArgumentList_1")) return false; ArgumentList_1_0(b, l + 1); return true; } // ExpressionArgList '...'? ','? private static boolean ArgumentList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArgumentList_1_0")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionArgList(b, l + 1); r = r && ArgumentList_1_0_1(b, l + 1); r = r && ArgumentList_1_0_2(b, l + 1); exit_section_(b, m, null, r); return r; } // '...'? private static boolean ArgumentList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArgumentList_1_0_1")) return false; consumeToken(b, TRIPLE_DOT); return true; } // ','? private static boolean ArgumentList_1_0_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArgumentList_1_0_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // '[' ('...'|Expression?) ']' Type public static boolean ArrayOrSliceType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArrayOrSliceType")) return false; if (!nextTokenIs(b, LBRACK)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ARRAY_OR_SLICE_TYPE, null); r = consumeToken(b, LBRACK); p = r; // pin = 1 r = r && report_error_(b, ArrayOrSliceType_1(b, l + 1)); r = p && report_error_(b, consumeToken(b, RBRACK)) && r; r = p && Type(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // '...'|Expression? private static boolean ArrayOrSliceType_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArrayOrSliceType_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, TRIPLE_DOT); if (!r) r = ArrayOrSliceType_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // Expression? private static boolean ArrayOrSliceType_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ArrayOrSliceType_1_1")) return false; Expression(b, l + 1, -1); return true; } /* ********************************************************** */ // assign_op ExpressionList public static boolean AssignmentStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "AssignmentStatement")) return false; boolean r, p; Marker m = enter_section_(b, l, _LEFT_, ASSIGNMENT_STATEMENT, ""); r = assign_op(b, l + 1); p = r; // pin = 1 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // BlockInner public static boolean Block(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Block")) return false; if (!nextTokenIs(b, LBRACE)) return false; boolean r; Marker m = enter_section_(b); r = BlockInner(b, l + 1); exit_section_(b, m, BLOCK, r); return r; } /* ********************************************************** */ // '{' ('}' | (<> | (!() Statements)) '}') static boolean BlockInner(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner")) return false; if (!nextTokenIs(b, LBRACE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LBRACE); p = r; // pin = 1 r = r && BlockInner_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // '}' | (<> | (!() Statements)) '}' private static boolean BlockInner_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, RBRACE); if (!r) r = BlockInner_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // (<> | (!() Statements)) '}' private static boolean BlockInner_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = BlockInner_1_1_0(b, l + 1); p = r; // pin = 1 r = r && consumeToken(b, RBRACE); exit_section_(b, l, m, r, p, null); return r || p; } // <> | (!() Statements) private static boolean BlockInner_1_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner_1_1_0")) return false; boolean r; Marker m = enter_section_(b); r = withOff(b, l + 1, Statements_parser_, "BLOCK?", "PAR"); if (!r) r = BlockInner_1_1_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // !() Statements private static boolean BlockInner_1_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner_1_1_0_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = BlockInner_1_1_0_1_0(b, l + 1); p = r; // pin = 1 r = r && Statements(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // !() private static boolean BlockInner_1_1_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockInner_1_1_0_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !BlockInner_1_1_0_1_0_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // () private static boolean BlockInner_1_1_0_1_0_0(PsiBuilder b, int l) { return true; } /* ********************************************************** */ // <> | BlockInner public static boolean BlockWithConsume(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BlockWithConsume")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, BLOCK, ""); r = consumeBlock(b, l + 1); if (!r) r = BlockInner(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // break LabelRef? public static boolean BreakStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BreakStatement")) return false; if (!nextTokenIs(b, BREAK)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, BREAK_STATEMENT, null); r = consumeToken(b, BREAK); p = r; // pin = 1 r = r && BreakStatement_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // LabelRef? private static boolean BreakStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BreakStatement_1")) return false; LabelRef(b, l + 1); return true; } /* ********************************************************** */ // Type [ ',' BuiltinArgsTail ] | BuiltinArgsTail static boolean BuiltinArgsInner(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsInner")) return false; boolean r; Marker m = enter_section_(b); r = BuiltinArgsInner_0(b, l + 1); if (!r) r = BuiltinArgsTail(b, l + 1); exit_section_(b, m, null, r); return r; } // Type [ ',' BuiltinArgsTail ] private static boolean BuiltinArgsInner_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsInner_0")) return false; boolean r; Marker m = enter_section_(b); r = Type(b, l + 1); r = r && BuiltinArgsInner_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // [ ',' BuiltinArgsTail ] private static boolean BuiltinArgsInner_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsInner_0_1")) return false; BuiltinArgsInner_0_1_0(b, l + 1); return true; } // ',' BuiltinArgsTail private static boolean BuiltinArgsInner_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsInner_0_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && BuiltinArgsTail(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ExpressionList '...'? static boolean BuiltinArgsTail(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsTail")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionList(b, l + 1); r = r && BuiltinArgsTail_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '...'? private static boolean BuiltinArgsTail_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgsTail_1")) return false; consumeToken(b, TRIPLE_DOT); return true; } /* ********************************************************** */ // '(' [ BuiltinArgsInner ','? ] ')' public static boolean BuiltinArgumentList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgumentList")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, BUILTIN_ARGUMENT_LIST, null); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, BuiltinArgumentList_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // [ BuiltinArgsInner ','? ] private static boolean BuiltinArgumentList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgumentList_1")) return false; BuiltinArgumentList_1_0(b, l + 1); return true; } // BuiltinArgsInner ','? private static boolean BuiltinArgumentList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgumentList_1_0")) return false; boolean r; Marker m = enter_section_(b); r = BuiltinArgsInner(b, l + 1); r = r && BuiltinArgumentList_1_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ','? private static boolean BuiltinArgumentList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinArgumentList_1_0_1")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // chan '<-'? | '<-' chan static boolean ChanTypePrefix(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ChanTypePrefix")) return false; if (!nextTokenIs(b, "", SEND_CHANNEL, CHAN)) return false; boolean r; Marker m = enter_section_(b); r = ChanTypePrefix_0(b, l + 1); if (!r) r = ChanTypePrefix_1(b, l + 1); exit_section_(b, m, null, r); return r; } // chan '<-'? private static boolean ChanTypePrefix_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ChanTypePrefix_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, CHAN); p = r; // pin = 1 r = r && ChanTypePrefix_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // '<-'? private static boolean ChanTypePrefix_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ChanTypePrefix_0_1")) return false; consumeToken(b, SEND_CHANNEL); return true; } // '<-' chan private static boolean ChanTypePrefix_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ChanTypePrefix_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, SEND_CHANNEL); p = r; // pin = 1 r = r && consumeToken(b, CHAN); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // ChanTypePrefix Type public static boolean ChannelType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ChannelType")) return false; if (!nextTokenIs(b, "", SEND_CHANNEL, CHAN)) return false; boolean r, p; Marker m = enter_section_(b, l, _COLLAPSE_, CHANNEL_TYPE, ""); r = ChanTypePrefix(b, l + 1); p = r; // pin = 1 r = r && Type(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // case ( Expression SendStatement | RecvStatement ) | default public static boolean CommCase(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommCase")) return false; if (!nextTokenIs(b, "", CASE, DEFAULT)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, COMM_CASE, ""); r = CommCase_0(b, l + 1); if (!r) r = consumeToken(b, DEFAULT); exit_section_(b, l, m, r, false, null); return r; } // case ( Expression SendStatement | RecvStatement ) private static boolean CommCase_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommCase_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, CASE); p = r; // pin = case r = r && CommCase_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Expression SendStatement | RecvStatement private static boolean CommCase_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommCase_0_1")) return false; boolean r; Marker m = enter_section_(b); r = CommCase_0_1_0(b, l + 1); if (!r) r = RecvStatement(b, l + 1); exit_section_(b, m, null, r); return r; } // Expression SendStatement private static boolean CommCase_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommCase_0_1_0")) return false; boolean r; Marker m = enter_section_(b); r = Expression(b, l + 1, -1); r = r && SendStatement(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // CommCase ':' Statements? public static boolean CommClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommClause")) return false; if (!nextTokenIs(b, "", CASE, DEFAULT)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, COMM_CLAUSE, ""); r = CommCase(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, COLON)); r = p && CommClause_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // Statements? private static boolean CommClause_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CommClause_2")) return false; Statements(b, l + 1); return true; } /* ********************************************************** */ // <> SimpleStatementOpt Expression? <> static boolean Condition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Condition")) return false; boolean r; Marker m = enter_section_(b); r = enterMode(b, l + 1, "BLOCK?"); r = r && SimpleStatementOpt(b, l + 1); r = r && Condition_2(b, l + 1); r = r && exitModeSafe(b, l + 1, "BLOCK?"); exit_section_(b, m, null, r); return r; } // Expression? private static boolean Condition_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Condition_2")) return false; Expression(b, l + 1, -1); return true; } /* ********************************************************** */ // const ( ConstSpec | '(' ConstSpecs? ')' ) public static boolean ConstDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDeclaration")) return false; if (!nextTokenIs(b, CONST)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, CONST_DECLARATION, null); r = consumeToken(b, CONST); p = r; // pin = 1 r = r && ConstDeclaration_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ConstSpec | '(' ConstSpecs? ')' private static boolean ConstDeclaration_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDeclaration_1")) return false; boolean r; Marker m = enter_section_(b); r = ConstSpec(b, l + 1); if (!r) r = ConstDeclaration_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '(' ConstSpecs? ')' private static boolean ConstDeclaration_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDeclaration_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, ConstDeclaration_1_1_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ConstSpecs? private static boolean ConstDeclaration_1_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDeclaration_1_1_1")) return false; ConstSpecs(b, l + 1); return true; } /* ********************************************************** */ // identifier public static boolean ConstDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDefinition")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, CONST_DEFINITION, r); return r; } /* ********************************************************** */ // ConstDefinition ( ',' ConstDefinition )* static boolean ConstDefinitionList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDefinitionList")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ConstDefinition(b, l + 1); p = r; // pin = 1 r = r && ConstDefinitionList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ( ',' ConstDefinition )* private static boolean ConstDefinitionList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDefinitionList_1")) return false; int c = current_position_(b); while (true) { if (!ConstDefinitionList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ConstDefinitionList_1", c)) break; c = current_position_(b); } return true; } // ',' ConstDefinition private static boolean ConstDefinitionList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstDefinitionList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && ConstDefinition(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // ConstDefinitionList [ ('=' ExpressionList | Type '=' ExpressionList) ] public static boolean ConstSpec(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpec")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, CONST_SPEC, null); r = ConstDefinitionList(b, l + 1); p = r; // pin = 1 r = r && ConstSpec_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // [ ('=' ExpressionList | Type '=' ExpressionList) ] private static boolean ConstSpec_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpec_1")) return false; ConstSpec_1_0(b, l + 1); return true; } // '=' ExpressionList | Type '=' ExpressionList private static boolean ConstSpec_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpec_1_0")) return false; boolean r; Marker m = enter_section_(b); r = ConstSpec_1_0_0(b, l + 1); if (!r) r = ConstSpec_1_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '=' ExpressionList private static boolean ConstSpec_1_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpec_1_0_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, ASSIGN); p = r; // pin = 1 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Type '=' ExpressionList private static boolean ConstSpec_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpec_1_0_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = Type(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, ASSIGN)); r = p && ExpressionList(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // ConstSpec (semi ConstSpec)* semi? static boolean ConstSpecs(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpecs")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ConstSpec(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, ConstSpecs_1(b, l + 1)); r = p && ConstSpecs_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi ConstSpec)* private static boolean ConstSpecs_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpecs_1")) return false; int c = current_position_(b); while (true) { if (!ConstSpecs_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ConstSpecs_1", c)) break; c = current_position_(b); } return true; } // semi ConstSpec private static boolean ConstSpecs_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpecs_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && ConstSpec(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean ConstSpecs_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConstSpecs_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // continue LabelRef? public static boolean ContinueStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ContinueStatement")) return false; if (!nextTokenIs(b, CONTINUE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, CONTINUE_STATEMENT, null); r = consumeToken(b, CONTINUE); p = r; // pin = 1 r = r && ContinueStatement_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // LabelRef? private static boolean ContinueStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ContinueStatement_1")) return false; LabelRef(b, l + 1); return true; } /* ********************************************************** */ // ConversionStart | '(' ConversionStart static boolean ConversionPredicate(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionPredicate")) return false; boolean r; Marker m = enter_section_(b); r = ConversionStart(b, l + 1); if (!r) r = ConversionPredicate_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '(' ConversionStart private static boolean ConversionPredicate_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionPredicate_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LPAREN); r = r && ConversionStart(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // '*' | '<-' | '[' | chan | func | interface | map | struct static boolean ConversionStart(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionStart")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, MUL); if (!r) r = consumeToken(b, SEND_CHANNEL); if (!r) r = consumeToken(b, LBRACK); if (!r) r = consumeToken(b, CHAN); if (!r) r = consumeToken(b, FUNC); if (!r) r = consumeToken(b, INTERFACE); if (!r) r = consumeToken(b, MAP); if (!r) r = consumeToken(b, STRUCT); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // '(' Expression ','? ')' static boolean ConversionTail(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionTail")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, Expression(b, l + 1, -1)); r = p && report_error_(b, ConversionTail_2(b, l + 1)) && r; r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ','? private static boolean ConversionTail_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionTail_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // defer Expression public static boolean DeferStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "DeferStatement")) return false; if (!nextTokenIs(b, DEFER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, DEFER_STATEMENT, null); r = consumeToken(b, DEFER); p = r; // pin = 1 r = r && Expression(b, l + 1, -1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // <> | (!() Element) static boolean E(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "E")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_); r = withOn(b, l + 1, "PAR", Element_parser_); if (!r) r = E_1(b, l + 1); exit_section_(b, l, m, r, false, E_recover_parser_); return r; } // !() Element private static boolean E_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "E_1")) return false; boolean r; Marker m = enter_section_(b); r = E_1_0(b, l + 1); r = r && Element(b, l + 1); exit_section_(b, m, null, r); return r; } // !() private static boolean E_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "E_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !E_1_0_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // () private static boolean E_1_0_0(PsiBuilder b, int l) { return true; } /* ********************************************************** */ // !('}'|',') static boolean E_recover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "E_recover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !E_recover_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '}'|',' private static boolean E_recover_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "E_recover_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, RBRACE); if (!r) r = consumeToken(b, COMMA); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // First [':' Value] public static boolean Element(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Element")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ELEMENT, ""); r = First(b, l + 1); p = r; // pin = 1 r = r && Element_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // [':' Value] private static boolean Element_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Element_1")) return false; Element_1_0(b, l + 1); return true; } // ':' Value private static boolean Element_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Element_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COLON); p = r; // pin = 1 r = r && Value(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // E ( ',' E? )* static boolean ElementList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElementList")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = E(b, l + 1); p = r; // pin = 1 r = r && ElementList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ( ',' E? )* private static boolean ElementList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElementList_1")) return false; int c = current_position_(b); while (true) { if (!ElementList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ElementList_1", c)) break; c = current_position_(b); } return true; } // ',' E? private static boolean ElementList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElementList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && ElementList_1_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // E? private static boolean ElementList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElementList_1_0_1")) return false; E(b, l + 1); return true; } /* ********************************************************** */ // else (IfStatement | Block) public static boolean ElseStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElseStatement")) return false; if (!nextTokenIs(b, ELSE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, ELSE_STATEMENT, null); r = consumeToken(b, ELSE); p = r; // pin = 1 r = r && ElseStatement_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // IfStatement | Block private static boolean ElseStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ElseStatement_1")) return false; boolean r; Marker m = enter_section_(b); r = IfStatement(b, l + 1); if (!r) r = Block(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // !'}' ExprSwitchCase ':' Statements? public static boolean ExprCaseClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprCaseClause")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, EXPR_CASE_CLAUSE, ""); r = ExprCaseClause_0(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, ExprSwitchCase(b, l + 1)); r = p && report_error_(b, consumeToken(b, COLON)) && r; r = p && ExprCaseClause_3(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // !'}' private static boolean ExprCaseClause_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprCaseClause_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !consumeToken(b, RBRACE); exit_section_(b, l, m, r, false, null); return r; } // Statements? private static boolean ExprCaseClause_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprCaseClause_3")) return false; Statements(b, l + 1); return true; } /* ********************************************************** */ // case ExpressionList | default static boolean ExprSwitchCase(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprSwitchCase")) return false; if (!nextTokenIs(b, "", CASE, DEFAULT)) return false; boolean r; Marker m = enter_section_(b); r = ExprSwitchCase_0(b, l + 1); if (!r) r = consumeToken(b, DEFAULT); exit_section_(b, m, null, r); return r; } // case ExpressionList private static boolean ExprSwitchCase_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprSwitchCase_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, CASE); p = r; // pin = 1 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // Condition '{' ExprCaseClause* '}' public static boolean ExprSwitchStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprSwitchStatement")) return false; boolean r, p; Marker m = enter_section_(b, l, _LEFT_, EXPR_SWITCH_STATEMENT, ""); r = Condition(b, l + 1); r = r && consumeToken(b, LBRACE); p = r; // pin = 2 r = r && report_error_(b, ExprSwitchStatement_2(b, l + 1)); r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ExprCaseClause* private static boolean ExprSwitchStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExprSwitchStatement_2")) return false; int c = current_position_(b); while (true) { if (!ExprCaseClause(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ExprSwitchStatement_2", c)) break; c = current_position_(b); } return true; } /* ********************************************************** */ // ExpressionOrTypeWithRecover2 (',' (ExpressionOrTypeWithRecover2 | &')'))* static boolean ExpressionArgList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionArgList")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ExpressionOrTypeWithRecover2(b, l + 1); p = r; // pin = 1 r = r && ExpressionArgList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // (',' (ExpressionOrTypeWithRecover2 | &')'))* private static boolean ExpressionArgList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionArgList_1")) return false; int c = current_position_(b); while (true) { if (!ExpressionArgList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ExpressionArgList_1", c)) break; c = current_position_(b); } return true; } // ',' (ExpressionOrTypeWithRecover2 | &')') private static boolean ExpressionArgList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionArgList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && ExpressionArgList_1_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ExpressionOrTypeWithRecover2 | &')' private static boolean ExpressionArgList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionArgList_1_0_1")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionOrTypeWithRecover2(b, l + 1); if (!r) r = ExpressionArgList_1_0_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &')' private static boolean ExpressionArgList_1_0_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionArgList_1_0_1_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, RPAREN); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // ExpressionWithRecover (',' (ExpressionWithRecover | &')'))* static boolean ExpressionList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionList")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ExpressionWithRecover(b, l + 1); p = r; // pin = 1 r = r && ExpressionList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // (',' (ExpressionWithRecover | &')'))* private static boolean ExpressionList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionList_1")) return false; int c = current_position_(b); while (true) { if (!ExpressionList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ExpressionList_1", c)) break; c = current_position_(b); } return true; } // ',' (ExpressionWithRecover | &')') private static boolean ExpressionList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && ExpressionList_1_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ExpressionWithRecover | &')' private static boolean ExpressionList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionList_1_0_1")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionWithRecover(b, l + 1); if (!r) r = ExpressionList_1_0_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &')' private static boolean ExpressionList_1_0_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionList_1_0_1_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, RPAREN); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // !('!' | '!=' | '%' | '%=' | '&&' | '&' | '&=' | '&^' | '&^=' | '(' | ')' | '*' | '*=' | '+' | '++' | '+=' | ',' | '-' | '--' | '-=' | '...' | '/' | '/=' | ':' | ';' | '<' | '<-' | '<<' | '<<=' | '<=' | '' | '=' | '==' | '>' | '>=' | '>>' | '>>=' | '[' | ']' | '^' | '^=' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | chan | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var) static boolean ExpressionListRecover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionListRecover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !ExpressionListRecover_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '!' | '!=' | '%' | '%=' | '&&' | '&' | '&=' | '&^' | '&^=' | '(' | ')' | '*' | '*=' | '+' | '++' | '+=' | ',' | '-' | '--' | '-=' | '...' | '/' | '/=' | ':' | ';' | '<' | '<-' | '<<' | '<<=' | '<=' | '' | '=' | '==' | '>' | '>=' | '>>' | '>>=' | '[' | ']' | '^' | '^=' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | chan | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var private static boolean ExpressionListRecover_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionListRecover_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, NOT); if (!r) r = consumeToken(b, NOT_EQ); if (!r) r = consumeToken(b, REMAINDER); if (!r) r = consumeToken(b, REMAINDER_ASSIGN); if (!r) r = consumeToken(b, COND_AND); if (!r) r = consumeToken(b, BIT_AND); if (!r) r = consumeToken(b, BIT_AND_ASSIGN); if (!r) r = consumeToken(b, BIT_CLEAR); if (!r) r = consumeToken(b, BIT_CLEAR_ASSIGN); if (!r) r = consumeToken(b, LPAREN); if (!r) r = consumeToken(b, RPAREN); if (!r) r = consumeToken(b, MUL); if (!r) r = consumeToken(b, MUL_ASSIGN); if (!r) r = consumeToken(b, PLUS); if (!r) r = consumeToken(b, PLUS_PLUS); if (!r) r = consumeToken(b, PLUS_ASSIGN); if (!r) r = consumeToken(b, COMMA); if (!r) r = consumeToken(b, MINUS); if (!r) r = consumeToken(b, MINUS_MINUS); if (!r) r = consumeToken(b, MINUS_ASSIGN); if (!r) r = consumeToken(b, TRIPLE_DOT); if (!r) r = consumeToken(b, QUOTIENT); if (!r) r = consumeToken(b, QUOTIENT_ASSIGN); if (!r) r = consumeToken(b, COLON); if (!r) r = consumeToken(b, SEMICOLON); if (!r) r = consumeToken(b, LESS); if (!r) r = consumeToken(b, SEND_CHANNEL); if (!r) r = consumeToken(b, SHIFT_LEFT); if (!r) r = consumeToken(b, SHIFT_LEFT_ASSIGN); if (!r) r = consumeToken(b, LESS_OR_EQUAL); if (!r) r = consumeToken(b, SEMICOLON_SYNTHETIC); if (!r) r = consumeToken(b, ASSIGN); if (!r) r = consumeToken(b, EQ); if (!r) r = consumeToken(b, GREATER); if (!r) r = consumeToken(b, GREATER_OR_EQUAL); if (!r) r = consumeToken(b, SHIFT_RIGHT); if (!r) r = consumeToken(b, SHIFT_RIGHT_ASSIGN); if (!r) r = consumeToken(b, LBRACK); if (!r) r = consumeToken(b, RBRACK); if (!r) r = consumeToken(b, BIT_XOR); if (!r) r = consumeToken(b, BIT_XOR_ASSIGN); if (!r) r = consumeToken(b, TYPE_); if (!r) r = consumeToken(b, LBRACE); if (!r) r = consumeToken(b, BIT_OR); if (!r) r = consumeToken(b, BIT_OR_ASSIGN); if (!r) r = consumeToken(b, COND_OR); if (!r) r = consumeToken(b, RBRACE); if (!r) r = consumeToken(b, BREAK); if (!r) r = consumeToken(b, CASE); if (!r) r = consumeToken(b, CHAN); if (!r) r = consumeToken(b, CHAR); if (!r) r = consumeToken(b, CONST); if (!r) r = consumeToken(b, CONTINUE); if (!r) r = consumeToken(b, DECIMALI); if (!r) r = consumeToken(b, DEFAULT); if (!r) r = consumeToken(b, DEFER); if (!r) r = consumeToken(b, ELSE); if (!r) r = consumeToken(b, FALLTHROUGH); if (!r) r = consumeToken(b, FLOAT); if (!r) r = consumeToken(b, FLOATI); if (!r) r = consumeToken(b, FOR); if (!r) r = consumeToken(b, FUNC); if (!r) r = consumeToken(b, GO); if (!r) r = consumeToken(b, GOTO); if (!r) r = consumeToken(b, HEX); if (!r) r = consumeToken(b, IDENTIFIER); if (!r) r = consumeToken(b, IF); if (!r) r = consumeToken(b, INT); if (!r) r = consumeToken(b, INTERFACE); if (!r) r = consumeToken(b, MAP); if (!r) r = consumeToken(b, OCT); if (!r) r = consumeToken(b, RETURN); if (!r) r = consumeToken(b, SELECT); if (!r) r = consumeToken(b, STRING); if (!r) r = consumeToken(b, RAW_STRING); if (!r) r = consumeToken(b, STRUCT); if (!r) r = consumeToken(b, SWITCH); if (!r) r = consumeToken(b, VAR); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Expression | LiteralTypeExpr static boolean ExpressionOrLiteralTypeExpr(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionOrLiteralTypeExpr")) return false; boolean r; Marker m = enter_section_(b); r = Expression(b, l + 1, -1); if (!r) r = LiteralTypeExpr(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ExpressionOrLiteralTypeExpr static boolean ExpressionOrTypeWithRecover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionOrTypeWithRecover")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_); r = ExpressionOrLiteralTypeExpr(b, l + 1); exit_section_(b, l, m, r, false, ExpressionListRecover_parser_); return r; } /* ********************************************************** */ // <> | (!() ExpressionOrLiteralTypeExpr) static boolean ExpressionOrTypeWithRecover2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionOrTypeWithRecover2")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_); r = withOn(b, l + 1, "PAR", ExpressionOrTypeWithRecover_parser_); if (!r) r = ExpressionOrTypeWithRecover2_1(b, l + 1); exit_section_(b, l, m, r, false, ExpressionListRecover_parser_); return r; } // !() ExpressionOrLiteralTypeExpr private static boolean ExpressionOrTypeWithRecover2_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionOrTypeWithRecover2_1")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionOrTypeWithRecover2_1_0(b, l + 1); r = r && ExpressionOrLiteralTypeExpr(b, l + 1); exit_section_(b, m, null, r); return r; } // !() private static boolean ExpressionOrTypeWithRecover2_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionOrTypeWithRecover2_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !ExpressionOrTypeWithRecover2_1_0_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // () private static boolean ExpressionOrTypeWithRecover2_1_0_0(PsiBuilder b, int l) { return true; } /* ********************************************************** */ // Expression static boolean ExpressionWithRecover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionWithRecover")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_); r = Expression(b, l + 1, -1); exit_section_(b, l, m, r, false, ExpressionListRecover_parser_); return r; } /* ********************************************************** */ // ExpressionList '=' | VarDefinitionList ':=' static boolean ExpressionsOrVariables(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionsOrVariables")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionsOrVariables_0(b, l + 1); if (!r) r = ExpressionsOrVariables_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ExpressionList '=' private static boolean ExpressionsOrVariables_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionsOrVariables_0")) return false; boolean r; Marker m = enter_section_(b); r = ExpressionList(b, l + 1); r = r && consumeToken(b, ASSIGN); exit_section_(b, m, null, r); return r; } // VarDefinitionList ':=' private static boolean ExpressionsOrVariables_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ExpressionsOrVariables_1")) return false; boolean r; Marker m = enter_section_(b); r = VarDefinitionList(b, l + 1); r = r && consumeToken(b, VAR_ASSIGN); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // fallthrough public static boolean FallthroughStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FallthroughStatement")) return false; if (!nextTokenIs(b, FALLTHROUGH)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, FALLTHROUGH); exit_section_(b, m, FALLTHROUGH_STATEMENT, r); return r; } /* ********************************************************** */ // (FieldDefinitionList Type | AnonymousFieldDefinition) Tag? public static boolean FieldDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDeclaration")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FIELD_DECLARATION, ""); r = FieldDeclaration_0(b, l + 1); r = r && FieldDeclaration_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // FieldDefinitionList Type | AnonymousFieldDefinition private static boolean FieldDeclaration_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDeclaration_0")) return false; boolean r; Marker m = enter_section_(b); r = FieldDeclaration_0_0(b, l + 1); if (!r) r = AnonymousFieldDefinition(b, l + 1); exit_section_(b, m, null, r); return r; } // FieldDefinitionList Type private static boolean FieldDeclaration_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDeclaration_0_0")) return false; boolean r; Marker m = enter_section_(b); r = FieldDefinitionList(b, l + 1); r = r && Type(b, l + 1); exit_section_(b, m, null, r); return r; } // Tag? private static boolean FieldDeclaration_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDeclaration_1")) return false; Tag(b, l + 1); return true; } /* ********************************************************** */ // identifier public static boolean FieldDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDefinition")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, FIELD_DEFINITION, r); return r; } /* ********************************************************** */ // FieldDefinition (',' FieldDefinition)* static boolean FieldDefinitionList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDefinitionList")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = FieldDefinition(b, l + 1); p = r; // pin = 1 r = r && FieldDefinitionList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // (',' FieldDefinition)* private static boolean FieldDefinitionList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDefinitionList_1")) return false; int c = current_position_(b); while (true) { if (!FieldDefinitionList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "FieldDefinitionList_1", c)) break; c = current_position_(b); } return true; } // ',' FieldDefinition private static boolean FieldDefinitionList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldDefinitionList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && FieldDefinition(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // identifier public static boolean FieldName(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FieldName")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, FIELD_NAME, r); return r; } /* ********************************************************** */ // FieldDeclaration (semi FieldDeclaration)* semi? static boolean Fields(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Fields")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = FieldDeclaration(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, Fields_1(b, l + 1)); r = p && Fields_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi FieldDeclaration)* private static boolean Fields_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Fields_1")) return false; int c = current_position_(b); while (true) { if (!Fields_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "Fields_1", c)) break; c = current_position_(b); } return true; } // semi FieldDeclaration private static boolean Fields_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Fields_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && FieldDeclaration(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean Fields_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Fields_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // PackageClause semi ImportList TopLevelDeclaration* static boolean File(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "File")) return false; if (!nextTokenIs(b, PACKAGE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = PackageClause(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, semi(b, l + 1)); r = p && report_error_(b, ImportList(b, l + 1)) && r; r = p && File_3(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // TopLevelDeclaration* private static boolean File_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "File_3")) return false; int c = current_position_(b); while (true) { if (!TopLevelDeclaration(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "File_3", c)) break; c = current_position_(b); } return true; } /* ********************************************************** */ // Key | <> static boolean First(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "First")) return false; boolean r; Marker m = enter_section_(b); r = Key(b, l + 1); if (!r) r = keyOrValueExpression(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // SimpleStatement? ';' Expression? ';' SimpleStatement? public static boolean ForClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForClause")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FOR_CLAUSE, ""); r = ForClause_0(b, l + 1); r = r && consumeToken(b, SEMICOLON); r = r && ForClause_2(b, l + 1); r = r && consumeToken(b, SEMICOLON); r = r && ForClause_4(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // SimpleStatement? private static boolean ForClause_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForClause_0")) return false; SimpleStatement(b, l + 1); return true; } // Expression? private static boolean ForClause_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForClause_2")) return false; Expression(b, l + 1, -1); return true; } // SimpleStatement? private static boolean ForClause_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForClause_4")) return false; SimpleStatement(b, l + 1); return true; } /* ********************************************************** */ // ForClause | RangeClause static boolean ForOrRangeClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForOrRangeClause")) return false; boolean r; Marker m = enter_section_(b); r = ForClause(b, l + 1); if (!r) r = RangeClause(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // for <> (ForOrRangeClause Block | Block | Expression Block) <> public static boolean ForStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForStatement")) return false; if (!nextTokenIs(b, FOR)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, FOR_STATEMENT, null); r = consumeToken(b, FOR); p = r; // pin = for|ForOrRangeClause r = r && report_error_(b, enterMode(b, l + 1, "BLOCK?")); r = p && report_error_(b, ForStatement_2(b, l + 1)) && r; r = p && exitModeSafe(b, l + 1, "BLOCK?") && r; exit_section_(b, l, m, r, p, null); return r || p; } // ForOrRangeClause Block | Block | Expression Block private static boolean ForStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForStatement_2")) return false; boolean r; Marker m = enter_section_(b); r = ForStatement_2_0(b, l + 1); if (!r) r = Block(b, l + 1); if (!r) r = ForStatement_2_2(b, l + 1); exit_section_(b, m, null, r); return r; } // ForOrRangeClause Block private static boolean ForStatement_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForStatement_2_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ForOrRangeClause(b, l + 1); p = r; // pin = for|ForOrRangeClause r = r && Block(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Expression Block private static boolean ForStatement_2_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ForStatement_2_2")) return false; boolean r; Marker m = enter_section_(b); r = Expression(b, l + 1, -1); r = r && Block(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // func identifier Signature BlockWithConsume? public static boolean FunctionDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionDeclaration")) return false; if (!nextTokenIs(b, FUNC)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, FUNCTION_DECLARATION, null); r = consumeTokens(b, 2, FUNC, IDENTIFIER); p = r; // pin = 2 r = r && report_error_(b, Signature(b, l + 1)); r = p && FunctionDeclaration_3(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // BlockWithConsume? private static boolean FunctionDeclaration_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionDeclaration_3")) return false; BlockWithConsume(b, l + 1); return true; } /* ********************************************************** */ // func Signature public static boolean FunctionType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionType")) return false; if (!nextTokenIs(b, FUNC)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, FUNCTION_TYPE, null); r = consumeToken(b, FUNC); p = r; // pin = 1 r = r && Signature(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // go Expression public static boolean GoStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "GoStatement")) return false; if (!nextTokenIs(b, GO)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, GO_STATEMENT, null); r = consumeToken(b, GO); p = r; // pin = 1 r = r && Expression(b, l + 1, -1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // goto LabelRef public static boolean GotoStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "GotoStatement")) return false; if (!nextTokenIs(b, GOTO)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, GOTO_STATEMENT, null); r = consumeToken(b, GOTO); p = r; // pin = 1 r = r && LabelRef(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // if Condition Block ElseStatement? public static boolean IfStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IfStatement")) return false; if (!nextTokenIs(b, IF)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, IF_STATEMENT, null); r = consumeToken(b, IF); p = r; // pin = 1 r = r && report_error_(b, Condition(b, l + 1)); r = p && report_error_(b, Block(b, l + 1)) && r; r = p && IfStatement_3(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ElseStatement? private static boolean IfStatement_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IfStatement_3")) return false; ElseStatement(b, l + 1); return true; } /* ********************************************************** */ // import ( ImportSpec | '(' ImportSpecs? ')' ) public static boolean ImportDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportDeclaration")) return false; if (!nextTokenIs(b, IMPORT)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, IMPORT_DECLARATION, null); r = consumeToken(b, IMPORT); p = r; // pin = 1 r = r && ImportDeclaration_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ImportSpec | '(' ImportSpecs? ')' private static boolean ImportDeclaration_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportDeclaration_1")) return false; boolean r; Marker m = enter_section_(b); r = ImportSpec(b, l + 1); if (!r) r = ImportDeclaration_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '(' ImportSpecs? ')' private static boolean ImportDeclaration_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportDeclaration_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, ImportDeclaration_1_1_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ImportSpecs? private static boolean ImportDeclaration_1_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportDeclaration_1_1_1")) return false; ImportSpecs(b, l + 1); return true; } /* ********************************************************** */ // (ImportDeclaration semi)+|<> public static boolean ImportList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportList")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, IMPORT_LIST, ""); r = ImportList_0(b, l + 1); if (!r) r = emptyImportList(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // (ImportDeclaration semi)+ private static boolean ImportList_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportList_0")) return false; boolean r; Marker m = enter_section_(b); r = ImportList_0_0(b, l + 1); int c = current_position_(b); while (r) { if (!ImportList_0_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ImportList_0", c)) break; c = current_position_(b); } exit_section_(b, m, null, r); return r; } // ImportDeclaration semi private static boolean ImportList_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportList_0_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ImportDeclaration(b, l + 1); p = r; // pin = 1 r = r && semi(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // [ '.' | identifier ] ImportString public static boolean ImportSpec(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpec")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, IMPORT_SPEC, ""); r = ImportSpec_0(b, l + 1); r = r && ImportString(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // [ '.' | identifier ] private static boolean ImportSpec_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpec_0")) return false; ImportSpec_0_0(b, l + 1); return true; } // '.' | identifier private static boolean ImportSpec_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpec_0_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, DOT); if (!r) r = consumeToken(b, IDENTIFIER); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ImportSpec (semi ImportSpec)* semi? static boolean ImportSpecs(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpecs")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ImportSpec(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, ImportSpecs_1(b, l + 1)); r = p && ImportSpecs_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi ImportSpec)* private static boolean ImportSpecs_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpecs_1")) return false; int c = current_position_(b); while (true) { if (!ImportSpecs_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ImportSpecs_1", c)) break; c = current_position_(b); } return true; } // semi ImportSpec private static boolean ImportSpecs_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpecs_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && ImportSpec(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean ImportSpecs_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportSpecs_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // StringLiteral public static boolean ImportString(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ImportString")) return false; if (!nextTokenIs(b, "", RAW_STRING, STRING)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, IMPORT_STRING, ""); r = StringLiteral(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // Expression ('++' | '--') public static boolean IncDecStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IncDecStatement")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, INC_DEC_STATEMENT, ""); r = Expression(b, l + 1, -1); r = r && IncDecStatement_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '++' | '--' private static boolean IncDecStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IncDecStatement_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, PLUS_PLUS); if (!r) r = consumeToken(b, MINUS_MINUS); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Expression SliceExprBodyInner? static boolean IndexExprBody(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IndexExprBody")) return false; boolean r; Marker m = enter_section_(b); r = Expression(b, l + 1, -1); r = r && IndexExprBody_1(b, l + 1); exit_section_(b, m, null, r); return r; } // SliceExprBodyInner? private static boolean IndexExprBody_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IndexExprBody_1")) return false; SliceExprBodyInner(b, l + 1); return true; } /* ********************************************************** */ // interface '{' MethodSpecs? '}' public static boolean InterfaceType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "InterfaceType")) return false; if (!nextTokenIs(b, INTERFACE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, INTERFACE_TYPE, null); r = consumeToken(b, INTERFACE); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, LBRACE)); r = p && report_error_(b, InterfaceType_2(b, l + 1)) && r; r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // MethodSpecs? private static boolean InterfaceType_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "InterfaceType_2")) return false; MethodSpecs(b, l + 1); return true; } /* ********************************************************** */ // (FieldName &':') | !() Expression public static boolean Key(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Key")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = Key_0(b, l + 1); if (!r) r = Key_1(b, l + 1); exit_section_(b, m, KEY, r); return r; } // FieldName &':' private static boolean Key_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Key_0")) return false; boolean r; Marker m = enter_section_(b); r = FieldName(b, l + 1); r = r && Key_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &':' private static boolean Key_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Key_0_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, COLON); exit_section_(b, l, m, r, false, null); return r; } // !() Expression private static boolean Key_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Key_1")) return false; boolean r; Marker m = enter_section_(b); r = Key_1_0(b, l + 1); r = r && Expression(b, l + 1, -1); exit_section_(b, m, null, r); return r; } // !() private static boolean Key_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Key_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !Key_1_0_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // () private static boolean Key_1_0_0(PsiBuilder b, int l) { return true; } /* ********************************************************** */ // identifier public static boolean LabelDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LabelDefinition")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, LABEL_DEFINITION, r); return r; } /* ********************************************************** */ // identifier public static boolean LabelRef(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LabelRef")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, LABEL_REF, r); return r; } /* ********************************************************** */ // LabelDefinition ':' Statement? public static boolean LabeledStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LabeledStatement")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, LABELED_STATEMENT, null); r = LabelDefinition(b, l + 1); r = r && consumeToken(b, COLON); p = r; // pin = 2 r = r && LabeledStatement_2(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Statement? private static boolean LabeledStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LabeledStatement_2")) return false; Statement(b, l + 1); return true; } /* ********************************************************** */ // ExpressionList public static boolean LeftHandExprList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LeftHandExprList")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, LEFT_HAND_EXPR_LIST, ""); r = ExpressionList(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // LiteralTypeExprInner | TypeName public static boolean LiteralTypeExpr(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LiteralTypeExpr")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, LITERAL_TYPE_EXPR, ""); r = LiteralTypeExprInner(b, l + 1); if (!r) r = TypeName(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // StructType | ArrayOrSliceType | MapType static boolean LiteralTypeExprInner(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LiteralTypeExprInner")) return false; boolean r; Marker m = enter_section_(b); r = StructType(b, l + 1); if (!r) r = ArrayOrSliceType(b, l + 1); if (!r) r = MapType(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // (<> | <> | <>) '{' ElementList? '}' public static boolean LiteralValue(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LiteralValue")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, LITERAL_VALUE, ""); r = LiteralValue_0(b, l + 1); r = r && consumeToken(b, LBRACE); p = r; // pin = 2 r = r && report_error_(b, LiteralValue_2(b, l + 1)); r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // <> | <> | <> private static boolean LiteralValue_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LiteralValue_0")) return false; boolean r; Marker m = enter_section_(b); r = isModeOff(b, l + 1, "BLOCK?"); if (!r) r = isModeOn(b, l + 1, "PAR"); if (!r) r = prevIsType(b, l + 1); exit_section_(b, m, null, r); return r; } // ElementList? private static boolean LiteralValue_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "LiteralValue_2")) return false; ElementList(b, l + 1); return true; } /* ********************************************************** */ // map '[' Type ']' Type public static boolean MapType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MapType")) return false; if (!nextTokenIs(b, MAP)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, MAP_TYPE, null); r = consumeToken(b, MAP); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, LBRACK)); r = p && report_error_(b, Type(b, l + 1)) && r; r = p && report_error_(b, consumeToken(b, RBRACK)) && r; r = p && Type(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // func Receiver identifier Signature BlockWithConsume? public static boolean MethodDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodDeclaration")) return false; if (!nextTokenIs(b, FUNC)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, METHOD_DECLARATION, null); r = consumeToken(b, FUNC); p = r; // pin = 1 r = r && report_error_(b, Receiver(b, l + 1)); r = p && report_error_(b, consumeToken(b, IDENTIFIER)) && r; r = p && report_error_(b, Signature(b, l + 1)) && r; r = p && MethodDeclaration_4(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // BlockWithConsume? private static boolean MethodDeclaration_4(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodDeclaration_4")) return false; BlockWithConsume(b, l + 1); return true; } /* ********************************************************** */ // TypeName &(!'(') | identifier Signature public static boolean MethodSpec(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpec")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = MethodSpec_0(b, l + 1); if (!r) r = MethodSpec_1(b, l + 1); exit_section_(b, m, METHOD_SPEC, r); return r; } // TypeName &(!'(') private static boolean MethodSpec_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpec_0")) return false; boolean r; Marker m = enter_section_(b); r = TypeName(b, l + 1); r = r && MethodSpec_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &(!'(') private static boolean MethodSpec_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpec_0_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = MethodSpec_0_1_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // !'(' private static boolean MethodSpec_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpec_0_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !consumeToken(b, LPAREN); exit_section_(b, l, m, r, false, null); return r; } // identifier Signature private static boolean MethodSpec_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpec_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); r = r && Signature(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // MethodSpec (semi MethodSpec)* semi? static boolean MethodSpecs(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpecs")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = MethodSpec(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, MethodSpecs_1(b, l + 1)); r = p && MethodSpecs_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi MethodSpec)* private static boolean MethodSpecs_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpecs_1")) return false; int c = current_position_(b); while (true) { if (!MethodSpecs_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "MethodSpecs_1", c)) break; c = current_position_(b); } return true; } // semi MethodSpec private static boolean MethodSpecs_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpecs_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && MethodSpec(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean MethodSpecs_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MethodSpecs_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // '*' | '/' | '%' | '<<' | '>>' | '&' | '&^' static boolean MulOp(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "MulOp")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, MUL); if (!r) r = consumeToken(b, QUOTIENT); if (!r) r = consumeToken(b, REMAINDER); if (!r) r = consumeToken(b, SHIFT_LEFT); if (!r) r = consumeToken(b, SHIFT_RIGHT); if (!r) r = consumeToken(b, BIT_AND); if (!r) r = consumeToken(b, BIT_CLEAR); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // package identifier public static boolean PackageClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "PackageClause")) return false; if (!nextTokenIs(b, PACKAGE)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, PACKAGE_CLAUSE, null); r = consumeTokens(b, 1, PACKAGE, IDENTIFIER); p = r; // pin = 1 exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // '(' Type ')' public static boolean ParType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParType")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LPAREN); r = r && Type(b, l + 1); r = r && consumeToken(b, RPAREN); exit_section_(b, m, PAR_TYPE, r); return r; } /* ********************************************************** */ // identifier public static boolean ParamDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinition")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, PARAM_DEFINITION, r); return r; } /* ********************************************************** */ // ParamDefinition &(!('.' | ')')) (',' ParamDefinition)* static boolean ParamDefinitionListNoPin(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = ParamDefinition(b, l + 1); r = r && ParamDefinitionListNoPin_1(b, l + 1); r = r && ParamDefinitionListNoPin_2(b, l + 1); exit_section_(b, m, null, r); return r; } // &(!('.' | ')')) private static boolean ParamDefinitionListNoPin_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = ParamDefinitionListNoPin_1_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // !('.' | ')') private static boolean ParamDefinitionListNoPin_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin_1_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !ParamDefinitionListNoPin_1_0_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '.' | ')' private static boolean ParamDefinitionListNoPin_1_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin_1_0_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, DOT); if (!r) r = consumeToken(b, RPAREN); exit_section_(b, m, null, r); return r; } // (',' ParamDefinition)* private static boolean ParamDefinitionListNoPin_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin_2")) return false; int c = current_position_(b); while (true) { if (!ParamDefinitionListNoPin_2_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ParamDefinitionListNoPin_2", c)) break; c = current_position_(b); } return true; } // ',' ParamDefinition private static boolean ParamDefinitionListNoPin_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParamDefinitionListNoPin_2_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && ParamDefinition(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // ParamDefinitionListNoPin? '...'? Type | Type public static boolean ParameterDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterDeclaration")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, PARAMETER_DECLARATION, ""); r = ParameterDeclaration_0(b, l + 1); if (!r) r = Type(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // ParamDefinitionListNoPin? '...'? Type private static boolean ParameterDeclaration_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterDeclaration_0")) return false; boolean r; Marker m = enter_section_(b); r = ParameterDeclaration_0_0(b, l + 1); r = r && ParameterDeclaration_0_1(b, l + 1); r = r && Type(b, l + 1); exit_section_(b, m, null, r); return r; } // ParamDefinitionListNoPin? private static boolean ParameterDeclaration_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterDeclaration_0_0")) return false; ParamDefinitionListNoPin(b, l + 1); return true; } // '...'? private static boolean ParameterDeclaration_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterDeclaration_0_1")) return false; consumeToken(b, TRIPLE_DOT); return true; } /* ********************************************************** */ // ParameterDeclaration (',' (ParameterDeclaration | &')'))* static boolean ParameterList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterList")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ParameterDeclaration(b, l + 1); p = r; // pin = 1 r = r && ParameterList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // (',' (ParameterDeclaration | &')'))* private static boolean ParameterList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterList_1")) return false; int c = current_position_(b); while (true) { if (!ParameterList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "ParameterList_1", c)) break; c = current_position_(b); } return true; } // ',' (ParameterDeclaration | &')') private static boolean ParameterList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && ParameterList_1_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ParameterDeclaration | &')' private static boolean ParameterList_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterList_1_0_1")) return false; boolean r; Marker m = enter_section_(b); r = ParameterDeclaration(b, l + 1); if (!r) r = ParameterList_1_0_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &')' private static boolean ParameterList_1_0_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParameterList_1_0_1_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, RPAREN); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // '(' [ (ParameterList ','?| TypeListNoPin) ] ')' public static boolean Parameters(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Parameters")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, PARAMETERS, null); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, Parameters_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // [ (ParameterList ','?| TypeListNoPin) ] private static boolean Parameters_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Parameters_1")) return false; Parameters_1_0(b, l + 1); return true; } // ParameterList ','?| TypeListNoPin private static boolean Parameters_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Parameters_1_0")) return false; boolean r; Marker m = enter_section_(b); r = Parameters_1_0_0(b, l + 1); if (!r) r = TypeListNoPin(b, l + 1); exit_section_(b, m, null, r); return r; } // ParameterList ','? private static boolean Parameters_1_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Parameters_1_0_0")) return false; boolean r; Marker m = enter_section_(b); r = ParameterList(b, l + 1); r = r && Parameters_1_0_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ','? private static boolean Parameters_1_0_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Parameters_1_0_0_1")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // '*' Type public static boolean PointerType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "PointerType")) return false; if (!nextTokenIs(b, MUL)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, POINTER_TYPE, null); r = consumeToken(b, MUL); p = r; // pin = 1 r = r && Type(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // '.' identifier public static boolean QualifiedReferenceExpression(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "QualifiedReferenceExpression")) return false; if (!nextTokenIs(b, DOT)) return false; boolean r; Marker m = enter_section_(b, l, _LEFT_, REFERENCE_EXPRESSION, null); r = consumeToken(b, DOT); r = r && consumeToken(b, IDENTIFIER); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // '.' identifier public static boolean QualifiedTypeReferenceExpression(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "QualifiedTypeReferenceExpression")) return false; if (!nextTokenIs(b, DOT)) return false; boolean r; Marker m = enter_section_(b, l, _LEFT_, TYPE_REFERENCE_EXPRESSION, null); r = consumeToken(b, DOT); r = r && consumeToken(b, IDENTIFIER); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // range Expression | ExpressionsOrVariables range Expression public static boolean RangeClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RangeClause")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, RANGE_CLAUSE, ""); r = RangeClause_0(b, l + 1); if (!r) r = RangeClause_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // range Expression private static boolean RangeClause_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RangeClause_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, RANGE); p = r; // pin = 1 r = r && Expression(b, l + 1, -1); exit_section_(b, l, m, r, p, null); return r || p; } // ExpressionsOrVariables range Expression private static boolean RangeClause_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RangeClause_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = ExpressionsOrVariables(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, RANGE)); r = p && Expression(b, l + 1, -1) && r; exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // '(' (identifier ReceiverTail | ReceiverTail) ')' public static boolean Receiver(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Receiver")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, RECEIVER, null); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, Receiver_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // identifier ReceiverTail | ReceiverTail private static boolean Receiver_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Receiver_1")) return false; boolean r; Marker m = enter_section_(b); r = Receiver_1_0(b, l + 1); if (!r) r = ReceiverTail(b, l + 1); exit_section_(b, m, null, r); return r; } // identifier ReceiverTail private static boolean Receiver_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Receiver_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); r = r && ReceiverTail(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Type ','? static boolean ReceiverTail(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ReceiverTail")) return false; boolean r; Marker m = enter_section_(b); r = Type(b, l + 1); r = r && ReceiverTail_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ','? private static boolean ReceiverTail_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ReceiverTail_1")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // ExpressionsOrVariables? Expression public static boolean RecvStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RecvStatement")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, RECV_STATEMENT, ""); r = RecvStatement_0(b, l + 1); r = r && Expression(b, l + 1, -1); exit_section_(b, l, m, r, false, null); return r; } // ExpressionsOrVariables? private static boolean RecvStatement_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RecvStatement_0")) return false; ExpressionsOrVariables(b, l + 1); return true; } /* ********************************************************** */ // identifier public static boolean ReferenceExpression(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ReferenceExpression")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, REFERENCE_EXPRESSION, r); return r; } /* ********************************************************** */ // '==' | '!=' | '<' | '<=' | '>' | '>=' static boolean RelOp(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "RelOp")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, EQ); if (!r) r = consumeToken(b, NOT_EQ); if (!r) r = consumeToken(b, LESS); if (!r) r = consumeToken(b, LESS_OR_EQUAL); if (!r) r = consumeToken(b, GREATER); if (!r) r = consumeToken(b, GREATER_OR_EQUAL); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // '(' TypeListNoPin ')' | Type | Parameters public static boolean Result(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Result")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, RESULT, ""); r = Result_0(b, l + 1); if (!r) r = Type(b, l + 1); if (!r) r = Parameters(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '(' TypeListNoPin ')' private static boolean Result_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Result_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LPAREN); r = r && TypeListNoPin(b, l + 1); r = r && consumeToken(b, RPAREN); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // return ExpressionList? public static boolean ReturnStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ReturnStatement")) return false; if (!nextTokenIs(b, RETURN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, RETURN_STATEMENT, null); r = consumeToken(b, RETURN); p = r; // pin = 1 r = r && ReturnStatement_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ExpressionList? private static boolean ReturnStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ReturnStatement_1")) return false; ExpressionList(b, l + 1); return true; } /* ********************************************************** */ // select '{' CommClause* '}' public static boolean SelectStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SelectStatement")) return false; if (!nextTokenIs(b, SELECT)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, SELECT_STATEMENT, null); r = consumeToken(b, SELECT); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, LBRACE)); r = p && report_error_(b, SelectStatement_2(b, l + 1)) && r; r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // CommClause* private static boolean SelectStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SelectStatement_2")) return false; int c = current_position_(b); while (true) { if (!CommClause(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "SelectStatement_2", c)) break; c = current_position_(b); } return true; } /* ********************************************************** */ // '<-' Expression public static boolean SendStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SendStatement")) return false; if (!nextTokenIs(b, SEND_CHANNEL)) return false; boolean r, p; Marker m = enter_section_(b, l, _LEFT_, SEND_STATEMENT, null); r = consumeToken(b, SEND_CHANNEL); p = r; // pin = 1 r = r && Expression(b, l + 1, -1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // VarDefinitionList ':=' ExpressionList public static boolean ShortVarDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ShortVarDeclaration")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, SHORT_VAR_DECLARATION, null); r = VarDefinitionList(b, l + 1); r = r && consumeToken(b, VAR_ASSIGN); p = r; // pin = 2 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // Parameters Result? public static boolean Signature(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Signature")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, SIGNATURE, null); r = Parameters(b, l + 1); p = r; // pin = 1 r = r && Signature_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Result? private static boolean Signature_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Signature_1")) return false; Result(b, l + 1); return true; } /* ********************************************************** */ // ShortVarDeclaration // | IncDecStatement // | (LeftHandExprList [AssignmentStatement | SendStatement]) public static boolean SimpleStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatement")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, SIMPLE_STATEMENT, ""); r = ShortVarDeclaration(b, l + 1); if (!r) r = IncDecStatement(b, l + 1); if (!r) r = SimpleStatement_2(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // LeftHandExprList [AssignmentStatement | SendStatement] private static boolean SimpleStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatement_2")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = LeftHandExprList(b, l + 1); p = r; // pin = LeftHandExprList r = r && SimpleStatement_2_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // [AssignmentStatement | SendStatement] private static boolean SimpleStatement_2_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatement_2_1")) return false; SimpleStatement_2_1_0(b, l + 1); return true; } // AssignmentStatement | SendStatement private static boolean SimpleStatement_2_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatement_2_1_0")) return false; boolean r; Marker m = enter_section_(b); r = AssignmentStatement(b, l + 1); if (!r) r = SendStatement(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // [SimpleStatement ';'?] static boolean SimpleStatementOpt(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatementOpt")) return false; SimpleStatementOpt_0(b, l + 1); return true; } // SimpleStatement ';'? private static boolean SimpleStatementOpt_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatementOpt_0")) return false; boolean r; Marker m = enter_section_(b); r = SimpleStatement(b, l + 1); r = r && SimpleStatementOpt_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // ';'? private static boolean SimpleStatementOpt_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SimpleStatementOpt_0_1")) return false; consumeToken(b, SEMICOLON); return true; } /* ********************************************************** */ // &':' (':' Expression ':' Expression) | (':' Expression?) static boolean SliceExprBody(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody")) return false; if (!nextTokenIs(b, COLON)) return false; boolean r; Marker m = enter_section_(b); r = SliceExprBody_0(b, l + 1); if (!r) r = SliceExprBody_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &':' (':' Expression ':' Expression) private static boolean SliceExprBody_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody_0")) return false; boolean r; Marker m = enter_section_(b); r = SliceExprBody_0_0(b, l + 1); r = r && SliceExprBody_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &':' private static boolean SliceExprBody_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody_0_0")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, COLON); exit_section_(b, l, m, r, false, null); return r; } // ':' Expression ':' Expression private static boolean SliceExprBody_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody_0_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COLON); r = r && Expression(b, l + 1, -1); r = r && consumeToken(b, COLON); r = r && Expression(b, l + 1, -1); exit_section_(b, m, null, r); return r; } // ':' Expression? private static boolean SliceExprBody_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COLON); r = r && SliceExprBody_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // Expression? private static boolean SliceExprBody_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SliceExprBody_1_1")) return false; Expression(b, l + 1, -1); return true; } /* ********************************************************** */ // SliceExprBody static boolean SliceExprBodyInner(PsiBuilder b, int l) { return SliceExprBody(b, l + 1); } /* ********************************************************** */ // identifier Type public static boolean SpecType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SpecType")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, SPEC_TYPE, null); r = consumeToken(b, IDENTIFIER); p = r; // pin = 1 r = r && Type(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // ConstDeclaration // | TypeDeclaration // | VarDeclaration // | LabeledStatement // | SimpleStatement // | GoStatement // | ReturnStatement // | BreakStatement // | ContinueStatement // | GotoStatement // | FallthroughStatement // | Block // | IfStatement // | SwitchStatement // | SelectStatement // | ForStatement // | DeferStatement public static boolean Statement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Statement")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, STATEMENT, ""); r = ConstDeclaration(b, l + 1); if (!r) r = TypeDeclaration(b, l + 1); if (!r) r = VarDeclaration(b, l + 1); if (!r) r = LabeledStatement(b, l + 1); if (!r) r = SimpleStatement(b, l + 1); if (!r) r = GoStatement(b, l + 1); if (!r) r = ReturnStatement(b, l + 1); if (!r) r = BreakStatement(b, l + 1); if (!r) r = ContinueStatement(b, l + 1); if (!r) r = GotoStatement(b, l + 1); if (!r) r = FallthroughStatement(b, l + 1); if (!r) r = Block(b, l + 1); if (!r) r = IfStatement(b, l + 1); if (!r) r = SwitchStatement(b, l + 1); if (!r) r = SelectStatement(b, l + 1); if (!r) r = ForStatement(b, l + 1); if (!r) r = DeferStatement(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // !('!' | '&' | '(' | '*' | '+' | '-' | ';' | '<-' | '^' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var) static boolean StatementRecover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StatementRecover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !StatementRecover_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '!' | '&' | '(' | '*' | '+' | '-' | ';' | '<-' | '^' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var private static boolean StatementRecover_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StatementRecover_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, NOT); if (!r) r = consumeToken(b, BIT_AND); if (!r) r = consumeToken(b, LPAREN); if (!r) r = consumeToken(b, MUL); if (!r) r = consumeToken(b, PLUS); if (!r) r = consumeToken(b, MINUS); if (!r) r = consumeToken(b, SEMICOLON); if (!r) r = consumeToken(b, SEND_CHANNEL); if (!r) r = consumeToken(b, BIT_XOR); if (!r) r = consumeToken(b, TYPE_); if (!r) r = consumeToken(b, LBRACE); if (!r) r = consumeToken(b, BIT_OR); if (!r) r = consumeToken(b, BIT_OR_ASSIGN); if (!r) r = consumeToken(b, COND_OR); if (!r) r = consumeToken(b, RBRACE); if (!r) r = consumeToken(b, BREAK); if (!r) r = consumeToken(b, CASE); if (!r) r = consumeToken(b, CHAR); if (!r) r = consumeToken(b, CONST); if (!r) r = consumeToken(b, CONTINUE); if (!r) r = consumeToken(b, DECIMALI); if (!r) r = consumeToken(b, DEFAULT); if (!r) r = consumeToken(b, DEFER); if (!r) r = consumeToken(b, ELSE); if (!r) r = consumeToken(b, FALLTHROUGH); if (!r) r = consumeToken(b, FLOAT); if (!r) r = consumeToken(b, FLOATI); if (!r) r = consumeToken(b, FOR); if (!r) r = consumeToken(b, FUNC); if (!r) r = consumeToken(b, GO); if (!r) r = consumeToken(b, GOTO); if (!r) r = consumeToken(b, HEX); if (!r) r = consumeToken(b, IDENTIFIER); if (!r) r = consumeToken(b, IF); if (!r) r = consumeToken(b, INT); if (!r) r = consumeToken(b, INTERFACE); if (!r) r = consumeToken(b, MAP); if (!r) r = consumeToken(b, OCT); if (!r) r = consumeToken(b, RETURN); if (!r) r = consumeToken(b, SELECT); if (!r) r = consumeToken(b, STRING); if (!r) r = consumeToken(b, RAW_STRING); if (!r) r = consumeToken(b, STRUCT); if (!r) r = consumeToken(b, SWITCH); if (!r) r = consumeToken(b, VAR); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Statement (semi|&'}') static boolean StatementWithSemi(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StatementWithSemi")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = Statement(b, l + 1); p = r; // pin = 1 r = r && StatementWithSemi_1(b, l + 1); exit_section_(b, l, m, r, p, StatementRecover_parser_); return r || p; } // semi|&'}' private static boolean StatementWithSemi_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StatementWithSemi_1")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); if (!r) r = StatementWithSemi_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // &'}' private static boolean StatementWithSemi_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StatementWithSemi_1_1")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = consumeToken(b, RBRACE); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // StatementWithSemi* static boolean Statements(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Statements")) return false; int c = current_position_(b); while (true) { if (!StatementWithSemi(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "Statements", c)) break; c = current_position_(b); } return true; } /* ********************************************************** */ // string | raw_string public static boolean StringLiteral(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StringLiteral")) return false; if (!nextTokenIs(b, "", RAW_STRING, STRING)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, STRING_LITERAL, ""); r = consumeToken(b, STRING); if (!r) r = consumeToken(b, RAW_STRING); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // struct '{' Fields? '}' public static boolean StructType(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StructType")) return false; if (!nextTokenIs(b, STRUCT)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, STRUCT_TYPE, null); r = consumeToken(b, STRUCT); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, LBRACE)); r = p && report_error_(b, StructType_2(b, l + 1)) && r; r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // Fields? private static boolean StructType_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "StructType_2")) return false; Fields(b, l + 1); return true; } /* ********************************************************** */ // switch public static boolean SwitchStart(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SwitchStart")) return false; if (!nextTokenIs(b, SWITCH)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, SWITCH); exit_section_(b, m, SWITCH_START, r); return r; } /* ********************************************************** */ // SwitchStart (TypeSwitchStatement | ExprSwitchStatement) public static boolean SwitchStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SwitchStatement")) return false; if (!nextTokenIs(b, SWITCH)) return false; boolean r, p; Marker m = enter_section_(b, l, _COLLAPSE_, SWITCH_STATEMENT, null); r = SwitchStart(b, l + 1); p = r; // pin = 1 r = r && SwitchStatement_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // TypeSwitchStatement | ExprSwitchStatement private static boolean SwitchStatement_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SwitchStatement_1")) return false; boolean r; Marker m = enter_section_(b); r = TypeSwitchStatement(b, l + 1); if (!r) r = ExprSwitchStatement(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // StringLiteral public static boolean Tag(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Tag")) return false; if (!nextTokenIs(b, "", RAW_STRING, STRING)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, TAG, ""); r = StringLiteral(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // ConstDeclaration // | TypeDeclaration // | VarDeclaration // | FunctionDeclaration // | MethodDeclaration static boolean TopDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TopDeclaration")) return false; boolean r; Marker m = enter_section_(b); r = ConstDeclaration(b, l + 1); if (!r) r = TypeDeclaration(b, l + 1); if (!r) r = VarDeclaration(b, l + 1); if (!r) r = FunctionDeclaration(b, l + 1); if (!r) r = MethodDeclaration(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // !<> TopDeclaration semi static boolean TopLevelDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TopLevelDeclaration")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = TopLevelDeclaration_0(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, TopDeclaration(b, l + 1)); r = p && semi(b, l + 1) && r; exit_section_(b, l, m, r, p, TopLevelDeclarationRecover_parser_); return r || p; } // !<> private static boolean TopLevelDeclaration_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TopLevelDeclaration_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !eof(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // !(';' |'type' | const | func | var) static boolean TopLevelDeclarationRecover(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TopLevelDeclarationRecover")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !TopLevelDeclarationRecover_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // ';' |'type' | const | func | var private static boolean TopLevelDeclarationRecover_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TopLevelDeclarationRecover_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, SEMICOLON); if (!r) r = consumeToken(b, TYPE_); if (!r) r = consumeToken(b, CONST); if (!r) r = consumeToken(b, FUNC); if (!r) r = consumeToken(b, VAR); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // TypeName | TypeLit | ParType public static boolean Type(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Type")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, TYPE, ""); r = TypeName(b, l + 1); if (!r) r = TypeLit(b, l + 1); if (!r) r = ParType(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // !'}' TypeSwitchCase ':' Statements? public static boolean TypeCaseClause(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeCaseClause")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, TYPE_CASE_CLAUSE, ""); r = TypeCaseClause_0(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, TypeSwitchCase(b, l + 1)); r = p && report_error_(b, consumeToken(b, COLON)) && r; r = p && TypeCaseClause_3(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // !'}' private static boolean TypeCaseClause_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeCaseClause_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !consumeToken(b, RBRACE); exit_section_(b, l, m, r, false, null); return r; } // Statements? private static boolean TypeCaseClause_3(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeCaseClause_3")) return false; Statements(b, l + 1); return true; } /* ********************************************************** */ // 'type' ( TypeSpec | '(' TypeSpecs? ')' ) public static boolean TypeDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeDeclaration")) return false; if (!nextTokenIs(b, TYPE_)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, TYPE_DECLARATION, null); r = consumeToken(b, TYPE_); p = r; // pin = 1 r = r && TypeDeclaration_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // TypeSpec | '(' TypeSpecs? ')' private static boolean TypeDeclaration_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeDeclaration_1")) return false; boolean r; Marker m = enter_section_(b); r = TypeSpec(b, l + 1); if (!r) r = TypeDeclaration_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '(' TypeSpecs? ')' private static boolean TypeDeclaration_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeDeclaration_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, TypeDeclaration_1_1_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // TypeSpecs? private static boolean TypeDeclaration_1_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeDeclaration_1_1_1")) return false; TypeSpecs(b, l + 1); return true; } /* ********************************************************** */ // '(' 'type' ')' public static boolean TypeGuard(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeGuard")) return false; if (!nextTokenIs(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, TYPE_GUARD, null); r = consumeToken(b, LPAREN); r = r && consumeToken(b, TYPE_); p = r; // pin = 2 r = r && consumeToken(b, RPAREN); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // Type ( ',' Type )* ','? public static boolean TypeList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeList")) return false; boolean r, p; Marker m = enter_section_(b, l, _COLLAPSE_, TYPE_LIST, ""); r = Type(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, TypeList_1(b, l + 1)); r = p && TypeList_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // ( ',' Type )* private static boolean TypeList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeList_1")) return false; int c = current_position_(b); while (true) { if (!TypeList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "TypeList_1", c)) break; c = current_position_(b); } return true; } // ',' Type private static boolean TypeList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && Type(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ','? private static boolean TypeList_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeList_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // Type ( ',' Type )* ','? public static boolean TypeListNoPin(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeListNoPin")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, TYPE_LIST, ""); r = Type(b, l + 1); r = r && TypeListNoPin_1(b, l + 1); r = r && TypeListNoPin_2(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // ( ',' Type )* private static boolean TypeListNoPin_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeListNoPin_1")) return false; int c = current_position_(b); while (true) { if (!TypeListNoPin_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "TypeListNoPin_1", c)) break; c = current_position_(b); } return true; } // ',' Type private static boolean TypeListNoPin_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeListNoPin_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && Type(b, l + 1); exit_section_(b, m, null, r); return r; } // ','? private static boolean TypeListNoPin_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeListNoPin_2")) return false; consumeToken(b, COMMA); return true; } /* ********************************************************** */ // ArrayOrSliceType // | StructType // | PointerType // | FunctionType // | InterfaceType // | MapType // | ChannelType static boolean TypeLit(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeLit")) return false; boolean r; Marker m = enter_section_(b); r = ArrayOrSliceType(b, l + 1); if (!r) r = StructType(b, l + 1); if (!r) r = PointerType(b, l + 1); if (!r) r = FunctionType(b, l + 1); if (!r) r = InterfaceType(b, l + 1); if (!r) r = MapType(b, l + 1); if (!r) r = ChannelType(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // TypeReferenceExpression QualifiedTypeReferenceExpression? static boolean TypeName(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeName")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = TypeReferenceExpression(b, l + 1); r = r && TypeName_1(b, l + 1); exit_section_(b, m, null, r); return r; } // QualifiedTypeReferenceExpression? private static boolean TypeName_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeName_1")) return false; QualifiedTypeReferenceExpression(b, l + 1); return true; } /* ********************************************************** */ // identifier public static boolean TypeReferenceExpression(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeReferenceExpression")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, TYPE_REFERENCE_EXPRESSION, r); return r; } /* ********************************************************** */ // SpecType public static boolean TypeSpec(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSpec")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = SpecType(b, l + 1); exit_section_(b, m, TYPE_SPEC, r); return r; } /* ********************************************************** */ // TypeSpec (semi TypeSpec)* semi? static boolean TypeSpecs(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSpecs")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = TypeSpec(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, TypeSpecs_1(b, l + 1)); r = p && TypeSpecs_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi TypeSpec)* private static boolean TypeSpecs_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSpecs_1")) return false; int c = current_position_(b); while (true) { if (!TypeSpecs_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "TypeSpecs_1", c)) break; c = current_position_(b); } return true; } // semi TypeSpec private static boolean TypeSpecs_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSpecs_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && TypeSpec(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean TypeSpecs_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSpecs_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // case TypeList | default static boolean TypeSwitchCase(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchCase")) return false; if (!nextTokenIs(b, "", CASE, DEFAULT)) return false; boolean r; Marker m = enter_section_(b); r = TypeSwitchCase_0(b, l + 1); if (!r) r = consumeToken(b, DEFAULT); exit_section_(b, m, null, r); return r; } // case TypeList private static boolean TypeSwitchCase_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchCase_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, CASE); p = r; // pin = 1 r = r && TypeList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // [ VarDefinition ':=' ] Expression '.' TypeGuard public static boolean TypeSwitchGuard(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchGuard")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, TYPE_SWITCH_GUARD, ""); r = TypeSwitchGuard_0(b, l + 1); r = r && Expression(b, l + 1, -1); r = r && consumeToken(b, DOT); r = r && TypeGuard(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // [ VarDefinition ':=' ] private static boolean TypeSwitchGuard_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchGuard_0")) return false; TypeSwitchGuard_0_0(b, l + 1); return true; } // VarDefinition ':=' private static boolean TypeSwitchGuard_0_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchGuard_0_0")) return false; boolean r; Marker m = enter_section_(b); r = VarDefinition(b, l + 1); r = r && consumeToken(b, VAR_ASSIGN); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // (TypeSwitchGuard | SimpleStatement ';'? TypeSwitchGuard) '{' ( TypeCaseClause )* '}' public static boolean TypeSwitchStatement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement")) return false; boolean r, p; Marker m = enter_section_(b, l, _LEFT_, TYPE_SWITCH_STATEMENT, ""); r = TypeSwitchStatement_0(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, consumeToken(b, LBRACE)); r = p && report_error_(b, TypeSwitchStatement_2(b, l + 1)) && r; r = p && consumeToken(b, RBRACE) && r; exit_section_(b, l, m, r, p, null); return r || p; } // TypeSwitchGuard | SimpleStatement ';'? TypeSwitchGuard private static boolean TypeSwitchStatement_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement_0")) return false; boolean r; Marker m = enter_section_(b); r = TypeSwitchGuard(b, l + 1); if (!r) r = TypeSwitchStatement_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // SimpleStatement ';'? TypeSwitchGuard private static boolean TypeSwitchStatement_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement_0_1")) return false; boolean r; Marker m = enter_section_(b); r = SimpleStatement(b, l + 1); r = r && TypeSwitchStatement_0_1_1(b, l + 1); r = r && TypeSwitchGuard(b, l + 1); exit_section_(b, m, null, r); return r; } // ';'? private static boolean TypeSwitchStatement_0_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement_0_1_1")) return false; consumeToken(b, SEMICOLON); return true; } // ( TypeCaseClause )* private static boolean TypeSwitchStatement_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement_2")) return false; int c = current_position_(b); while (true) { if (!TypeSwitchStatement_2_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "TypeSwitchStatement_2", c)) break; c = current_position_(b); } return true; } // ( TypeCaseClause ) private static boolean TypeSwitchStatement_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeSwitchStatement_2_0")) return false; boolean r; Marker m = enter_section_(b); r = TypeCaseClause(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // '+' | '-' | '!' | '^' | '*' | '&' | '<-' static boolean UnaryOp(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "UnaryOp")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, PLUS); if (!r) r = consumeToken(b, MINUS); if (!r) r = consumeToken(b, NOT); if (!r) r = consumeToken(b, BIT_XOR); if (!r) r = consumeToken(b, MUL); if (!r) r = consumeToken(b, BIT_AND); if (!r) r = consumeToken(b, SEND_CHANNEL); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Expression | LiteralValue public static boolean Value(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Value")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, VALUE, ""); r = Expression(b, l + 1, -1); if (!r) r = LiteralValue(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // var ( VarSpec | '(' VarSpecs? ')' ) public static boolean VarDeclaration(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDeclaration")) return false; if (!nextTokenIs(b, VAR)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, VAR_DECLARATION, null); r = consumeToken(b, VAR); p = r; // pin = 1 r = r && VarDeclaration_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // VarSpec | '(' VarSpecs? ')' private static boolean VarDeclaration_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDeclaration_1")) return false; boolean r; Marker m = enter_section_(b); r = VarSpec(b, l + 1); if (!r) r = VarDeclaration_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // '(' VarSpecs? ')' private static boolean VarDeclaration_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDeclaration_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, VarDeclaration_1_1_1(b, l + 1)); r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } // VarSpecs? private static boolean VarDeclaration_1_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDeclaration_1_1_1")) return false; VarSpecs(b, l + 1); return true; } /* ********************************************************** */ // identifier public static boolean VarDefinition(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDefinition")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, IDENTIFIER); exit_section_(b, m, VAR_DEFINITION, r); return r; } /* ********************************************************** */ // VarDefinition ( ',' VarDefinition )* static boolean VarDefinitionList(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDefinitionList")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = VarDefinition(b, l + 1); p = r; // pin = 1 r = r && VarDefinitionList_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // ( ',' VarDefinition )* private static boolean VarDefinitionList_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDefinitionList_1")) return false; int c = current_position_(b); while (true) { if (!VarDefinitionList_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "VarDefinitionList_1", c)) break; c = current_position_(b); } return true; } // ',' VarDefinition private static boolean VarDefinitionList_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarDefinitionList_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, COMMA); p = r; // pin = 1 r = r && VarDefinition(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // VarDefinitionList ( Type [ '=' ExpressionList ] | '=' ExpressionList ) public static boolean VarSpec(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, VAR_SPEC, null); r = VarDefinitionList(b, l + 1); p = r; // pin = 1 r = r && VarSpec_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // Type [ '=' ExpressionList ] | '=' ExpressionList private static boolean VarSpec_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec_1")) return false; boolean r; Marker m = enter_section_(b); r = VarSpec_1_0(b, l + 1); if (!r) r = VarSpec_1_1(b, l + 1); exit_section_(b, m, null, r); return r; } // Type [ '=' ExpressionList ] private static boolean VarSpec_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = Type(b, l + 1); p = r; // pin = 1 r = r && VarSpec_1_0_1(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // [ '=' ExpressionList ] private static boolean VarSpec_1_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec_1_0_1")) return false; VarSpec_1_0_1_0(b, l + 1); return true; } // '=' ExpressionList private static boolean VarSpec_1_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec_1_0_1_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, ASSIGN); p = r; // pin = 1 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // '=' ExpressionList private static boolean VarSpec_1_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpec_1_1")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = consumeToken(b, ASSIGN); p = r; // pin = 1 r = r && ExpressionList(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } /* ********************************************************** */ // VarSpec (semi VarSpec)* semi? static boolean VarSpecs(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpecs")) return false; if (!nextTokenIs(b, IDENTIFIER)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = VarSpec(b, l + 1); p = r; // pin = 1 r = r && report_error_(b, VarSpecs_1(b, l + 1)); r = p && VarSpecs_2(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // (semi VarSpec)* private static boolean VarSpecs_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpecs_1")) return false; int c = current_position_(b); while (true) { if (!VarSpecs_1_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "VarSpecs_1", c)) break; c = current_position_(b); } return true; } // semi VarSpec private static boolean VarSpecs_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpecs_1_0")) return false; boolean r; Marker m = enter_section_(b); r = semi(b, l + 1); r = r && VarSpec(b, l + 1); exit_section_(b, m, null, r); return r; } // semi? private static boolean VarSpecs_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "VarSpecs_2")) return false; semi(b, l + 1); return true; } /* ********************************************************** */ // '=' | '+=' | '-=' | '|=' | '^=' | '*=' | '/=' | '%=' | '<<=' | '>>=' | '&=' | '&^=' public static boolean assign_op(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "assign_op")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, ASSIGN_OP, ""); r = consumeToken(b, ASSIGN); if (!r) r = consumeToken(b, PLUS_ASSIGN); if (!r) r = consumeToken(b, MINUS_ASSIGN); if (!r) r = consumeToken(b, BIT_OR_ASSIGN); if (!r) r = consumeToken(b, BIT_XOR_ASSIGN); if (!r) r = consumeToken(b, MUL_ASSIGN); if (!r) r = consumeToken(b, QUOTIENT_ASSIGN); if (!r) r = consumeToken(b, REMAINDER_ASSIGN); if (!r) r = consumeToken(b, SHIFT_LEFT_ASSIGN); if (!r) r = consumeToken(b, SHIFT_RIGHT_ASSIGN); if (!r) r = consumeToken(b, BIT_AND_ASSIGN); if (!r) r = consumeToken(b, BIT_CLEAR_ASSIGN); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ // '' | ';' | <> static boolean semi(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "semi")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, SEMICOLON_SYNTHETIC); if (!r) r = consumeToken(b, SEMICOLON); if (!r) r = eof(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // Expression root: Expression // Operator priority table: // 0: BINARY(OrExpr) // 1: BINARY(AndExpr) // 2: BINARY(ConditionalExpr) // 3: BINARY(AddExpr) // 4: BINARY(MulExpr) // 5: PREFIX(UnaryExpr) // 6: ATOM(ConversionExpr) // 7: ATOM(CompositeLit) ATOM(OperandName) POSTFIX(BuiltinCallExpr) POSTFIX(CallExpr) // POSTFIX(TypeAssertionExpr) BINARY(SelectorExpr) POSTFIX(IndexOrSliceExpr) ATOM(Literal) // ATOM(FunctionLit) // 8: ATOM(ParenthesesExpr) public static boolean Expression(PsiBuilder b, int l, int g) { if (!recursion_guard_(b, l, "Expression")) return false; addVariant(b, ""); boolean r, p; Marker m = enter_section_(b, l, _NONE_, ""); r = UnaryExpr(b, l + 1); if (!r) r = ConversionExpr(b, l + 1); if (!r) r = CompositeLit(b, l + 1); if (!r) r = OperandName(b, l + 1); if (!r) r = Literal(b, l + 1); if (!r) r = FunctionLit(b, l + 1); if (!r) r = ParenthesesExpr(b, l + 1); p = r; r = r && Expression_0(b, l + 1, g); exit_section_(b, l, m, null, r, p, null); return r || p; } public static boolean Expression_0(PsiBuilder b, int l, int g) { if (!recursion_guard_(b, l, "Expression_0")) return false; boolean r = true; while (true) { Marker m = enter_section_(b, l, _LEFT_, null); if (g < 0 && consumeTokenSmart(b, COND_OR)) { r = Expression(b, l, 0); exit_section_(b, l, m, OR_EXPR, r, true, null); } else if (g < 1 && consumeTokenSmart(b, COND_AND)) { r = Expression(b, l, 1); exit_section_(b, l, m, AND_EXPR, r, true, null); } else if (g < 2 && RelOp(b, l + 1)) { r = Expression(b, l, 2); exit_section_(b, l, m, CONDITIONAL_EXPR, r, true, null); } else if (g < 3 && AddOp(b, l + 1)) { r = Expression(b, l, 3); exit_section_(b, l, m, ADD_EXPR, r, true, null); } else if (g < 4 && MulOp(b, l + 1)) { r = Expression(b, l, 4); exit_section_(b, l, m, MUL_EXPR, r, true, null); } else if (g < 7 && leftMarkerIs(b, REFERENCE_EXPRESSION) && BuiltinCallExpr_0(b, l + 1)) { r = true; exit_section_(b, l, m, BUILTIN_CALL_EXPR, r, true, null); } else if (g < 7 && ArgumentList(b, l + 1)) { r = true; exit_section_(b, l, m, CALL_EXPR, r, true, null); } else if (g < 7 && TypeAssertionExpr_0(b, l + 1)) { r = true; exit_section_(b, l, m, TYPE_ASSERTION_EXPR, r, true, null); } else if (g < 7 && SelectorExpr_0(b, l + 1)) { r = Expression(b, l, 7); exit_section_(b, l, m, SELECTOR_EXPR, r, true, null); } else if (g < 7 && IndexOrSliceExpr_0(b, l + 1)) { r = true; exit_section_(b, l, m, INDEX_OR_SLICE_EXPR, r, true, null); } else { exit_section_(b, l, m, null, false, false, null); break; } } return r; } public static boolean UnaryExpr(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "UnaryExpr")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, null); r = UnaryOp(b, l + 1); p = r; r = p && Expression(b, l, 5); exit_section_(b, l, m, UNARY_EXPR, r, p, null); return r || p; } // &ConversionPredicate Type ConversionTail public static boolean ConversionExpr(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionExpr")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, CONVERSION_EXPR, ""); r = ConversionExpr_0(b, l + 1); r = r && Type(b, l + 1); r = r && ConversionTail(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // &ConversionPredicate private static boolean ConversionExpr_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ConversionExpr_0")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = ConversionPredicate(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // LiteralTypeExprInner LiteralValue | TypeName LiteralValue public static boolean CompositeLit(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CompositeLit")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, COMPOSITE_LIT, ""); r = CompositeLit_0(b, l + 1); if (!r) r = CompositeLit_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // LiteralTypeExprInner LiteralValue private static boolean CompositeLit_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CompositeLit_0")) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_); r = LiteralTypeExprInner(b, l + 1); p = r; // pin = LiteralTypeExprInner r = r && LiteralValue(b, l + 1); exit_section_(b, l, m, r, p, null); return r || p; } // TypeName LiteralValue private static boolean CompositeLit_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "CompositeLit_1")) return false; boolean r; Marker m = enter_section_(b); r = TypeName(b, l + 1); r = r && LiteralValue(b, l + 1); exit_section_(b, m, null, r); return r; } // ReferenceExpression QualifiedReferenceExpression? public static boolean OperandName(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "OperandName")) return false; if (!nextTokenIsSmart(b, IDENTIFIER)) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, REFERENCE_EXPRESSION, null); r = ReferenceExpression(b, l + 1); r = r && OperandName_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // QualifiedReferenceExpression? private static boolean OperandName_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "OperandName_1")) return false; QualifiedReferenceExpression(b, l + 1); return true; } // <> BuiltinArgumentList private static boolean BuiltinCallExpr_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "BuiltinCallExpr_0")) return false; boolean r; Marker m = enter_section_(b); r = isBuiltin(b, l + 1); r = r && BuiltinArgumentList(b, l + 1); exit_section_(b, m, null, r); return r; } // '.' '(' &(!'type') Type ')' private static boolean TypeAssertionExpr_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeAssertionExpr_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeTokenSmart(b, DOT); r = r && consumeToken(b, LPAREN); r = r && TypeAssertionExpr_0_2(b, l + 1); r = r && Type(b, l + 1); r = r && consumeToken(b, RPAREN); exit_section_(b, m, null, r); return r; } // &(!'type') private static boolean TypeAssertionExpr_0_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeAssertionExpr_0_2")) return false; boolean r; Marker m = enter_section_(b, l, _AND_); r = TypeAssertionExpr_0_2_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // !'type' private static boolean TypeAssertionExpr_0_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "TypeAssertionExpr_0_2_0")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !consumeTokenSmart(b, TYPE_); exit_section_(b, l, m, r, false, null); return r; } // '.' !('(' 'type') private static boolean SelectorExpr_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SelectorExpr_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeTokenSmart(b, DOT); r = r && SelectorExpr_0_1(b, l + 1); exit_section_(b, m, null, r); return r; } // !('(' 'type') private static boolean SelectorExpr_0_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SelectorExpr_0_1")) return false; boolean r; Marker m = enter_section_(b, l, _NOT_); r = !SelectorExpr_0_1_0(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '(' 'type' private static boolean SelectorExpr_0_1_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "SelectorExpr_0_1_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeTokenSmart(b, LPAREN); r = r && consumeToken(b, TYPE_); exit_section_(b, m, null, r); return r; } // '[' <> (SliceExprBody | IndexExprBody) <> ']' private static boolean IndexOrSliceExpr_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IndexOrSliceExpr_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeTokenSmart(b, LBRACK); r = r && enterMode(b, l + 1, "PAR"); r = r && IndexOrSliceExpr_0_2(b, l + 1); r = r && exitModeSafe(b, l + 1, "PAR"); r = r && consumeToken(b, RBRACK); exit_section_(b, m, null, r); return r; } // SliceExprBody | IndexExprBody private static boolean IndexOrSliceExpr_0_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "IndexOrSliceExpr_0_2")) return false; boolean r; Marker m = enter_section_(b); r = SliceExprBody(b, l + 1); if (!r) r = IndexExprBody(b, l + 1); exit_section_(b, m, null, r); return r; } // int // | float // | floati // | decimali // | hex // | oct // | StringLiteral // | char public static boolean Literal(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Literal")) return false; boolean r; Marker m = enter_section_(b, l, _COLLAPSE_, LITERAL, ""); r = consumeTokenSmart(b, INT); if (!r) r = consumeTokenSmart(b, FLOAT); if (!r) r = consumeTokenSmart(b, FLOATI); if (!r) r = consumeTokenSmart(b, DECIMALI); if (!r) r = consumeTokenSmart(b, HEX); if (!r) r = consumeTokenSmart(b, OCT); if (!r) r = StringLiteral(b, l + 1); if (!r) r = consumeTokenSmart(b, CHAR); exit_section_(b, l, m, r, false, null); return r; } // func Signature Block public static boolean FunctionLit(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionLit")) return false; if (!nextTokenIsSmart(b, FUNC)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, FUNCTION_LIT, null); r = consumeTokenSmart(b, FUNC); p = r; // pin = 1 r = r && report_error_(b, Signature(b, l + 1)); r = p && Block(b, l + 1) && r; exit_section_(b, l, m, r, p, null); return r || p; } // '(' <> Expression <>')' public static boolean ParenthesesExpr(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "ParenthesesExpr")) return false; if (!nextTokenIsSmart(b, LPAREN)) return false; boolean r, p; Marker m = enter_section_(b, l, _NONE_, PARENTHESES_EXPR, null); r = consumeTokenSmart(b, LPAREN); p = r; // pin = 1 r = r && report_error_(b, enterMode(b, l + 1, "PAR")); r = p && report_error_(b, Expression(b, l + 1, -1)) && r; r = p && report_error_(b, exitModeSafe(b, l + 1, "PAR")) && r; r = p && consumeToken(b, RPAREN) && r; exit_section_(b, l, m, r, p, null); return r || p; } final static Parser E_recover_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return E_recover(b, l + 1); } }; final static Parser Element_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return Element(b, l + 1); } }; final static Parser ExpressionListRecover_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return ExpressionListRecover(b, l + 1); } }; final static Parser ExpressionOrTypeWithRecover_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return ExpressionOrTypeWithRecover(b, l + 1); } }; final static Parser StatementRecover_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return StatementRecover(b, l + 1); } }; final static Parser Statements_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return Statements(b, l + 1); } }; final static Parser TopLevelDeclarationRecover_parser_ = new Parser() { public boolean parse(PsiBuilder b, int l) { return TopLevelDeclarationRecover(b, l + 1); } }; } ================================================ FILE: gen/com/goide/psi/GoAddExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoAddExpr extends GoBinaryExpr { @Nullable PsiElement getBitOr(); @Nullable PsiElement getBitXor(); @Nullable PsiElement getMinus(); @Nullable PsiElement getPlus(); } ================================================ FILE: gen/com/goide/psi/GoAndExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoAndExpr extends GoBinaryExpr { @NotNull PsiElement getCondAnd(); } ================================================ FILE: gen/com/goide/psi/GoAnonymousFieldDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoAnonymousFieldDefinitionStub; import com.intellij.psi.ResolveState; public interface GoAnonymousFieldDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull GoType getType(); @Nullable PsiElement getIdentifier(); @Nullable String getName(); @Nullable GoTypeReferenceExpression getTypeReferenceExpression(); @Nullable GoType getGoTypeInner(ResolveState context); } ================================================ FILE: gen/com/goide/psi/GoArgumentList.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoArgumentList extends GoCompositeElement { @NotNull List getExpressionList(); @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); @Nullable PsiElement getTripleDot(); } ================================================ FILE: gen/com/goide/psi/GoArrayOrSliceType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoArrayOrSliceType extends GoType { @Nullable GoExpression getExpression(); @Nullable GoType getType(); @NotNull PsiElement getLbrack(); @Nullable PsiElement getRbrack(); @Nullable PsiElement getTripleDot(); } ================================================ FILE: gen/com/goide/psi/GoAssignOp.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoAssignOp extends GoCompositeElement { @Nullable PsiElement getAssign(); @Nullable PsiElement getBitAndAssign(); @Nullable PsiElement getBitClearAssign(); @Nullable PsiElement getBitOrAssign(); @Nullable PsiElement getBitXorAssign(); @Nullable PsiElement getMinusAssign(); @Nullable PsiElement getMulAssign(); @Nullable PsiElement getPlusAssign(); @Nullable PsiElement getQuotientAssign(); @Nullable PsiElement getRemainderAssign(); @Nullable PsiElement getShiftLeftAssign(); @Nullable PsiElement getShiftRightAssign(); } ================================================ FILE: gen/com/goide/psi/GoAssignmentStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoAssignmentStatement extends GoStatement { @NotNull List getExpressionList(); @NotNull GoLeftHandExprList getLeftHandExprList(); @NotNull GoAssignOp getAssignOp(); } ================================================ FILE: gen/com/goide/psi/GoBinaryExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoBinaryExpr extends GoExpression { @NotNull List getExpressionList(); @NotNull GoExpression getLeft(); @Nullable GoExpression getRight(); @Nullable PsiElement getOperator(); } ================================================ FILE: gen/com/goide/psi/GoBlock.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public interface GoBlock extends GoCompositeElement { @NotNull List getStatementList(); @NotNull PsiElement getLbrace(); @Nullable PsiElement getRbrace(); boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place); } ================================================ FILE: gen/com/goide/psi/GoBreakStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoBreakStatement extends GoStatement { @Nullable GoLabelRef getLabelRef(); @NotNull PsiElement getBreak(); } ================================================ FILE: gen/com/goide/psi/GoBuiltinArgumentList.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoBuiltinArgumentList extends GoArgumentList { @Nullable GoType getType(); } ================================================ FILE: gen/com/goide/psi/GoBuiltinCallExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoBuiltinCallExpr extends GoExpression { @Nullable GoBuiltinArgumentList getBuiltinArgumentList(); @NotNull GoReferenceExpression getReferenceExpression(); } ================================================ FILE: gen/com/goide/psi/GoCallExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoCallExpr extends GoExpression { @NotNull GoArgumentList getArgumentList(); @NotNull GoExpression getExpression(); } ================================================ FILE: gen/com/goide/psi/GoChannelType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoChannelType extends GoType { @Nullable GoType getType(); @Nullable PsiElement getSendChannel(); @Nullable PsiElement getChan(); } ================================================ FILE: gen/com/goide/psi/GoCommCase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoCommCase extends GoCompositeElement { @Nullable GoRecvStatement getRecvStatement(); @Nullable GoSendStatement getSendStatement(); @Nullable PsiElement getCase(); @Nullable PsiElement getDefault(); } ================================================ FILE: gen/com/goide/psi/GoCommClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoCommClause extends GoCompositeElement { @NotNull GoCommCase getCommCase(); @NotNull List getStatementList(); @Nullable PsiElement getColon(); } ================================================ FILE: gen/com/goide/psi/GoCompositeLit.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoCompositeLit extends GoExpression { @Nullable GoLiteralValue getLiteralValue(); @Nullable GoType getType(); @Nullable GoTypeReferenceExpression getTypeReferenceExpression(); } ================================================ FILE: gen/com/goide/psi/GoConditionalExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoConditionalExpr extends GoBinaryExpr { @Nullable PsiElement getEq(); @Nullable PsiElement getGreater(); @Nullable PsiElement getGreaterOrEqual(); @Nullable PsiElement getLess(); @Nullable PsiElement getLessOrEqual(); @Nullable PsiElement getNotEq(); } ================================================ FILE: gen/com/goide/psi/GoConstDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoConstDeclaration extends GoTopLevelDeclaration { @NotNull List getConstSpecList(); @Nullable PsiElement getLparen(); @Nullable PsiElement getRparen(); @NotNull PsiElement getConst(); @NotNull GoConstSpec addSpec(String name, String type, String value, GoConstSpec specAnchor); void deleteSpec(GoConstSpec specToDelete); } ================================================ FILE: gen/com/goide/psi/GoConstDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoConstDefinitionStub; import com.intellij.psi.ResolveState; public interface GoConstDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull PsiElement getIdentifier(); @Nullable GoType getGoTypeInner(ResolveState context); @Nullable GoExpression getValue(); } ================================================ FILE: gen/com/goide/psi/GoConstSpec.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoConstSpecStub; public interface GoConstSpec extends GoCompositeElement, StubBasedPsiElement { @NotNull List getConstDefinitionList(); @NotNull List getExpressionList(); @Nullable GoType getType(); @Nullable PsiElement getAssign(); void deleteDefinition(GoConstDefinition definitionToDelete); } ================================================ FILE: gen/com/goide/psi/GoContinueStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoContinueStatement extends GoStatement { @Nullable GoLabelRef getLabelRef(); @NotNull PsiElement getContinue(); } ================================================ FILE: gen/com/goide/psi/GoConversionExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoConversionExpr extends GoBinaryExpr { @Nullable GoExpression getExpression(); @NotNull GoType getType(); @Nullable PsiElement getComma(); @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); } ================================================ FILE: gen/com/goide/psi/GoDeferStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoDeferStatement extends GoStatement { @Nullable GoExpression getExpression(); @NotNull PsiElement getDefer(); } ================================================ FILE: gen/com/goide/psi/GoElement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoElement extends GoCompositeElement { @Nullable GoKey getKey(); @Nullable GoValue getValue(); @Nullable PsiElement getColon(); } ================================================ FILE: gen/com/goide/psi/GoElseStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoElseStatement extends GoStatement { @Nullable GoIfStatement getIfStatement(); @NotNull PsiElement getElse(); } ================================================ FILE: gen/com/goide/psi/GoExprCaseClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoExprCaseClause extends GoCaseClause { @NotNull List getExpressionList(); @NotNull List getStatementList(); @Nullable PsiElement getColon(); @Nullable PsiElement getCase(); @Nullable PsiElement getDefault(); } ================================================ FILE: gen/com/goide/psi/GoExprSwitchStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoExprSwitchStatement extends GoSwitchStatement { @NotNull List getExprCaseClauseList(); @Nullable GoExpression getExpression(); @Nullable GoStatement getStatement(); @NotNull GoSwitchStart getSwitchStart(); @NotNull PsiElement getLbrace(); @Nullable PsiElement getRbrace(); @Nullable PsiElement getSemicolon(); } ================================================ FILE: gen/com/goide/psi/GoExpression.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; public interface GoExpression extends GoTypeOwner { @Nullable GoType getGoType(ResolveState context); } ================================================ FILE: gen/com/goide/psi/GoFallthroughStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoFallthroughStatement extends GoStatement { @NotNull PsiElement getFallthrough(); } ================================================ FILE: gen/com/goide/psi/GoFieldDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoFieldDeclaration extends GoCompositeElement { @Nullable GoAnonymousFieldDefinition getAnonymousFieldDefinition(); @NotNull List getFieldDefinitionList(); @Nullable GoTag getTag(); @Nullable GoType getType(); } ================================================ FILE: gen/com/goide/psi/GoFieldDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoFieldDefinitionStub; public interface GoFieldDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull PsiElement getIdentifier(); } ================================================ FILE: gen/com/goide/psi/GoFieldName.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; public interface GoFieldName extends GoReferenceExpressionBase { @NotNull PsiElement getIdentifier(); @NotNull PsiReference getReference(); @Nullable GoReferenceExpression getQualifier(); @Nullable PsiElement resolve(); } ================================================ FILE: gen/com/goide/psi/GoForClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public interface GoForClause extends GoCompositeElement { @Nullable GoExpression getExpression(); @NotNull List getStatementList(); boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place); } ================================================ FILE: gen/com/goide/psi/GoForStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoForStatement extends GoStatement { @Nullable GoExpression getExpression(); @Nullable GoForClause getForClause(); @Nullable GoRangeClause getRangeClause(); @NotNull PsiElement getFor(); } ================================================ FILE: gen/com/goide/psi/GoFunctionDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoFunctionDeclarationStub; public interface GoFunctionDeclaration extends GoFunctionOrMethodDeclaration, StubBasedPsiElement { @Nullable GoBlock getBlock(); @Nullable GoSignature getSignature(); @NotNull PsiElement getFunc(); @NotNull PsiElement getIdentifier(); } ================================================ FILE: gen/com/goide/psi/GoFunctionLit.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public interface GoFunctionLit extends GoExpression, GoSignatureOwner { @Nullable GoBlock getBlock(); @Nullable GoSignature getSignature(); @NotNull PsiElement getFunc(); boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place); } ================================================ FILE: gen/com/goide/psi/GoFunctionType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoFunctionType extends GoType, GoSignatureOwner { @Nullable GoSignature getSignature(); @NotNull PsiElement getFunc(); } ================================================ FILE: gen/com/goide/psi/GoGoStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoGoStatement extends GoStatement { @Nullable GoExpression getExpression(); @NotNull PsiElement getGo(); } ================================================ FILE: gen/com/goide/psi/GoGotoStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoGotoStatement extends GoStatement { @Nullable GoLabelRef getLabelRef(); @NotNull PsiElement getGoto(); } ================================================ FILE: gen/com/goide/psi/GoIfStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoIfStatement extends GoStatement { @Nullable GoElseStatement getElseStatement(); @Nullable GoExpression getExpression(); @Nullable GoStatement getStatement(); @Nullable PsiElement getSemicolon(); @NotNull PsiElement getIf(); } ================================================ FILE: gen/com/goide/psi/GoImportDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoImportDeclaration extends GoCompositeElement { @NotNull List getImportSpecList(); @Nullable PsiElement getLparen(); @Nullable PsiElement getRparen(); @NotNull PsiElement getImport(); @NotNull GoImportSpec addImportSpec(String packagePath, String alias); } ================================================ FILE: gen/com/goide/psi/GoImportList.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoImportList extends GoCompositeElement { @NotNull List getImportDeclarationList(); @NotNull GoImportSpec addImport(String packagePath, String alias); } ================================================ FILE: gen/com/goide/psi/GoImportSpec.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoImportSpecStub; public interface GoImportSpec extends GoNamedElement, StubBasedPsiElement { @NotNull GoImportString getImportString(); @Nullable PsiElement getDot(); @Nullable PsiElement getIdentifier(); String getAlias(); String getLocalPackageName(); boolean shouldGoDeeper(); boolean isForSideEffects(); boolean isDot(); @NotNull String getPath(); String getName(); boolean isCImport(); } ================================================ FILE: gen/com/goide/psi/GoImportString.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiReference; public interface GoImportString extends GoCompositeElement { @NotNull GoStringLiteral getStringLiteral(); @NotNull PsiReference[] getReferences(); @Nullable PsiDirectory resolve(); @NotNull String getPath(); @NotNull TextRange getPathTextRange(); } ================================================ FILE: gen/com/goide/psi/GoIncDecStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoIncDecStatement extends GoStatement { @NotNull GoExpression getExpression(); @Nullable PsiElement getMinusMinus(); @Nullable PsiElement getPlusPlus(); } ================================================ FILE: gen/com/goide/psi/GoIndexOrSliceExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.openapi.util.Trinity; public interface GoIndexOrSliceExpr extends GoExpression { @NotNull List getExpressionList(); @NotNull PsiElement getLbrack(); @Nullable PsiElement getRbrack(); @Nullable GoExpression getExpression(); @NotNull Trinity getIndices(); } ================================================ FILE: gen/com/goide/psi/GoInterfaceType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoInterfaceType extends GoType { @NotNull List getMethodSpecList(); @Nullable PsiElement getLbrace(); @Nullable PsiElement getRbrace(); @NotNull PsiElement getInterface(); @NotNull List getMethods(); @NotNull List getBaseTypesReferences(); } ================================================ FILE: gen/com/goide/psi/GoKey.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoKey extends GoCompositeElement { @Nullable GoExpression getExpression(); @Nullable GoFieldName getFieldName(); } ================================================ FILE: gen/com/goide/psi/GoLabelDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoLabelDefinitionStub; public interface GoLabelDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull PsiElement getIdentifier(); } ================================================ FILE: gen/com/goide/psi/GoLabelRef.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; public interface GoLabelRef extends GoCompositeElement { @NotNull PsiElement getIdentifier(); @NotNull PsiReference getReference(); } ================================================ FILE: gen/com/goide/psi/GoLabeledStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoLabeledStatement extends GoStatement { @NotNull GoLabelDefinition getLabelDefinition(); @Nullable GoStatement getStatement(); @NotNull PsiElement getColon(); } ================================================ FILE: gen/com/goide/psi/GoLeftHandExprList.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoLeftHandExprList extends GoCompositeElement { @NotNull List getExpressionList(); } ================================================ FILE: gen/com/goide/psi/GoLiteral.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoLiteral extends GoExpression { @Nullable PsiElement getChar(); @Nullable PsiElement getDecimali(); @Nullable PsiElement getFloat(); @Nullable PsiElement getFloati(); @Nullable PsiElement getHex(); @Nullable PsiElement getInt(); @Nullable PsiElement getOct(); } ================================================ FILE: gen/com/goide/psi/GoLiteralTypeExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoLiteralTypeExpr extends GoExpression { @Nullable GoType getType(); @Nullable GoTypeReferenceExpression getTypeReferenceExpression(); } ================================================ FILE: gen/com/goide/psi/GoLiteralValue.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoLiteralValue extends GoCompositeElement { @NotNull List getElementList(); @NotNull PsiElement getLbrace(); @Nullable PsiElement getRbrace(); } ================================================ FILE: gen/com/goide/psi/GoMapType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoMapType extends GoType { @NotNull List getTypeList(); @Nullable PsiElement getLbrack(); @Nullable PsiElement getRbrack(); @NotNull PsiElement getMap(); @Nullable GoType getKeyType(); @Nullable GoType getValueType(); } ================================================ FILE: gen/com/goide/psi/GoMethodDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoMethodDeclarationStub; public interface GoMethodDeclaration extends GoFunctionOrMethodDeclaration, StubBasedPsiElement { @Nullable GoBlock getBlock(); @Nullable GoReceiver getReceiver(); @Nullable GoSignature getSignature(); @NotNull PsiElement getFunc(); @Nullable PsiElement getIdentifier(); @Nullable GoType getReceiverType(); } ================================================ FILE: gen/com/goide/psi/GoMethodSpec.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoMethodSpecStub; import com.intellij.psi.ResolveState; public interface GoMethodSpec extends GoNamedSignatureOwner, StubBasedPsiElement { @Nullable GoSignature getSignature(); @Nullable GoTypeReferenceExpression getTypeReferenceExpression(); @Nullable PsiElement getIdentifier(); @Nullable GoType getGoTypeInner(ResolveState context); @Nullable String getName(); } ================================================ FILE: gen/com/goide/psi/GoMulExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoMulExpr extends GoBinaryExpr { @Nullable PsiElement getBitAnd(); @Nullable PsiElement getBitClear(); @Nullable PsiElement getMul(); @Nullable PsiElement getQuotient(); @Nullable PsiElement getRemainder(); @Nullable PsiElement getShiftLeft(); @Nullable PsiElement getShiftRight(); } ================================================ FILE: gen/com/goide/psi/GoOrExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoOrExpr extends GoBinaryExpr { @NotNull PsiElement getCondOr(); } ================================================ FILE: gen/com/goide/psi/GoPackageClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoPackageClauseStub; public interface GoPackageClause extends GoCompositeElement, StubBasedPsiElement { @Nullable PsiElement getIdentifier(); @NotNull PsiElement getPackage(); @Nullable String getName(); } ================================================ FILE: gen/com/goide/psi/GoParType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoParType extends GoType { @NotNull GoType getType(); @NotNull PsiElement getLparen(); @NotNull PsiElement getRparen(); @NotNull GoType getActualType(); } ================================================ FILE: gen/com/goide/psi/GoParamDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoParamDefinitionStub; public interface GoParamDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull PsiElement getIdentifier(); boolean isVariadic(); } ================================================ FILE: gen/com/goide/psi/GoParameterDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoParameterDeclarationStub; public interface GoParameterDeclaration extends GoCompositeElement, StubBasedPsiElement { @NotNull List getParamDefinitionList(); @NotNull GoType getType(); @Nullable PsiElement getTripleDot(); boolean isVariadic(); } ================================================ FILE: gen/com/goide/psi/GoParameters.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoParametersStub; public interface GoParameters extends GoCompositeElement, StubBasedPsiElement { @NotNull List getParameterDeclarationList(); @Nullable GoType getType(); @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); } ================================================ FILE: gen/com/goide/psi/GoParenthesesExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoParenthesesExpr extends GoExpression { @Nullable GoExpression getExpression(); @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); } ================================================ FILE: gen/com/goide/psi/GoPointerType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoPointerType extends GoType { @Nullable GoType getType(); @NotNull PsiElement getMul(); } ================================================ FILE: gen/com/goide/psi/GoRangeClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoRangeClause extends GoVarSpec { @NotNull List getVarDefinitionList(); @Nullable PsiElement getVarAssign(); @Nullable PsiElement getRange(); @Nullable GoExpression getRangeExpression(); @NotNull List getLeftExpressionsList(); @NotNull List getRightExpressionsList(); } ================================================ FILE: gen/com/goide/psi/GoReceiver.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoReceiverStub; import com.intellij.psi.ResolveState; public interface GoReceiver extends GoNamedElement, StubBasedPsiElement { @Nullable GoType getType(); @Nullable PsiElement getComma(); @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); @Nullable PsiElement getIdentifier(); @Nullable GoType getGoTypeInner(ResolveState context); } ================================================ FILE: gen/com/goide/psi/GoRecvStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoRecvStatement extends GoVarSpec { @NotNull List getExpressionList(); @NotNull List getVarDefinitionList(); @Nullable PsiElement getVarAssign(); @Nullable GoExpression getRecvExpression(); @NotNull List getLeftExpressionsList(); @NotNull List getRightExpressionsList(); } ================================================ FILE: gen/com/goide/psi/GoReferenceExpression.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.goide.psi.impl.GoReference; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access; public interface GoReferenceExpression extends GoExpression, GoReferenceExpressionBase { @NotNull PsiElement getIdentifier(); @NotNull GoReference getReference(); @Nullable GoReferenceExpression getQualifier(); @Nullable PsiElement resolve(); @NotNull Access getReadWriteAccess(); } ================================================ FILE: gen/com/goide/psi/GoResult.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoResultStub; public interface GoResult extends GoCompositeElement, StubBasedPsiElement { @Nullable GoParameters getParameters(); @Nullable GoType getType(); @Nullable PsiElement getLparen(); @Nullable PsiElement getRparen(); boolean isVoid(); } ================================================ FILE: gen/com/goide/psi/GoReturnStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoReturnStatement extends GoStatement { @NotNull List getExpressionList(); @NotNull PsiElement getReturn(); } ================================================ FILE: gen/com/goide/psi/GoSelectStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSelectStatement extends GoStatement { @NotNull List getCommClauseList(); @Nullable PsiElement getLbrace(); @Nullable PsiElement getRbrace(); @NotNull PsiElement getSelect(); } ================================================ FILE: gen/com/goide/psi/GoSelectorExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSelectorExpr extends GoBinaryExpr { @NotNull PsiElement getDot(); } ================================================ FILE: gen/com/goide/psi/GoSendStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSendStatement extends GoStatement { @NotNull List getExpressionList(); @Nullable GoLeftHandExprList getLeftHandExprList(); @NotNull PsiElement getSendChannel(); @Nullable GoExpression getSendExpression(); } ================================================ FILE: gen/com/goide/psi/GoShortVarDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoShortVarDeclaration extends GoVarSpec { @NotNull PsiElement getVarAssign(); } ================================================ FILE: gen/com/goide/psi/GoSignature.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoSignatureStub; public interface GoSignature extends GoCompositeElement, StubBasedPsiElement { @NotNull GoParameters getParameters(); @Nullable GoResult getResult(); } ================================================ FILE: gen/com/goide/psi/GoSimpleStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSimpleStatement extends GoStatement { @Nullable GoLeftHandExprList getLeftHandExprList(); @Nullable GoShortVarDeclaration getShortVarDeclaration(); @Nullable GoStatement getStatement(); } ================================================ FILE: gen/com/goide/psi/GoSpecType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoTypeStub; public interface GoSpecType extends GoType, StubBasedPsiElement { @Nullable GoType getType(); @NotNull PsiElement getIdentifier(); } ================================================ FILE: gen/com/goide/psi/GoStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public interface GoStatement extends GoCompositeElement { @Nullable GoBlock getBlock(); @Nullable GoConstDeclaration getConstDeclaration(); @Nullable GoTypeDeclaration getTypeDeclaration(); @Nullable GoVarDeclaration getVarDeclaration(); boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place); } ================================================ FILE: gen/com/goide/psi/GoStringLiteral.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.goide.psi.impl.GoStringLiteralImpl; import com.goide.util.GoStringLiteralEscaper; public interface GoStringLiteral extends GoExpression, PsiLanguageInjectionHost { @Nullable PsiElement getRawString(); @Nullable PsiElement getString(); boolean isValidHost(); @NotNull GoStringLiteralImpl updateText(String text); @NotNull GoStringLiteralEscaper createLiteralTextEscaper(); @NotNull String getDecodedText(); } ================================================ FILE: gen/com/goide/psi/GoStructType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoStructType extends GoType { @NotNull List getFieldDeclarationList(); @Nullable PsiElement getLbrace(); @Nullable PsiElement getRbrace(); @NotNull PsiElement getStruct(); } ================================================ FILE: gen/com/goide/psi/GoSwitchStart.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSwitchStart extends GoCompositeElement { @NotNull PsiElement getSwitch(); } ================================================ FILE: gen/com/goide/psi/GoSwitchStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoSwitchStatement extends GoStatement { @Nullable GoSwitchStart getSwitchStart(); @Nullable GoSwitchStatement getSwitchStatement(); } ================================================ FILE: gen/com/goide/psi/GoTag.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTag extends GoCompositeElement { @NotNull GoStringLiteral getStringLiteral(); } ================================================ FILE: gen/com/goide/psi/GoType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoTypeStub; public interface GoType extends GoCompositeElement, StubBasedPsiElement { @Nullable GoTypeReferenceExpression getTypeReferenceExpression(); @NotNull GoType getUnderlyingType(); boolean shouldGoDeeper(); } ================================================ FILE: gen/com/goide/psi/GoTypeAssertionExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeAssertionExpr extends GoExpression { @NotNull GoExpression getExpression(); @NotNull GoType getType(); @NotNull PsiElement getDot(); @NotNull PsiElement getLparen(); @NotNull PsiElement getRparen(); } ================================================ FILE: gen/com/goide/psi/GoTypeCaseClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeCaseClause extends GoCaseClause { @NotNull List getStatementList(); @Nullable GoType getType(); @Nullable PsiElement getColon(); @Nullable PsiElement getCase(); @Nullable PsiElement getDefault(); } ================================================ FILE: gen/com/goide/psi/GoTypeDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeDeclaration extends GoTopLevelDeclaration { @NotNull List getTypeSpecList(); @Nullable PsiElement getLparen(); @Nullable PsiElement getRparen(); @NotNull PsiElement getType_(); } ================================================ FILE: gen/com/goide/psi/GoTypeGuard.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeGuard extends GoCompositeElement { @NotNull PsiElement getLparen(); @Nullable PsiElement getRparen(); @NotNull PsiElement getType_(); } ================================================ FILE: gen/com/goide/psi/GoTypeList.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeList extends GoType { @NotNull List getTypeList(); } ================================================ FILE: gen/com/goide/psi/GoTypeReferenceExpression.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; public interface GoTypeReferenceExpression extends GoReferenceExpressionBase { @NotNull PsiElement getIdentifier(); @NotNull PsiReference getReference(); @Nullable GoTypeReferenceExpression getQualifier(); @Nullable PsiElement resolve(); @Nullable GoType resolveType(); } ================================================ FILE: gen/com/goide/psi/GoTypeSpec.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoTypeSpecStub; import com.intellij.psi.ResolveState; public interface GoTypeSpec extends GoNamedElement, StubBasedPsiElement { @NotNull GoSpecType getSpecType(); @Nullable GoType getGoTypeInner(ResolveState context); @NotNull List getMethods(); boolean shouldGoDeeper(); @NotNull PsiElement getIdentifier(); } ================================================ FILE: gen/com/goide/psi/GoTypeSwitchGuard.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeSwitchGuard extends GoCompositeElement { @NotNull GoExpression getExpression(); @NotNull GoTypeGuard getTypeGuard(); @Nullable GoVarDefinition getVarDefinition(); @NotNull PsiElement getDot(); @Nullable PsiElement getVarAssign(); } ================================================ FILE: gen/com/goide/psi/GoTypeSwitchStatement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoTypeSwitchStatement extends GoSwitchStatement { @Nullable GoStatement getStatement(); @NotNull GoSwitchStart getSwitchStart(); @NotNull List getTypeCaseClauseList(); @NotNull GoTypeSwitchGuard getTypeSwitchGuard(); @Nullable PsiElement getLbrace(); @Nullable PsiElement getRbrace(); @Nullable PsiElement getSemicolon(); } ================================================ FILE: gen/com/goide/psi/GoUnaryExpr.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoUnaryExpr extends GoExpression { @Nullable GoExpression getExpression(); @Nullable PsiElement getBitAnd(); @Nullable PsiElement getBitXor(); @Nullable PsiElement getMinus(); @Nullable PsiElement getMul(); @Nullable PsiElement getNot(); @Nullable PsiElement getPlus(); @Nullable PsiElement getSendChannel(); @Nullable PsiElement getOperator(); } ================================================ FILE: gen/com/goide/psi/GoValue.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoValue extends GoCompositeElement { @Nullable GoExpression getExpression(); @Nullable GoLiteralValue getLiteralValue(); } ================================================ FILE: gen/com/goide/psi/GoVarDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoVarDeclaration extends GoTopLevelDeclaration { @NotNull List getVarSpecList(); @Nullable PsiElement getLparen(); @Nullable PsiElement getRparen(); @NotNull PsiElement getVar(); @NotNull GoVarSpec addSpec(String name, String type, String value, GoVarSpec specAnchor); void deleteSpec(GoVarSpec specToDelete); } ================================================ FILE: gen/com/goide/psi/GoVarDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoVarDefinitionStub; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveState; public interface GoVarDefinition extends GoNamedElement, StubBasedPsiElement { @NotNull PsiElement getIdentifier(); @Nullable GoType getGoTypeInner(ResolveState context); @Nullable PsiReference getReference(); @Nullable GoExpression getValue(); } ================================================ FILE: gen/com/goide/psi/GoVarSpec.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.intellij.psi.StubBasedPsiElement; import com.goide.stubs.GoVarSpecStub; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public interface GoVarSpec extends GoCompositeElement, StubBasedPsiElement { @NotNull List getExpressionList(); @Nullable GoType getType(); @NotNull List getVarDefinitionList(); @Nullable PsiElement getAssign(); boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place); void deleteDefinition(GoVarDefinition definitionToDelete); @NotNull List getRightExpressionsList(); } ================================================ FILE: gen/com/goide/psi/GoVisitor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiLanguageInjectionHost; public class GoVisitor extends PsiElementVisitor { public void visitAddExpr(@NotNull GoAddExpr o) { visitBinaryExpr(o); } public void visitAndExpr(@NotNull GoAndExpr o) { visitBinaryExpr(o); } public void visitAnonymousFieldDefinition(@NotNull GoAnonymousFieldDefinition o) { visitNamedElement(o); } public void visitArgumentList(@NotNull GoArgumentList o) { visitCompositeElement(o); } public void visitArrayOrSliceType(@NotNull GoArrayOrSliceType o) { visitType(o); } public void visitAssignmentStatement(@NotNull GoAssignmentStatement o) { visitStatement(o); } public void visitBinaryExpr(@NotNull GoBinaryExpr o) { visitExpression(o); } public void visitBlock(@NotNull GoBlock o) { visitCompositeElement(o); } public void visitBreakStatement(@NotNull GoBreakStatement o) { visitStatement(o); } public void visitBuiltinArgumentList(@NotNull GoBuiltinArgumentList o) { visitArgumentList(o); } public void visitBuiltinCallExpr(@NotNull GoBuiltinCallExpr o) { visitExpression(o); } public void visitCallExpr(@NotNull GoCallExpr o) { visitExpression(o); } public void visitChannelType(@NotNull GoChannelType o) { visitType(o); } public void visitCommCase(@NotNull GoCommCase o) { visitCompositeElement(o); } public void visitCommClause(@NotNull GoCommClause o) { visitCompositeElement(o); } public void visitCompositeLit(@NotNull GoCompositeLit o) { visitExpression(o); } public void visitConditionalExpr(@NotNull GoConditionalExpr o) { visitBinaryExpr(o); } public void visitConstDeclaration(@NotNull GoConstDeclaration o) { visitTopLevelDeclaration(o); } public void visitConstDefinition(@NotNull GoConstDefinition o) { visitNamedElement(o); } public void visitConstSpec(@NotNull GoConstSpec o) { visitCompositeElement(o); } public void visitContinueStatement(@NotNull GoContinueStatement o) { visitStatement(o); } public void visitConversionExpr(@NotNull GoConversionExpr o) { visitBinaryExpr(o); } public void visitDeferStatement(@NotNull GoDeferStatement o) { visitStatement(o); } public void visitElement(@NotNull GoElement o) { visitCompositeElement(o); } public void visitElseStatement(@NotNull GoElseStatement o) { visitStatement(o); } public void visitExprCaseClause(@NotNull GoExprCaseClause o) { visitCaseClause(o); } public void visitExprSwitchStatement(@NotNull GoExprSwitchStatement o) { visitSwitchStatement(o); } public void visitExpression(@NotNull GoExpression o) { visitTypeOwner(o); } public void visitFallthroughStatement(@NotNull GoFallthroughStatement o) { visitStatement(o); } public void visitFieldDeclaration(@NotNull GoFieldDeclaration o) { visitCompositeElement(o); } public void visitFieldDefinition(@NotNull GoFieldDefinition o) { visitNamedElement(o); } public void visitFieldName(@NotNull GoFieldName o) { visitReferenceExpressionBase(o); } public void visitForClause(@NotNull GoForClause o) { visitCompositeElement(o); } public void visitForStatement(@NotNull GoForStatement o) { visitStatement(o); } public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { visitFunctionOrMethodDeclaration(o); } public void visitFunctionLit(@NotNull GoFunctionLit o) { visitExpression(o); // visitSignatureOwner(o); } public void visitFunctionType(@NotNull GoFunctionType o) { visitType(o); // visitSignatureOwner(o); } public void visitGoStatement(@NotNull GoGoStatement o) { visitStatement(o); } public void visitGotoStatement(@NotNull GoGotoStatement o) { visitStatement(o); } public void visitIfStatement(@NotNull GoIfStatement o) { visitStatement(o); } public void visitImportDeclaration(@NotNull GoImportDeclaration o) { visitCompositeElement(o); } public void visitImportList(@NotNull GoImportList o) { visitCompositeElement(o); } public void visitImportSpec(@NotNull GoImportSpec o) { visitNamedElement(o); } public void visitImportString(@NotNull GoImportString o) { visitCompositeElement(o); } public void visitIncDecStatement(@NotNull GoIncDecStatement o) { visitStatement(o); } public void visitIndexOrSliceExpr(@NotNull GoIndexOrSliceExpr o) { visitExpression(o); } public void visitInterfaceType(@NotNull GoInterfaceType o) { visitType(o); } public void visitKey(@NotNull GoKey o) { visitCompositeElement(o); } public void visitLabelDefinition(@NotNull GoLabelDefinition o) { visitNamedElement(o); } public void visitLabelRef(@NotNull GoLabelRef o) { visitCompositeElement(o); } public void visitLabeledStatement(@NotNull GoLabeledStatement o) { visitStatement(o); } public void visitLeftHandExprList(@NotNull GoLeftHandExprList o) { visitCompositeElement(o); } public void visitLiteral(@NotNull GoLiteral o) { visitExpression(o); } public void visitLiteralTypeExpr(@NotNull GoLiteralTypeExpr o) { visitExpression(o); } public void visitLiteralValue(@NotNull GoLiteralValue o) { visitCompositeElement(o); } public void visitMapType(@NotNull GoMapType o) { visitType(o); } public void visitMethodDeclaration(@NotNull GoMethodDeclaration o) { visitFunctionOrMethodDeclaration(o); } public void visitMethodSpec(@NotNull GoMethodSpec o) { visitNamedSignatureOwner(o); } public void visitMulExpr(@NotNull GoMulExpr o) { visitBinaryExpr(o); } public void visitOrExpr(@NotNull GoOrExpr o) { visitBinaryExpr(o); } public void visitPackageClause(@NotNull GoPackageClause o) { visitCompositeElement(o); } public void visitParType(@NotNull GoParType o) { visitType(o); } public void visitParamDefinition(@NotNull GoParamDefinition o) { visitNamedElement(o); } public void visitParameterDeclaration(@NotNull GoParameterDeclaration o) { visitCompositeElement(o); } public void visitParameters(@NotNull GoParameters o) { visitCompositeElement(o); } public void visitParenthesesExpr(@NotNull GoParenthesesExpr o) { visitExpression(o); } public void visitPointerType(@NotNull GoPointerType o) { visitType(o); } public void visitRangeClause(@NotNull GoRangeClause o) { visitVarSpec(o); } public void visitReceiver(@NotNull GoReceiver o) { visitNamedElement(o); } public void visitRecvStatement(@NotNull GoRecvStatement o) { visitVarSpec(o); } public void visitReferenceExpression(@NotNull GoReferenceExpression o) { visitExpression(o); // visitReferenceExpressionBase(o); } public void visitResult(@NotNull GoResult o) { visitCompositeElement(o); } public void visitReturnStatement(@NotNull GoReturnStatement o) { visitStatement(o); } public void visitSelectStatement(@NotNull GoSelectStatement o) { visitStatement(o); } public void visitSelectorExpr(@NotNull GoSelectorExpr o) { visitBinaryExpr(o); } public void visitSendStatement(@NotNull GoSendStatement o) { visitStatement(o); } public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { visitVarSpec(o); } public void visitSignature(@NotNull GoSignature o) { visitCompositeElement(o); } public void visitSimpleStatement(@NotNull GoSimpleStatement o) { visitStatement(o); } public void visitSpecType(@NotNull GoSpecType o) { visitType(o); } public void visitStatement(@NotNull GoStatement o) { visitCompositeElement(o); } public void visitStringLiteral(@NotNull GoStringLiteral o) { visitExpression(o); // visitPsiLanguageInjectionHost(o); } public void visitStructType(@NotNull GoStructType o) { visitType(o); } public void visitSwitchStart(@NotNull GoSwitchStart o) { visitCompositeElement(o); } public void visitSwitchStatement(@NotNull GoSwitchStatement o) { visitStatement(o); } public void visitTag(@NotNull GoTag o) { visitCompositeElement(o); } public void visitType(@NotNull GoType o) { visitCompositeElement(o); } public void visitTypeAssertionExpr(@NotNull GoTypeAssertionExpr o) { visitExpression(o); } public void visitTypeCaseClause(@NotNull GoTypeCaseClause o) { visitCaseClause(o); } public void visitTypeDeclaration(@NotNull GoTypeDeclaration o) { visitTopLevelDeclaration(o); } public void visitTypeGuard(@NotNull GoTypeGuard o) { visitCompositeElement(o); } public void visitTypeList(@NotNull GoTypeList o) { visitType(o); } public void visitTypeReferenceExpression(@NotNull GoTypeReferenceExpression o) { visitReferenceExpressionBase(o); } public void visitTypeSpec(@NotNull GoTypeSpec o) { visitNamedElement(o); } public void visitTypeSwitchGuard(@NotNull GoTypeSwitchGuard o) { visitCompositeElement(o); } public void visitTypeSwitchStatement(@NotNull GoTypeSwitchStatement o) { visitSwitchStatement(o); } public void visitUnaryExpr(@NotNull GoUnaryExpr o) { visitExpression(o); } public void visitValue(@NotNull GoValue o) { visitCompositeElement(o); } public void visitVarDeclaration(@NotNull GoVarDeclaration o) { visitTopLevelDeclaration(o); } public void visitVarDefinition(@NotNull GoVarDefinition o) { visitNamedElement(o); } public void visitVarSpec(@NotNull GoVarSpec o) { visitCompositeElement(o); } public void visitAssignOp(@NotNull GoAssignOp o) { visitCompositeElement(o); } public void visitCaseClause(@NotNull GoCaseClause o) { visitCompositeElement(o); } public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { visitCompositeElement(o); } public void visitNamedElement(@NotNull GoNamedElement o) { visitCompositeElement(o); } public void visitNamedSignatureOwner(@NotNull GoNamedSignatureOwner o) { visitCompositeElement(o); } public void visitReferenceExpressionBase(@NotNull GoReferenceExpressionBase o) { visitCompositeElement(o); } public void visitTopLevelDeclaration(@NotNull GoTopLevelDeclaration o) { visitCompositeElement(o); } public void visitTypeOwner(@NotNull GoTypeOwner o) { visitCompositeElement(o); } public void visitCompositeElement(@NotNull GoCompositeElement o) { visitElement(o); } } ================================================ FILE: gen/com/goide/psi/impl/GoAddExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoAddExprImpl extends GoBinaryExprImpl implements GoAddExpr { public GoAddExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitAddExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getBitOr() { return findChildByType(BIT_OR); } @Override @Nullable public PsiElement getBitXor() { return findChildByType(BIT_XOR); } @Override @Nullable public PsiElement getMinus() { return findChildByType(MINUS); } @Override @Nullable public PsiElement getPlus() { return findChildByType(PLUS); } } ================================================ FILE: gen/com/goide/psi/impl/GoAndExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoAndExprImpl extends GoBinaryExprImpl implements GoAndExpr { public GoAndExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitAndExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getCondAnd() { return notNullChild(findChildByType(COND_AND)); } } ================================================ FILE: gen/com/goide/psi/impl/GoAnonymousFieldDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoAnonymousFieldDefinitionStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoAnonymousFieldDefinitionImpl extends GoNamedElementImpl implements GoAnonymousFieldDefinition { public GoAnonymousFieldDefinitionImpl(GoAnonymousFieldDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoAnonymousFieldDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitAnonymousFieldDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoType getType() { return notNullChild(GoPsiTreeUtil.getStubChildOfType(this, GoType.class)); } @Nullable public PsiElement getIdentifier() { return GoPsiImplUtil.getIdentifier(this); } @Nullable public String getName() { return GoPsiImplUtil.getName(this); } @Nullable public GoTypeReferenceExpression getTypeReferenceExpression() { return GoPsiImplUtil.getTypeReferenceExpression(this); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } } ================================================ FILE: gen/com/goide/psi/impl/GoArgumentListImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoArgumentListImpl extends GoCompositeElementImpl implements GoArgumentList { public GoArgumentListImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitArgumentList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @Nullable public PsiElement getTripleDot() { return findChildByType(TRIPLE_DOT); } } ================================================ FILE: gen/com/goide/psi/impl/GoArrayOrSliceTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoArrayOrSliceTypeImpl extends GoTypeImpl implements GoArrayOrSliceType { public GoArrayOrSliceTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoArrayOrSliceTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitArrayOrSliceType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @NotNull public PsiElement getLbrack() { return notNullChild(findChildByType(LBRACK)); } @Override @Nullable public PsiElement getRbrack() { return findChildByType(RBRACK); } @Override @Nullable public PsiElement getTripleDot() { return findChildByType(TRIPLE_DOT); } } ================================================ FILE: gen/com/goide/psi/impl/GoAssignOpImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoAssignOpImpl extends GoCompositeElementImpl implements GoAssignOp { public GoAssignOpImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitAssignOp(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getAssign() { return findChildByType(ASSIGN); } @Override @Nullable public PsiElement getBitAndAssign() { return findChildByType(BIT_AND_ASSIGN); } @Override @Nullable public PsiElement getBitClearAssign() { return findChildByType(BIT_CLEAR_ASSIGN); } @Override @Nullable public PsiElement getBitOrAssign() { return findChildByType(BIT_OR_ASSIGN); } @Override @Nullable public PsiElement getBitXorAssign() { return findChildByType(BIT_XOR_ASSIGN); } @Override @Nullable public PsiElement getMinusAssign() { return findChildByType(MINUS_ASSIGN); } @Override @Nullable public PsiElement getMulAssign() { return findChildByType(MUL_ASSIGN); } @Override @Nullable public PsiElement getPlusAssign() { return findChildByType(PLUS_ASSIGN); } @Override @Nullable public PsiElement getQuotientAssign() { return findChildByType(QUOTIENT_ASSIGN); } @Override @Nullable public PsiElement getRemainderAssign() { return findChildByType(REMAINDER_ASSIGN); } @Override @Nullable public PsiElement getShiftLeftAssign() { return findChildByType(SHIFT_LEFT_ASSIGN); } @Override @Nullable public PsiElement getShiftRightAssign() { return findChildByType(SHIFT_RIGHT_ASSIGN); } } ================================================ FILE: gen/com/goide/psi/impl/GoAssignmentStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoAssignmentStatementImpl extends GoStatementImpl implements GoAssignmentStatement { public GoAssignmentStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitAssignmentStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public GoLeftHandExprList getLeftHandExprList() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoLeftHandExprList.class)); } @Override @NotNull public GoAssignOp getAssignOp() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoAssignOp.class)); } } ================================================ FILE: gen/com/goide/psi/impl/GoBinaryExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoBinaryExprImpl extends GoExpressionImpl implements GoBinaryExpr { public GoBinaryExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitBinaryExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public GoExpression getLeft() { List p1 = getExpressionList(); return p1.get(0); } @Override @Nullable public GoExpression getRight() { List p1 = getExpressionList(); return p1.size() < 2 ? null : p1.get(1); } @Nullable public PsiElement getOperator() { return GoPsiImplUtil.getOperator(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoBlockImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public class GoBlockImpl extends GoCompositeElementImpl implements GoBlock { public GoBlockImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitBlock(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getStatementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoStatement.class); } @Override @NotNull public PsiElement getLbrace() { return notNullChild(findChildByType(LBRACE)); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } public boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) { return GoPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } } ================================================ FILE: gen/com/goide/psi/impl/GoBreakStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoBreakStatementImpl extends GoStatementImpl implements GoBreakStatement { public GoBreakStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitBreakStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLabelRef getLabelRef() { return GoPsiTreeUtil.getChildOfType(this, GoLabelRef.class); } @Override @NotNull public PsiElement getBreak() { return notNullChild(findChildByType(BREAK)); } } ================================================ FILE: gen/com/goide/psi/impl/GoBuiltinArgumentListImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoBuiltinArgumentListImpl extends GoArgumentListImpl implements GoBuiltinArgumentList { public GoBuiltinArgumentListImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitBuiltinArgumentList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getChildOfType(this, GoType.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoBuiltinCallExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoBuiltinCallExprImpl extends GoExpressionImpl implements GoBuiltinCallExpr { public GoBuiltinCallExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitBuiltinCallExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoBuiltinArgumentList getBuiltinArgumentList() { return GoPsiTreeUtil.getChildOfType(this, GoBuiltinArgumentList.class); } @Override @NotNull public GoReferenceExpression getReferenceExpression() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoReferenceExpression.class)); } } ================================================ FILE: gen/com/goide/psi/impl/GoCallExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoCallExprImpl extends GoExpressionImpl implements GoCallExpr { public GoCallExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitCallExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoArgumentList getArgumentList() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoArgumentList.class)); } @Override @NotNull public GoExpression getExpression() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoExpression.class)); } } ================================================ FILE: gen/com/goide/psi/impl/GoChannelTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoChannelTypeImpl extends GoTypeImpl implements GoChannelType { public GoChannelTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoChannelTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitChannelType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @Nullable public PsiElement getSendChannel() { return findChildByType(SEND_CHANNEL); } @Override @Nullable public PsiElement getChan() { return findChildByType(CHAN); } } ================================================ FILE: gen/com/goide/psi/impl/GoCommCaseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoCommCaseImpl extends GoCompositeElementImpl implements GoCommCase { public GoCommCaseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitCommCase(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoRecvStatement getRecvStatement() { return GoPsiTreeUtil.getChildOfType(this, GoRecvStatement.class); } @Override @Nullable public GoSendStatement getSendStatement() { return GoPsiTreeUtil.getChildOfType(this, GoSendStatement.class); } @Override @Nullable public PsiElement getCase() { return findChildByType(CASE); } @Override @Nullable public PsiElement getDefault() { return findChildByType(DEFAULT); } } ================================================ FILE: gen/com/goide/psi/impl/GoCommClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoCommClauseImpl extends GoCompositeElementImpl implements GoCommClause { public GoCommClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitCommClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoCommCase getCommCase() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoCommCase.class)); } @Override @NotNull public List getStatementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoStatement.class); } @Override @Nullable public PsiElement getColon() { return findChildByType(COLON); } } ================================================ FILE: gen/com/goide/psi/impl/GoCompositeLitImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoCompositeLitImpl extends GoExpressionImpl implements GoCompositeLit { public GoCompositeLitImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitCompositeLit(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLiteralValue getLiteralValue() { return GoPsiTreeUtil.getChildOfType(this, GoLiteralValue.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getChildOfType(this, GoType.class); } @Override @Nullable public GoTypeReferenceExpression getTypeReferenceExpression() { return GoPsiTreeUtil.getChildOfType(this, GoTypeReferenceExpression.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoConditionalExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoConditionalExprImpl extends GoBinaryExprImpl implements GoConditionalExpr { public GoConditionalExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitConditionalExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getEq() { return findChildByType(EQ); } @Override @Nullable public PsiElement getGreater() { return findChildByType(GREATER); } @Override @Nullable public PsiElement getGreaterOrEqual() { return findChildByType(GREATER_OR_EQUAL); } @Override @Nullable public PsiElement getLess() { return findChildByType(LESS); } @Override @Nullable public PsiElement getLessOrEqual() { return findChildByType(LESS_OR_EQUAL); } @Override @Nullable public PsiElement getNotEq() { return findChildByType(NOT_EQ); } } ================================================ FILE: gen/com/goide/psi/impl/GoConstDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoConstDeclarationImpl extends GoCompositeElementImpl implements GoConstDeclaration { public GoConstDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitConstDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getConstSpecList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoConstSpec.class); } @Override @Nullable public PsiElement getLparen() { return findChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @NotNull public PsiElement getConst() { return notNullChild(findChildByType(CONST)); } @NotNull public GoConstSpec addSpec(String name, String type, String value, GoConstSpec specAnchor) { return GoPsiImplUtil.addSpec(this, name, type, value, specAnchor); } public void deleteSpec(GoConstSpec specToDelete) { GoPsiImplUtil.deleteSpec(this, specToDelete); } } ================================================ FILE: gen/com/goide/psi/impl/GoConstDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoConstDefinitionStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoConstDefinitionImpl extends GoNamedElementImpl implements GoConstDefinition { public GoConstDefinitionImpl(GoConstDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoConstDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitConstDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } @Nullable public GoExpression getValue() { return GoPsiImplUtil.getValue(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoConstSpecImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoConstSpecStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoConstSpecImpl extends GoStubbedElementImpl implements GoConstSpec { public GoConstSpecImpl(GoConstSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoConstSpecImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitConstSpec(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getConstDefinitionList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoConstDefinition.class); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @Nullable public PsiElement getAssign() { return findChildByType(ASSIGN); } public void deleteDefinition(GoConstDefinition definitionToDelete) { GoPsiImplUtil.deleteDefinition(this, definitionToDelete); } } ================================================ FILE: gen/com/goide/psi/impl/GoContinueStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoContinueStatementImpl extends GoStatementImpl implements GoContinueStatement { public GoContinueStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitContinueStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLabelRef getLabelRef() { return GoPsiTreeUtil.getChildOfType(this, GoLabelRef.class); } @Override @NotNull public PsiElement getContinue() { return notNullChild(findChildByType(CONTINUE)); } } ================================================ FILE: gen/com/goide/psi/impl/GoConversionExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoConversionExprImpl extends GoBinaryExprImpl implements GoConversionExpr { public GoConversionExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitConversionExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @NotNull public GoType getType() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoType.class)); } @Override @Nullable public PsiElement getComma() { return findChildByType(COMMA); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } } ================================================ FILE: gen/com/goide/psi/impl/GoDeferStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoDeferStatementImpl extends GoStatementImpl implements GoDeferStatement { public GoDeferStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitDeferStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @NotNull public PsiElement getDefer() { return notNullChild(findChildByType(DEFER)); } } ================================================ FILE: gen/com/goide/psi/impl/GoElementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoElementImpl extends GoCompositeElementImpl implements GoElement { public GoElementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitElement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoKey getKey() { return GoPsiTreeUtil.getChildOfType(this, GoKey.class); } @Override @Nullable public GoValue getValue() { return GoPsiTreeUtil.getChildOfType(this, GoValue.class); } @Override @Nullable public PsiElement getColon() { return findChildByType(COLON); } } ================================================ FILE: gen/com/goide/psi/impl/GoElseStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoElseStatementImpl extends GoStatementImpl implements GoElseStatement { public GoElseStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitElseStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoIfStatement getIfStatement() { return GoPsiTreeUtil.getChildOfType(this, GoIfStatement.class); } @Override @NotNull public PsiElement getElse() { return notNullChild(findChildByType(ELSE)); } } ================================================ FILE: gen/com/goide/psi/impl/GoExprCaseClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoExprCaseClauseImpl extends GoCompositeElementImpl implements GoExprCaseClause { public GoExprCaseClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitExprCaseClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public List getStatementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoStatement.class); } @Override @Nullable public PsiElement getColon() { return findChildByType(COLON); } @Override @Nullable public PsiElement getCase() { return findChildByType(CASE); } @Override @Nullable public PsiElement getDefault() { return findChildByType(DEFAULT); } } ================================================ FILE: gen/com/goide/psi/impl/GoExprSwitchStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoExprSwitchStatementImpl extends GoSwitchStatementImpl implements GoExprSwitchStatement { public GoExprSwitchStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitExprSwitchStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExprCaseClauseList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExprCaseClause.class); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } @Override @NotNull public GoSwitchStart getSwitchStart() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoSwitchStart.class)); } @Override @NotNull public PsiElement getLbrace() { return notNullChild(findChildByType(LBRACE)); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } @Override @Nullable public PsiElement getSemicolon() { return findChildByType(SEMICOLON); } } ================================================ FILE: gen/com/goide/psi/impl/GoExpressionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.ResolveState; public class GoExpressionImpl extends GoCompositeElementImpl implements GoExpression { public GoExpressionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitExpression(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Nullable public GoType getGoType(ResolveState context) { return GoPsiImplUtil.getGoType(this, context); } } ================================================ FILE: gen/com/goide/psi/impl/GoFallthroughStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoFallthroughStatementImpl extends GoStatementImpl implements GoFallthroughStatement { public GoFallthroughStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFallthroughStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getFallthrough() { return notNullChild(findChildByType(FALLTHROUGH)); } } ================================================ FILE: gen/com/goide/psi/impl/GoFieldDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoFieldDeclarationImpl extends GoCompositeElementImpl implements GoFieldDeclaration { public GoFieldDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFieldDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoAnonymousFieldDefinition getAnonymousFieldDefinition() { return GoPsiTreeUtil.getChildOfType(this, GoAnonymousFieldDefinition.class); } @Override @NotNull public List getFieldDefinitionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoFieldDefinition.class); } @Override @Nullable public GoTag getTag() { return GoPsiTreeUtil.getChildOfType(this, GoTag.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getChildOfType(this, GoType.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoFieldDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoFieldDefinitionStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoFieldDefinitionImpl extends GoNamedElementImpl implements GoFieldDefinition { public GoFieldDefinitionImpl(GoFieldDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoFieldDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFieldDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } } ================================================ FILE: gen/com/goide/psi/impl/GoFieldNameImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.PsiReference; public class GoFieldNameImpl extends GoCompositeElementImpl implements GoFieldName { public GoFieldNameImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFieldName(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @NotNull public PsiReference getReference() { return GoPsiImplUtil.getReference(this); } @Nullable public GoReferenceExpression getQualifier() { return GoPsiImplUtil.getQualifier(this); } @Nullable public PsiElement resolve() { return GoPsiImplUtil.resolve(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoForClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public class GoForClauseImpl extends GoCompositeElementImpl implements GoForClause { public GoForClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitForClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @NotNull public List getStatementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoStatement.class); } public boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) { return GoPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } } ================================================ FILE: gen/com/goide/psi/impl/GoForStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoForStatementImpl extends GoStatementImpl implements GoForStatement { public GoForStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitForStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoForClause getForClause() { return GoPsiTreeUtil.getChildOfType(this, GoForClause.class); } @Override @Nullable public GoRangeClause getRangeClause() { return GoPsiTreeUtil.getChildOfType(this, GoRangeClause.class); } @Override @NotNull public PsiElement getFor() { return notNullChild(findChildByType(FOR)); } } ================================================ FILE: gen/com/goide/psi/impl/GoFunctionDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoFunctionDeclarationStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoFunctionDeclarationImpl extends GoFunctionOrMethodDeclarationImpl implements GoFunctionDeclaration { public GoFunctionDeclarationImpl(GoFunctionDeclarationStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoFunctionDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFunctionDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoBlock getBlock() { return GoPsiTreeUtil.getChildOfType(this, GoBlock.class); } @Override @Nullable public GoSignature getSignature() { return GoPsiTreeUtil.getStubChildOfType(this, GoSignature.class); } @Override @NotNull public PsiElement getFunc() { return notNullChild(findChildByType(FUNC)); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } } ================================================ FILE: gen/com/goide/psi/impl/GoFunctionLitImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public class GoFunctionLitImpl extends GoExpressionImpl implements GoFunctionLit { public GoFunctionLitImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFunctionLit(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoBlock getBlock() { return GoPsiTreeUtil.getChildOfType(this, GoBlock.class); } @Override @Nullable public GoSignature getSignature() { return GoPsiTreeUtil.getChildOfType(this, GoSignature.class); } @Override @NotNull public PsiElement getFunc() { return notNullChild(findChildByType(FUNC)); } public boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) { return GoPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } } ================================================ FILE: gen/com/goide/psi/impl/GoFunctionTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoFunctionTypeImpl extends GoTypeImpl implements GoFunctionType { public GoFunctionTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoFunctionTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitFunctionType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoSignature getSignature() { return GoPsiTreeUtil.getStubChildOfType(this, GoSignature.class); } @Override @NotNull public PsiElement getFunc() { return notNullChild(findChildByType(FUNC)); } } ================================================ FILE: gen/com/goide/psi/impl/GoGoStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoGoStatementImpl extends GoStatementImpl implements GoGoStatement { public GoGoStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitGoStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @NotNull public PsiElement getGo() { return notNullChild(findChildByType(GO)); } } ================================================ FILE: gen/com/goide/psi/impl/GoGotoStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoGotoStatementImpl extends GoStatementImpl implements GoGotoStatement { public GoGotoStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitGotoStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLabelRef getLabelRef() { return GoPsiTreeUtil.getChildOfType(this, GoLabelRef.class); } @Override @NotNull public PsiElement getGoto() { return notNullChild(findChildByType(GOTO)); } } ================================================ FILE: gen/com/goide/psi/impl/GoIfStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoIfStatementImpl extends GoStatementImpl implements GoIfStatement { public GoIfStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitIfStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoElseStatement getElseStatement() { return GoPsiTreeUtil.getChildOfType(this, GoElseStatement.class); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } @Override @Nullable public PsiElement getSemicolon() { return findChildByType(SEMICOLON); } @Override @NotNull public PsiElement getIf() { return notNullChild(findChildByType(IF)); } } ================================================ FILE: gen/com/goide/psi/impl/GoImportDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoImportDeclarationImpl extends GoCompositeElementImpl implements GoImportDeclaration { public GoImportDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitImportDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getImportSpecList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoImportSpec.class); } @Override @Nullable public PsiElement getLparen() { return findChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @NotNull public PsiElement getImport() { return notNullChild(findChildByType(IMPORT)); } @NotNull public GoImportSpec addImportSpec(String packagePath, String alias) { return GoPsiImplUtil.addImportSpec(this, packagePath, alias); } } ================================================ FILE: gen/com/goide/psi/impl/GoImportListImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoImportListImpl extends GoCompositeElementImpl implements GoImportList { public GoImportListImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitImportList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getImportDeclarationList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoImportDeclaration.class); } @NotNull public GoImportSpec addImport(String packagePath, String alias) { return GoPsiImplUtil.addImport(this, packagePath, alias); } } ================================================ FILE: gen/com/goide/psi/impl/GoImportSpecImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoImportSpecStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoImportSpecImpl extends GoNamedElementImpl implements GoImportSpec { public GoImportSpecImpl(GoImportSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoImportSpecImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitImportSpec(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoImportString getImportString() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoImportString.class)); } @Override @Nullable public PsiElement getDot() { return findChildByType(DOT); } @Override @Nullable public PsiElement getIdentifier() { return findChildByType(IDENTIFIER); } public String getAlias() { return GoPsiImplUtil.getAlias(this); } public String getLocalPackageName() { return GoPsiImplUtil.getLocalPackageName(this); } public boolean shouldGoDeeper() { return GoPsiImplUtil.shouldGoDeeper(this); } public boolean isForSideEffects() { return GoPsiImplUtil.isForSideEffects(this); } public boolean isDot() { return GoPsiImplUtil.isDot(this); } @NotNull public String getPath() { return GoPsiImplUtil.getPath(this); } public String getName() { return GoPsiImplUtil.getName(this); } public boolean isCImport() { return GoPsiImplUtil.isCImport(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoImportStringImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiReference; public class GoImportStringImpl extends GoCompositeElementImpl implements GoImportString { public GoImportStringImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitImportString(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoStringLiteral getStringLiteral() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoStringLiteral.class)); } @NotNull public PsiReference[] getReferences() { return GoPsiImplUtil.getReferences(this); } @Nullable public PsiDirectory resolve() { return GoPsiImplUtil.resolve(this); } @NotNull public String getPath() { return GoPsiImplUtil.getPath(this); } @NotNull public TextRange getPathTextRange() { return GoPsiImplUtil.getPathTextRange(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoIncDecStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoIncDecStatementImpl extends GoStatementImpl implements GoIncDecStatement { public GoIncDecStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitIncDecStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoExpression getExpression() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoExpression.class)); } @Override @Nullable public PsiElement getMinusMinus() { return findChildByType(MINUS_MINUS); } @Override @Nullable public PsiElement getPlusPlus() { return findChildByType(PLUS_PLUS); } } ================================================ FILE: gen/com/goide/psi/impl/GoIndexOrSliceExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.openapi.util.Trinity; public class GoIndexOrSliceExprImpl extends GoExpressionImpl implements GoIndexOrSliceExpr { public GoIndexOrSliceExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitIndexOrSliceExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public PsiElement getLbrack() { return notNullChild(findChildByType(LBRACK)); } @Override @Nullable public PsiElement getRbrack() { return findChildByType(RBRACK); } @Nullable public GoExpression getExpression() { return GoPsiImplUtil.getExpression(this); } @NotNull public Trinity getIndices() { return GoPsiImplUtil.getIndices(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoInterfaceTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoInterfaceTypeImpl extends GoTypeImpl implements GoInterfaceType { public GoInterfaceTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoInterfaceTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitInterfaceType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getMethodSpecList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoMethodSpec.class); } @Override @Nullable public PsiElement getLbrace() { return findChildByType(LBRACE); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } @Override @NotNull public PsiElement getInterface() { return notNullChild(findChildByType(INTERFACE)); } @NotNull public List getMethods() { return GoPsiImplUtil.getMethods(this); } @NotNull public List getBaseTypesReferences() { return GoPsiImplUtil.getBaseTypesReferences(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoKeyImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoKeyImpl extends GoCompositeElementImpl implements GoKey { public GoKeyImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitKey(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoFieldName getFieldName() { return GoPsiTreeUtil.getChildOfType(this, GoFieldName.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoLabelDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoLabelDefinitionStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoLabelDefinitionImpl extends GoNamedElementImpl implements GoLabelDefinition { public GoLabelDefinitionImpl(GoLabelDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoLabelDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLabelDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } } ================================================ FILE: gen/com/goide/psi/impl/GoLabelRefImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.PsiReference; public class GoLabelRefImpl extends GoCompositeElementImpl implements GoLabelRef { public GoLabelRefImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLabelRef(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @NotNull public PsiReference getReference() { return GoPsiImplUtil.getReference(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoLabeledStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoLabeledStatementImpl extends GoStatementImpl implements GoLabeledStatement { public GoLabeledStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLabeledStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoLabelDefinition getLabelDefinition() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoLabelDefinition.class)); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } @Override @NotNull public PsiElement getColon() { return notNullChild(findChildByType(COLON)); } } ================================================ FILE: gen/com/goide/psi/impl/GoLeftHandExprListImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoLeftHandExprListImpl extends GoCompositeElementImpl implements GoLeftHandExprList { public GoLeftHandExprListImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLeftHandExprList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoLiteralImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoLiteralImpl extends GoExpressionImpl implements GoLiteral { public GoLiteralImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLiteral(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getChar() { return findChildByType(CHAR); } @Override @Nullable public PsiElement getDecimali() { return findChildByType(DECIMALI); } @Override @Nullable public PsiElement getFloat() { return findChildByType(FLOAT); } @Override @Nullable public PsiElement getFloati() { return findChildByType(FLOATI); } @Override @Nullable public PsiElement getHex() { return findChildByType(HEX); } @Override @Nullable public PsiElement getInt() { return findChildByType(INT); } @Override @Nullable public PsiElement getOct() { return findChildByType(OCT); } } ================================================ FILE: gen/com/goide/psi/impl/GoLiteralTypeExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoLiteralTypeExprImpl extends GoExpressionImpl implements GoLiteralTypeExpr { public GoLiteralTypeExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLiteralTypeExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getChildOfType(this, GoType.class); } @Override @Nullable public GoTypeReferenceExpression getTypeReferenceExpression() { return GoPsiTreeUtil.getChildOfType(this, GoTypeReferenceExpression.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoLiteralValueImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoLiteralValueImpl extends GoCompositeElementImpl implements GoLiteralValue { public GoLiteralValueImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitLiteralValue(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getElementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoElement.class); } @Override @NotNull public PsiElement getLbrace() { return notNullChild(findChildByType(LBRACE)); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } } ================================================ FILE: gen/com/goide/psi/impl/GoMapTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoMapTypeImpl extends GoTypeImpl implements GoMapType { public GoMapTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoMapTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitMapType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getTypeList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoType.class); } @Override @Nullable public PsiElement getLbrack() { return findChildByType(LBRACK); } @Override @Nullable public PsiElement getRbrack() { return findChildByType(RBRACK); } @Override @NotNull public PsiElement getMap() { return notNullChild(findChildByType(MAP)); } @Override @Nullable public GoType getKeyType() { List p1 = getTypeList(); return p1.size() < 1 ? null : p1.get(0); } @Override @Nullable public GoType getValueType() { List p1 = getTypeList(); return p1.size() < 2 ? null : p1.get(1); } } ================================================ FILE: gen/com/goide/psi/impl/GoMethodDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoMethodDeclarationStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoMethodDeclarationImpl extends GoFunctionOrMethodDeclarationImpl implements GoMethodDeclaration { public GoMethodDeclarationImpl(GoMethodDeclarationStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoMethodDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitMethodDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoBlock getBlock() { return GoPsiTreeUtil.getChildOfType(this, GoBlock.class); } @Override @Nullable public GoReceiver getReceiver() { return GoPsiTreeUtil.getStubChildOfType(this, GoReceiver.class); } @Override @Nullable public GoSignature getSignature() { return GoPsiTreeUtil.getStubChildOfType(this, GoSignature.class); } @Override @NotNull public PsiElement getFunc() { return notNullChild(findChildByType(FUNC)); } @Override @Nullable public PsiElement getIdentifier() { return findChildByType(IDENTIFIER); } @Nullable public GoType getReceiverType() { return GoPsiImplUtil.getReceiverType(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoMethodSpecImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoMethodSpecStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoMethodSpecImpl extends GoNamedElementImpl implements GoMethodSpec { public GoMethodSpecImpl(GoMethodSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoMethodSpecImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitMethodSpec(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoSignature getSignature() { return GoPsiTreeUtil.getStubChildOfType(this, GoSignature.class); } @Override @Nullable public GoTypeReferenceExpression getTypeReferenceExpression() { return GoPsiTreeUtil.getChildOfType(this, GoTypeReferenceExpression.class); } @Override @Nullable public PsiElement getIdentifier() { return findChildByType(IDENTIFIER); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } @Nullable public String getName() { return GoPsiImplUtil.getName(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoMulExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoMulExprImpl extends GoBinaryExprImpl implements GoMulExpr { public GoMulExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitMulExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getBitAnd() { return findChildByType(BIT_AND); } @Override @Nullable public PsiElement getBitClear() { return findChildByType(BIT_CLEAR); } @Override @Nullable public PsiElement getMul() { return findChildByType(MUL); } @Override @Nullable public PsiElement getQuotient() { return findChildByType(QUOTIENT); } @Override @Nullable public PsiElement getRemainder() { return findChildByType(REMAINDER); } @Override @Nullable public PsiElement getShiftLeft() { return findChildByType(SHIFT_LEFT); } @Override @Nullable public PsiElement getShiftRight() { return findChildByType(SHIFT_RIGHT); } } ================================================ FILE: gen/com/goide/psi/impl/GoOrExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoOrExprImpl extends GoBinaryExprImpl implements GoOrExpr { public GoOrExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitOrExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getCondOr() { return notNullChild(findChildByType(COND_OR)); } } ================================================ FILE: gen/com/goide/psi/impl/GoPackageClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoPackageClauseStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoPackageClauseImpl extends GoStubbedElementImpl implements GoPackageClause { public GoPackageClauseImpl(GoPackageClauseStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoPackageClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitPackageClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getIdentifier() { return findChildByType(IDENTIFIER); } @Override @NotNull public PsiElement getPackage() { return notNullChild(findChildByType(PACKAGE)); } @Nullable public String getName() { return GoPsiImplUtil.getName(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoParTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoParTypeImpl extends GoTypeImpl implements GoParType { public GoParTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoParTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitParType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoType getType() { return notNullChild(GoPsiTreeUtil.getStubChildOfType(this, GoType.class)); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @NotNull public PsiElement getRparen() { return notNullChild(findChildByType(RPAREN)); } @NotNull public GoType getActualType() { return GoPsiImplUtil.getActualType(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoParamDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoParamDefinitionStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoParamDefinitionImpl extends GoNamedElementImpl implements GoParamDefinition { public GoParamDefinitionImpl(GoParamDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoParamDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitParamDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } public boolean isVariadic() { return GoPsiImplUtil.isVariadic(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoParameterDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoParameterDeclarationStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoParameterDeclarationImpl extends GoStubbedElementImpl implements GoParameterDeclaration { public GoParameterDeclarationImpl(GoParameterDeclarationStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoParameterDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitParameterDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getParamDefinitionList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoParamDefinition.class); } @Override @NotNull public GoType getType() { return notNullChild(GoPsiTreeUtil.getStubChildOfType(this, GoType.class)); } @Override @Nullable public PsiElement getTripleDot() { return findChildByType(TRIPLE_DOT); } public boolean isVariadic() { return GoPsiImplUtil.isVariadic(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoParametersImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoParametersStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoParametersImpl extends GoStubbedElementImpl implements GoParameters { public GoParametersImpl(GoParametersStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoParametersImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitParameters(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getParameterDeclarationList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoParameterDeclaration.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } } ================================================ FILE: gen/com/goide/psi/impl/GoParenthesesExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoParenthesesExprImpl extends GoExpressionImpl implements GoParenthesesExpr { public GoParenthesesExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitParenthesesExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } } ================================================ FILE: gen/com/goide/psi/impl/GoPointerTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoPointerTypeImpl extends GoTypeImpl implements GoPointerType { public GoPointerTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoPointerTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitPointerType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @NotNull public PsiElement getMul() { return notNullChild(findChildByType(MUL)); } } ================================================ FILE: gen/com/goide/psi/impl/GoRangeClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoVarSpecStub; import com.intellij.psi.stubs.IStubElementType; public class GoRangeClauseImpl extends GoVarSpecImpl implements GoRangeClause { public GoRangeClauseImpl(GoVarSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoRangeClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitRangeClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getVarDefinitionList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoVarDefinition.class); } @Override @Nullable public PsiElement getVarAssign() { return findChildByType(VAR_ASSIGN); } @Override @Nullable public PsiElement getRange() { return findChildByType(RANGE); } @Nullable public GoExpression getRangeExpression() { return GoPsiImplUtil.getRangeExpression(this); } @NotNull public List getLeftExpressionsList() { return GoPsiImplUtil.getLeftExpressionsList(this); } @NotNull public List getRightExpressionsList() { return GoPsiImplUtil.getRightExpressionsList(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoReceiverImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoReceiverStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoReceiverImpl extends GoNamedElementImpl implements GoReceiver { public GoReceiverImpl(GoReceiverStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoReceiverImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitReceiver(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @Nullable public PsiElement getComma() { return findChildByType(COMMA); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @Nullable public PsiElement getIdentifier() { return findChildByType(IDENTIFIER); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } } ================================================ FILE: gen/com/goide/psi/impl/GoRecvStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoVarSpecStub; import com.intellij.psi.stubs.IStubElementType; public class GoRecvStatementImpl extends GoVarSpecImpl implements GoRecvStatement { public GoRecvStatementImpl(GoVarSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoRecvStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitRecvStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public List getVarDefinitionList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoVarDefinition.class); } @Override @Nullable public PsiElement getVarAssign() { return findChildByType(VAR_ASSIGN); } @Nullable public GoExpression getRecvExpression() { return GoPsiImplUtil.getRecvExpression(this); } @NotNull public List getLeftExpressionsList() { return GoPsiImplUtil.getLeftExpressionsList(this); } @NotNull public List getRightExpressionsList() { return GoPsiImplUtil.getRightExpressionsList(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoReferenceExpressionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access; public class GoReferenceExpressionImpl extends GoExpressionImpl implements GoReferenceExpression { public GoReferenceExpressionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitReferenceExpression(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @NotNull public GoReference getReference() { return GoPsiImplUtil.getReference(this); } @Nullable public GoReferenceExpression getQualifier() { return GoPsiImplUtil.getQualifier(this); } @Nullable public PsiElement resolve() { return GoPsiImplUtil.resolve(this); } @NotNull public Access getReadWriteAccess() { return GoPsiImplUtil.getReadWriteAccess(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoResultImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoResultStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoResultImpl extends GoStubbedElementImpl implements GoResult { public GoResultImpl(GoResultStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoResultImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitResult(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoParameters getParameters() { return GoPsiTreeUtil.getStubChildOfType(this, GoParameters.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @Nullable public PsiElement getLparen() { return findChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } public boolean isVoid() { return GoPsiImplUtil.isVoid(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoReturnStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoReturnStatementImpl extends GoStatementImpl implements GoReturnStatement { public GoReturnStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitReturnStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @NotNull public PsiElement getReturn() { return notNullChild(findChildByType(RETURN)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSelectStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSelectStatementImpl extends GoStatementImpl implements GoSelectStatement { public GoSelectStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSelectStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getCommClauseList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoCommClause.class); } @Override @Nullable public PsiElement getLbrace() { return findChildByType(LBRACE); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } @Override @NotNull public PsiElement getSelect() { return notNullChild(findChildByType(SELECT)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSelectorExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSelectorExprImpl extends GoBinaryExprImpl implements GoSelectorExpr { public GoSelectorExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSelectorExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getDot() { return notNullChild(findChildByType(DOT)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSendStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSendStatementImpl extends GoStatementImpl implements GoSendStatement { public GoSendStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSendStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @Nullable public GoLeftHandExprList getLeftHandExprList() { return GoPsiTreeUtil.getChildOfType(this, GoLeftHandExprList.class); } @Override @NotNull public PsiElement getSendChannel() { return notNullChild(findChildByType(SEND_CHANNEL)); } @Nullable public GoExpression getSendExpression() { return GoPsiImplUtil.getSendExpression(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoShortVarDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoVarSpecStub; import com.intellij.psi.stubs.IStubElementType; public class GoShortVarDeclarationImpl extends GoVarSpecImpl implements GoShortVarDeclaration { public GoShortVarDeclarationImpl(GoVarSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoShortVarDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitShortVarDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getVarAssign() { return notNullChild(findChildByType(VAR_ASSIGN)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSignatureImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoSignatureStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoSignatureImpl extends GoStubbedElementImpl implements GoSignature { public GoSignatureImpl(GoSignatureStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoSignatureImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSignature(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoParameters getParameters() { return notNullChild(GoPsiTreeUtil.getStubChildOfType(this, GoParameters.class)); } @Override @Nullable public GoResult getResult() { return GoPsiTreeUtil.getStubChildOfType(this, GoResult.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoSimpleStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSimpleStatementImpl extends GoStatementImpl implements GoSimpleStatement { public GoSimpleStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSimpleStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoLeftHandExprList getLeftHandExprList() { return GoPsiTreeUtil.getChildOfType(this, GoLeftHandExprList.class); } @Override @Nullable public GoShortVarDeclaration getShortVarDeclaration() { return GoPsiTreeUtil.getChildOfType(this, GoShortVarDeclaration.class); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoSpecTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoSpecTypeImpl extends GoTypeImpl implements GoSpecType { public GoSpecTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoSpecTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSpecType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } } ================================================ FILE: gen/com/goide/psi/impl/GoStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; public class GoStatementImpl extends GoCompositeElementImpl implements GoStatement { public GoStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoBlock getBlock() { return GoPsiTreeUtil.getChildOfType(this, GoBlock.class); } @Override @Nullable public GoConstDeclaration getConstDeclaration() { return GoPsiTreeUtil.getChildOfType(this, GoConstDeclaration.class); } @Override @Nullable public GoTypeDeclaration getTypeDeclaration() { return GoPsiTreeUtil.getChildOfType(this, GoTypeDeclaration.class); } @Override @Nullable public GoVarDeclaration getVarDeclaration() { return GoPsiTreeUtil.getChildOfType(this, GoVarDeclaration.class); } public boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) { return GoPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } } ================================================ FILE: gen/com/goide/psi/impl/GoStringLiteralImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.util.GoStringLiteralEscaper; public class GoStringLiteralImpl extends GoExpressionImpl implements GoStringLiteral { public GoStringLiteralImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitStringLiteral(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public PsiElement getRawString() { return findChildByType(RAW_STRING); } @Override @Nullable public PsiElement getString() { return findChildByType(STRING); } public boolean isValidHost() { return GoPsiImplUtil.isValidHost(this); } @NotNull public GoStringLiteralImpl updateText(String text) { return GoPsiImplUtil.updateText(this, text); } @NotNull public GoStringLiteralEscaper createLiteralTextEscaper() { return GoPsiImplUtil.createLiteralTextEscaper(this); } @NotNull public String getDecodedText() { return GoPsiImplUtil.getDecodedText(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoStructTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoStructTypeImpl extends GoTypeImpl implements GoStructType { public GoStructTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoStructTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitStructType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getFieldDeclarationList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoFieldDeclaration.class); } @Override @Nullable public PsiElement getLbrace() { return findChildByType(LBRACE); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } @Override @NotNull public PsiElement getStruct() { return notNullChild(findChildByType(STRUCT)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSwitchStartImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSwitchStartImpl extends GoCompositeElementImpl implements GoSwitchStart { public GoSwitchStartImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSwitchStart(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getSwitch() { return notNullChild(findChildByType(SWITCH)); } } ================================================ FILE: gen/com/goide/psi/impl/GoSwitchStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoSwitchStatementImpl extends GoStatementImpl implements GoSwitchStatement { public GoSwitchStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitSwitchStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoSwitchStart getSwitchStart() { return GoPsiTreeUtil.getChildOfType(this, GoSwitchStart.class); } @Override @Nullable public GoSwitchStatement getSwitchStatement() { return GoPsiTreeUtil.getChildOfType(this, GoSwitchStatement.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoTagImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTagImpl extends GoCompositeElementImpl implements GoTag { public GoTagImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTag(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoStringLiteral getStringLiteral() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoStringLiteral.class)); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeAssertionExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeAssertionExprImpl extends GoExpressionImpl implements GoTypeAssertionExpr { public GoTypeAssertionExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeAssertionExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoExpression getExpression() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoExpression.class)); } @Override @NotNull public GoType getType() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoType.class)); } @Override @NotNull public PsiElement getDot() { return notNullChild(findChildByType(DOT)); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @NotNull public PsiElement getRparen() { return notNullChild(findChildByType(RPAREN)); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeCaseClauseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeCaseClauseImpl extends GoCompositeElementImpl implements GoTypeCaseClause { public GoTypeCaseClauseImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeCaseClause(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getStatementList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoStatement.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getChildOfType(this, GoType.class); } @Override @Nullable public PsiElement getColon() { return findChildByType(COLON); } @Override @Nullable public PsiElement getCase() { return findChildByType(CASE); } @Override @Nullable public PsiElement getDefault() { return findChildByType(DEFAULT); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeDeclarationImpl extends GoCompositeElementImpl implements GoTypeDeclaration { public GoTypeDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getTypeSpecList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoTypeSpec.class); } @Override @Nullable public PsiElement getLparen() { return findChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @NotNull public PsiElement getType_() { return notNullChild(findChildByType(TYPE_)); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeGuardImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeGuardImpl extends GoCompositeElementImpl implements GoTypeGuard { public GoTypeGuardImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeGuard(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getLparen() { return notNullChild(findChildByType(LPAREN)); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @NotNull public PsiElement getType_() { return notNullChild(findChildByType(TYPE_)); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoTypeStub; import com.goide.psi.*; import com.intellij.psi.stubs.IStubElementType; public class GoTypeImpl extends GoStubbedElementImpl implements GoType { public GoTypeImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoTypeImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitType(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoTypeReferenceExpression getTypeReferenceExpression() { return GoPsiTreeUtil.getChildOfType(this, GoTypeReferenceExpression.class); } @NotNull public GoType getUnderlyingType() { return GoPsiImplUtil.getUnderlyingType(this); } public boolean shouldGoDeeper() { return GoPsiImplUtil.shouldGoDeeper(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeListImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.psi.stubs.IStubElementType; public class GoTypeListImpl extends GoTypeImpl implements GoTypeList { public GoTypeListImpl(GoTypeStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoTypeListImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getTypeList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoType.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeReferenceExpressionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; import com.intellij.psi.PsiReference; public class GoTypeReferenceExpressionImpl extends GoCompositeElementImpl implements GoTypeReferenceExpression { public GoTypeReferenceExpressionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeReferenceExpression(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @NotNull public PsiReference getReference() { return GoPsiImplUtil.getReference(this); } @Nullable public GoTypeReferenceExpression getQualifier() { return GoPsiImplUtil.getQualifier(this); } @Nullable public PsiElement resolve() { return GoPsiImplUtil.resolve(this); } @Nullable public GoType resolveType() { return GoPsiImplUtil.resolveType(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeSpecImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoTypeSpecStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoTypeSpecImpl extends GoNamedElementImpl implements GoTypeSpec { public GoTypeSpecImpl(GoTypeSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoTypeSpecImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeSpec(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoSpecType getSpecType() { return notNullChild(GoPsiTreeUtil.getStubChildOfType(this, GoSpecType.class)); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } @NotNull public List getMethods() { return GoPsiImplUtil.getMethods(this); } public boolean shouldGoDeeper() { return GoPsiImplUtil.shouldGoDeeper(this); } @Override @NotNull public PsiElement getIdentifier() { GoSpecType p1 = getSpecType(); return p1.getIdentifier(); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeSwitchGuardImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeSwitchGuardImpl extends GoCompositeElementImpl implements GoTypeSwitchGuard { public GoTypeSwitchGuardImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeSwitchGuard(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public GoExpression getExpression() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoExpression.class)); } @Override @NotNull public GoTypeGuard getTypeGuard() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoTypeGuard.class)); } @Override @Nullable public GoVarDefinition getVarDefinition() { return GoPsiTreeUtil.getChildOfType(this, GoVarDefinition.class); } @Override @NotNull public PsiElement getDot() { return notNullChild(findChildByType(DOT)); } @Override @Nullable public PsiElement getVarAssign() { return findChildByType(VAR_ASSIGN); } } ================================================ FILE: gen/com/goide/psi/impl/GoTypeSwitchStatementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoTypeSwitchStatementImpl extends GoSwitchStatementImpl implements GoTypeSwitchStatement { public GoTypeSwitchStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitTypeSwitchStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoStatement getStatement() { return GoPsiTreeUtil.getChildOfType(this, GoStatement.class); } @Override @NotNull public GoSwitchStart getSwitchStart() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoSwitchStart.class)); } @Override @NotNull public List getTypeCaseClauseList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoTypeCaseClause.class); } @Override @NotNull public GoTypeSwitchGuard getTypeSwitchGuard() { return notNullChild(GoPsiTreeUtil.getChildOfType(this, GoTypeSwitchGuard.class)); } @Override @Nullable public PsiElement getLbrace() { return findChildByType(LBRACE); } @Override @Nullable public PsiElement getRbrace() { return findChildByType(RBRACE); } @Override @Nullable public PsiElement getSemicolon() { return findChildByType(SEMICOLON); } } ================================================ FILE: gen/com/goide/psi/impl/GoUnaryExprImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoUnaryExprImpl extends GoExpressionImpl implements GoUnaryExpr { public GoUnaryExprImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitUnaryExpr(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public PsiElement getBitAnd() { return findChildByType(BIT_AND); } @Override @Nullable public PsiElement getBitXor() { return findChildByType(BIT_XOR); } @Override @Nullable public PsiElement getMinus() { return findChildByType(MINUS); } @Override @Nullable public PsiElement getMul() { return findChildByType(MUL); } @Override @Nullable public PsiElement getNot() { return findChildByType(NOT); } @Override @Nullable public PsiElement getPlus() { return findChildByType(PLUS); } @Override @Nullable public PsiElement getSendChannel() { return findChildByType(SEND_CHANNEL); } @Nullable public PsiElement getOperator() { return GoPsiImplUtil.getOperator(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoValueImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoValueImpl extends GoCompositeElementImpl implements GoValue { public GoValueImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitValue(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @Nullable public GoExpression getExpression() { return GoPsiTreeUtil.getChildOfType(this, GoExpression.class); } @Override @Nullable public GoLiteralValue getLiteralValue() { return GoPsiTreeUtil.getChildOfType(this, GoLiteralValue.class); } } ================================================ FILE: gen/com/goide/psi/impl/GoVarDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoVarDeclarationImpl extends GoCompositeElementImpl implements GoVarDeclaration { public GoVarDeclarationImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitVarDeclaration(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getVarSpecList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoVarSpec.class); } @Override @Nullable public PsiElement getLparen() { return findChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } @Override @NotNull public PsiElement getVar() { return notNullChild(findChildByType(VAR)); } @NotNull public GoVarSpec addSpec(String name, String type, String value, GoVarSpec specAnchor) { return GoPsiImplUtil.addSpec(this, name, type, value, specAnchor); } public void deleteSpec(GoVarSpec specToDelete) { GoPsiImplUtil.deleteSpec(this, specToDelete); } } ================================================ FILE: gen/com/goide/psi/impl/GoVarDefinitionImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoVarDefinitionStub; import com.goide.psi.*; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; public class GoVarDefinitionImpl extends GoNamedElementImpl implements GoVarDefinition { public GoVarDefinitionImpl(GoVarDefinitionStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoVarDefinitionImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitVarDefinition(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return notNullChild(findChildByType(IDENTIFIER)); } @Nullable public GoType getGoTypeInner(ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } @Nullable public PsiReference getReference() { return GoPsiImplUtil.getReference(this); } @Nullable public GoExpression getValue() { return GoPsiImplUtil.getValue(this); } } ================================================ FILE: gen/com/goide/psi/impl/GoVarSpecImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.goide.psi.GoPsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.stubs.GoVarSpecStub; import com.goide.psi.*; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.stubs.IStubElementType; public class GoVarSpecImpl extends GoStubbedElementImpl implements GoVarSpec { public GoVarSpecImpl(GoVarSpecStub stub, IStubElementType nodeType) { super(stub, nodeType); } public GoVarSpecImpl(ASTNode node) { super(node); } public void accept(@NotNull GoVisitor visitor) { visitor.visitVarSpec(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) accept((GoVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getExpressionList() { return GoPsiTreeUtil.getChildrenOfTypeAsList(this, GoExpression.class); } @Override @Nullable public GoType getType() { return GoPsiTreeUtil.getStubChildOfType(this, GoType.class); } @Override @NotNull public List getVarDefinitionList() { return GoPsiTreeUtil.getStubChildrenOfTypeAsList(this, GoVarDefinition.class); } @Override @Nullable public PsiElement getAssign() { return findChildByType(ASSIGN); } public boolean processDeclarations(PsiScopeProcessor processor, ResolveState state, PsiElement lastParent, PsiElement place) { return GoPsiImplUtil.processDeclarations(this, processor, state, lastParent, place); } public void deleteDefinition(GoVarDefinition definitionToDelete) { GoPsiImplUtil.deleteDefinition(this, definitionToDelete); } @NotNull public List getRightExpressionsList() { return GoPsiImplUtil.getRightExpressionsList(this); } } ================================================ FILE: google-app-engine/google-app-engine-yaml/build.gradle ================================================ dependencies { compile project(':google-app-engine') } ================================================ FILE: google-app-engine/google-app-engine-yaml/src/yaml/AppEngineYamlCompletionContributor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 yaml; import com.intellij.appengine.AppEngineExtension; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.psi.PsiElement; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; @SuppressWarnings("ALL") public class AppEngineYamlCompletionContributor extends CompletionContributor { public AppEngineYamlCompletionContributor() { //extend(CompletionType.BASIC, key(), new YamlCompletionProvider()); //extend(CompletionType.BASIC, inSequence(), new YamlCompletionProvider()); } private static class YamlCompletionProvider extends CompletionProvider { @Override protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet result) { PsiElement position = completionParameters.getPosition(); if (!AppEngineExtension.isAppEngineContext(position)) { return; } } } } ================================================ FILE: google-app-engine/google-app-engine-yaml/src/yaml/YamlConstants.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 yaml; import java.util.Collections; import java.util.EnumSet; public interface YamlConstants { enum Value { REQUIRED, ADMIN, UNAUTHORIZED, REDIRECT, OPTIONAL, NEVER, ALWAYS, TRUE, FALSE } enum Key { APPLICATION(true, true), HANDLERS(true, true), VERSION(false, true), RUNTIME(true, true), API_VERSION(true, true), URL(true, false), THREADSAFE(false, true, Value.TRUE, Value.FALSE), DEFAULT_EXPIRATION(false, true), BUILTINS(false, true), INCLUDES(false, true), INBOUND_SERVICES(false, true), ADMIN_CONSOLE(false, true), ERROR_HANDLERS(false, true), MIME_TYPE(false, false), EXPIRATION(false, false), UPLOAD(false, false), AUTH_FAIL_ACTION(false, false, Value.UNAUTHORIZED, Value.REDIRECT), SECURE(false, false, Value.OPTIONAL, Value.NEVER, Value.ALWAYS), LOGIN(false, false, Value.REQUIRED, Value.ADMIN), SKIP_FILES(false, true), TYPE_SCRIPT(true, false), TYPE_STATIC_DIR(true, false), TYPE_STATIC_FILES(true, false); private final boolean myRequired; private final boolean myTopLevel; private final EnumSet myValues; Key(boolean required, boolean topLevel, Value... values) { myRequired = required; myTopLevel = topLevel; myValues = EnumSet.noneOf(Value.class); Collections.addAll(myValues, values); } } } ================================================ FILE: google-app-engine/src/com/intellij/appengine/AppEngineExtension.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.intellij.appengine; import com.intellij.openapi.Disposable; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.util.Disposer; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class AppEngineExtension { private static final ExtensionPointName EXTENSION = ExtensionPointName.create("ro.redeul.google.go.appengine.Extension"); private static boolean ourTestingMode; public static void enableTestingMode(@NotNull Disposable disposable) { ourTestingMode = true; Disposer.register(disposable, () -> { //noinspection AssignmentToStaticFieldFromInstanceMethod ourTestingMode = false; }); } public abstract boolean isAppEngineEnabled(@Nullable PsiElement context); public static boolean isAppEngineContext(@Nullable PsiElement context) { for (AppEngineExtension extension : EXTENSION.getExtensions()) { if (extension.isAppEngineEnabled(context)) { return true; } } return ourTestingMode; } } ================================================ FILE: google-app-engine/src/com/intellij/appengine/GoogleAppEngineIcons.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.intellij.appengine; import com.intellij.openapi.util.IconLoader; import javax.swing.*; public class GoogleAppEngineIcons { public static final Icon AppEngine = IconLoader.findIcon("/icons/appEngine.png"); public static final Icon AppEngineMark = IconLoader.findIcon("/icons/appEngineMark.png"); private GoogleAppEngineIcons() {} } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ # # Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan # # 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. # #Wed Jun 22 07:25:55 MSK 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-milestone-2-all.zip ================================================ FILE: gradle.properties ================================================ # # Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan # # 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. # version = 0.13 ideaVersion = 2016.3 javaVersion = 1.8 javaTargetVersion = 1.8 delveVersion = 0.11.318 customDlvPath = buildNumber=SNAPSHOT isEAP=false sources=true customSinceBuild= localIdePath= publishUsername=user publishPassword=password publishChannel= org.gradle.jvmargs=-Xms256m -Xmx1024m ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: grammars/copyrightHeader.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. ================================================ FILE: grammars/go.bnf ================================================ { parserClass='com.goide.parser.GoParser' classHeader='copyrightHeader.java' implements='com.goide.psi.GoCompositeElement' extends='com.goide.psi.impl.GoCompositeElementImpl' elementTypeHolderClass='com.goide.GoTypes' elementTypeClass='com.goide.psi.GoCompositeElementType' tokenTypeClass='com.goide.psi.GoTokenType' psiTreeUtilClass='com.goide.psi.GoPsiTreeUtil' psiClassPrefix='Go' psiImplClassSuffix='Impl' psiPackage='com.goide.psi' psiImplPackage='com.goide.psi.impl' psiImplUtilClass="com.goide.psi.impl.GoPsiImplUtil" parserUtilClass="com.goide.parser.GoParserUtil" tokens=[ LBRACE = '{' RBRACE = '}' LBRACK = '[' RBRACK = ']' LPAREN = '(' RPAREN = ')' COLON = ':' SEMICOLON = ';' COMMA = ',' EQ = '==' ASSIGN = '=' NOT_EQ = '!=' NOT = '!' PLUS_PLUS = '++' PLUS_ASSIGN = '+=' PLUS = '+' MINUS_MINUS = '--' MINUS_ASSIGN = '-=' MINUS = '-' COND_OR = '||' BIT_OR_ASSIGN = '|=' BIT_CLEAR_ASSIGN = '&^=' BIT_CLEAR = '&^' COND_AND = '&&' BIT_AND_ASSIGN = '&=' BIT_AND = '&' BIT_OR = '|' SHIFT_LEFT_ASSIGN = '<<=' SHIFT_LEFT = '<<' SEND_CHANNEL = '<-' LESS_OR_EQUAL = '<=' LESS = '<' BIT_XOR_ASSIGN = '^=' BIT_XOR = '^' MUL_ASSIGN = '*=' MUL = '*' QUOTIENT_ASSIGN = '/=' QUOTIENT = '/' REMAINDER_ASSIGN = '%=' REMAINDER = '%' SHIFT_RIGHT_ASSIGN = '>>=' SHIFT_RIGHT = '>>' GREATER_OR_EQUAL = '>=' GREATER = '>' VAR_ASSIGN = ':=' TRIPLE_DOT = '...' DOT = '.' SEMICOLON_SYNTHETIC = '' TYPE_ = 'type' raw_string = 'raw_string' ] extends("(Or|And|Add|Conversion|Mul|Selector|Conditional)Expr")=BinaryExpr extends(".*(Expr|Literal|Lit|OperandName)")=Expression implements("(Type|Import)Spec|(Var|Const|Param|(Anonymous)?Field|Label)Definition|Receiver")="com.goide.psi.GoNamedElement" implements("FunctionLit")="com.goide.psi.GoSignatureOwner" implements("MethodSpec")="com.goide.psi.GoNamedSignatureOwner" implements("(Function|Method)Declaration")="com.goide.psi.GoFunctionOrMethodDeclaration" implements("(Const|Type|Var)Declaration")="com.goide.psi.GoTopLevelDeclaration" implements(".*ReferenceExpression|FieldName")="com.goide.psi.GoReferenceExpressionBase" extends("(Function|Method)Declaration")="com.goide.psi.impl.GoFunctionOrMethodDeclarationImpl" extends("(Type|Import|Method)Spec|(Var|Const|Param|(Anonymous)?Field|Label)Definition|Receiver")="com.goide.psi.impl.GoNamedElementImpl" extends("PackageClause|Parameters|Signature|ParameterDeclaration|Result|Type|(Const|Var|Import)Spec")="com.goide.psi.impl.GoStubbedElementImpl" elementTypeFactory("PackageClause|(Function|Method|Parameter)Declaration|(Type|Import|Method|Const|Var)Spec|RangeClause|RecvStatement|ShortVarDeclaration|(Var|Const|Param|(Anonymous)?Field|Label)Definition|Receiver|Parameters|Signature|Result|.*Type|TypeList.*")='com.goide.stubs.GoElementTypeFactory.stubFactory' pin(".*Statement")=1 extends(".*Statement")=Statement extends(".*Type|TypeList")=Type pin('.*List(?:_\d.*)?')=1 generateTokenAccessors=true } File ::= PackageClause semi ImportList TopLevelDeclaration* {pin(".*")=1} ImportList ::= (ImportDeclaration semi)+|<> { methods=[addImport] } private semi ::= '' | ';' | <> PackageClause ::= package identifier {pin=1 methods=[getName] stubClass="com.goide.stubs.GoPackageClauseStub"} ImportDeclaration ::= import ( ImportSpec | '(' ImportSpecs? ')' ) { pin(".*")=1 methods=[addImportSpec] } private ImportSpecs ::= ImportSpec (semi ImportSpec)* semi? {pin=1} ImportSpec ::= [ '.' | identifier ] ImportString { stubClass="com.goide.stubs.GoImportSpecStub" methods=[getAlias getLocalPackageName shouldGoDeeper isForSideEffects isDot getPath getName isCImport] } ImportString ::= StringLiteral {methods=[getReferences resolve getPath getPathTextRange]} Type ::= TypeName | TypeLit | ParType {stubClass="com.goide.stubs.GoTypeStub" methods=[getUnderlyingType shouldGoDeeper]} ParType ::= '(' Type ')' {methods=[getActualType]} private TypeName ::= TypeReferenceExpression QualifiedTypeReferenceExpression? TypeReferenceExpression ::= identifier { methods=[getReference getQualifier resolve resolveType] } left QualifiedTypeReferenceExpression ::= '.' identifier {elementType=TypeReferenceExpression} private TypeLit ::= ArrayOrSliceType | StructType | PointerType | FunctionType | InterfaceType | MapType | ChannelType ArrayOrSliceType ::= '[' ('...'|Expression?) ']' Type {pin=1} StructType ::= struct '{' Fields? '}' {pin=1} private Fields ::= FieldDeclaration (semi FieldDeclaration)* semi? {pin=1} FieldDeclaration ::= (FieldDefinitionList Type | AnonymousFieldDefinition) Tag? Tag ::= StringLiteral private FieldDefinitionList ::= FieldDefinition (',' FieldDefinition)* FieldDefinition ::= identifier { stubClass="com.goide.stubs.GoFieldDefinitionStub" } AnonymousFieldDefinition ::= Type { stubClass="com.goide.stubs.GoAnonymousFieldDefinitionStub" methods=[getIdentifier getName getTypeReferenceExpression getGoTypeInner] } PointerType ::= '*' Type {pin=1} FunctionType ::= func Signature {pin=1 implements="com.goide.psi.GoSignatureOwner"} Signature ::= Parameters Result? { pin=1 stubClass="com.goide.stubs.GoSignatureStub" } Result ::= '(' TypeListNoPin ')' | Type | Parameters { // todo: reorder and pin ( stubClass="com.goide.stubs.GoResultStub" methods=[isVoid] } Parameters ::= '(' [ (ParameterList ','?| TypeListNoPin) ] ')' { pin=1 stubClass="com.goide.stubs.GoParametersStub" } private ParameterList ::= ParameterDeclaration (',' (ParameterDeclaration | &')'))* {pin(".*")=1} ParameterDeclaration ::= ParamDefinitionListNoPin? '...'? Type | Type { // todo: use left rule stubClass="com.goide.stubs.GoParameterDeclarationStub" methods = [isVariadic] } private ParamDefinitionListNoPin ::= ParamDefinition &(!('.' | ')')) (',' ParamDefinition)* // todo ParamDefinition ::= identifier { stubClass="com.goide.stubs.GoParamDefinitionStub" methods = [isVariadic] } InterfaceType ::= interface '{' MethodSpecs? '}' { pin(".*")=1 methods=[getMethods getBaseTypesReferences] } private MethodSpecs ::= MethodSpec (semi MethodSpec)* semi? {pin=1} MethodSpec ::= TypeName &(!'(') | identifier Signature { stubClass="com.goide.stubs.GoMethodSpecStub" methods=[getGoTypeInner getName] } MapType ::= map '[' Type ']' Type { pin=1 methods = [ keyType="Type[0]" valueType="Type[1]" ] } ChannelType ::= ChanTypePrefix Type {pin=1} private ChanTypePrefix ::= chan '<-'? | '<-' chan {pin(".*")=1} BlockWithConsume ::= <> | BlockInner {elementType=Block} Block ::= BlockInner {methods=[processDeclarations]} private BlockInner ::= '{' ('}' | (<> | (!() Statements)) '}') {pin(".*")=1} private Statements ::= StatementWithSemi* private StatementWithSemi ::= Statement (semi|&'}') { pin=1 recoverWhile=StatementRecover } Statement ::= ConstDeclaration | TypeDeclaration | VarDeclaration | LabeledStatement | SimpleStatement | GoStatement | ReturnStatement | BreakStatement | ContinueStatement | GotoStatement | FallthroughStatement | Block | IfStatement | SwitchStatement | SelectStatement | ForStatement | DeferStatement {methods=[processDeclarations]} private StatementRecover ::= !('!' | '&' | '(' | '*' | '+' | '-' | ';' | '<-' | '^' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var) SimpleStatement ::= ShortVarDeclaration | IncDecStatement | (LeftHandExprList [AssignmentStatement | SendStatement]) {pin(".*")=LeftHandExprList} private TopLevelDeclaration ::= !<> TopDeclaration semi {pin=1 recoverWhile=TopLevelDeclarationRecover} private TopDeclaration ::= ConstDeclaration | TypeDeclaration | VarDeclaration | FunctionDeclaration | MethodDeclaration private TopLevelDeclarationRecover ::= !(';' |'type' | const | func | var) ConstDeclaration ::= const ( ConstSpec | '(' ConstSpecs? ')' ) {pin(".*")=1 methods=[addSpec deleteSpec]} private ConstSpecs ::= ConstSpec (semi ConstSpec)* semi? {pin=1} ConstSpec ::= ConstDefinitionList [ ('=' ExpressionList | Type '=' ExpressionList) ] { pin(".*")=1 stubClass="com.goide.stubs.GoConstSpecStub" methods=[deleteDefinition] } private ConstDefinitionList ::= ConstDefinition ( ',' ConstDefinition )* ConstDefinition ::= identifier { stubClass="com.goide.stubs.GoConstDefinitionStub" methods=[getGoTypeInner getValue] } LeftHandExprList ::= ExpressionList private ExpressionArgList ::= ExpressionOrTypeWithRecover2 (',' (ExpressionOrTypeWithRecover2 | &')'))* {pin(".*")=1} private ExpressionOrTypeWithRecover2 ::= <> | (!() ExpressionOrLiteralTypeExpr) {recoverWhile=ExpressionListRecover} private ExpressionOrTypeWithRecover ::= ExpressionOrLiteralTypeExpr {recoverWhile=ExpressionListRecover} private ExpressionOrLiteralTypeExpr ::= Expression | LiteralTypeExpr private ExpressionList ::= ExpressionWithRecover (',' (ExpressionWithRecover | &')'))* {pin(".*")=1} private ExpressionWithRecover ::= Expression {recoverWhile=ExpressionListRecover} private ExpressionListRecover ::= !('!' | '!=' | '%' | '%=' | '&&' | '&' | '&=' | '&^' | '&^=' | '(' | ')' | '*' | '*=' | '+' | '++' | '+=' | ',' | '-' | '--' | '-=' | '...' | '/' | '/=' | ':' | ';' | '<' | '<-' | '<<' | '<<=' | '<=' | '' | '=' | '==' | '>' | '>=' | '>>' | '>>=' | '[' | ']' | '^' | '^=' | 'type' | '{' | '|' | '|=' | '||' | '}' | break | case | chan | char | const | continue | decimali | default | defer | else | fallthrough | float | floati | for | func | go | goto | hex | identifier | if | int | interface | map | oct | return | select | string | raw_string | struct | switch | var) TypeDeclaration ::= 'type' ( TypeSpec | '(' TypeSpecs? ')' ) {pin(".*")=1} private TypeSpecs ::= TypeSpec (semi TypeSpec)* semi? {pin=1} TypeSpec ::= SpecType { methods=[getGoTypeInner getMethods shouldGoDeeper identifier="SpecType/identifier"] stubClass="com.goide.stubs.GoTypeSpecStub" } SpecType ::= identifier Type {pin=1 stubClass="com.goide.stubs.GoTypeStub" extends="com.goide.psi.impl.GoTypeImpl" implements=Type} VarDeclaration ::= var ( VarSpec | '(' VarSpecs? ')' ) {pin(".*")=1 methods=[addSpec deleteSpec]} private VarSpecs ::= VarSpec (semi VarSpec)* semi? {pin=1} VarSpec ::= VarDefinitionList ( Type [ '=' ExpressionList ] | '=' ExpressionList ) { pin(".*")=1 methods=[processDeclarations deleteDefinition getRightExpressionsList] stubClass="com.goide.stubs.GoVarSpecStub" } private VarDefinitionList ::= VarDefinition ( ',' VarDefinition )* VarDefinition ::= identifier { methods=[getGoTypeInner getReference getValue] stubClass="com.goide.stubs.GoVarDefinitionStub" } ShortVarDeclaration ::= VarDefinitionList ':=' ExpressionList {pin=2 extends=VarSpec} FunctionDeclaration ::= func identifier Signature BlockWithConsume? { pin=2 stubClass="com.goide.stubs.GoFunctionDeclarationStub" } MethodDeclaration ::= func Receiver identifier Signature BlockWithConsume? { pin=1 stubClass="com.goide.stubs.GoMethodDeclarationStub" methods=[getReceiverType] } Receiver ::= '(' (identifier ReceiverTail | ReceiverTail) ')' { methods=[getGoTypeInner] pin=1 stubClass="com.goide.stubs.GoReceiverStub" } private ReceiverTail ::= Type ','? Literal ::= int | float | floati | decimali | hex | oct | StringLiteral | char StringLiteral ::= string | raw_string { implements = "com.intellij.psi.PsiLanguageInjectionHost" methods = [isValidHost updateText createLiteralTextEscaper getDecodedText] } OperandName ::= ReferenceExpression QualifiedReferenceExpression? {elementType=ReferenceExpression} left QualifiedReferenceExpression ::= '.' identifier {elementType=ReferenceExpression} ReferenceExpression ::= identifier { methods=[getReference getQualifier resolve getReadWriteAccess] extends=Expression} CompositeLit ::= (LiteralTypeExprInner LiteralValue | TypeName LiteralValue) {pin(".*")="LiteralTypeExprInner"} // the brackets are valuable private LiteralTypeExprInner ::= StructType | ArrayOrSliceType | MapType LiteralTypeExpr ::= LiteralTypeExprInner | TypeName LiteralValue ::= (<> | <> | <>) '{' ElementList? '}' {pin=2} private ElementList ::= E ( ',' E? )* private E ::= <> | (!() Element) {recoverWhile=E_recover} private E_recover ::= !('}'|',') Element ::= First [':' Value] {pin(".*")=1} private First ::= Key | <> Key ::= (FieldName &':') | !() Expression // nullability hack for key without reference inside FieldName ::= identifier { methods=[getReference getQualifier resolve] } Value ::= Expression | LiteralValue FunctionLit ::= func Signature Block {pin=1 methods=[processDeclarations]} Expression ::= OrExpr | AndExpr | ConditionalExpr | AddExpr | MulExpr | UnaryExpr | ConversionExpr | MaxGroup | ParenthesesExpr {methods=[getGoType] implements="com.goide.psi.GoTypeOwner"} fake BinaryExpr ::= Expression+ { methods=[left="Expression[0]" right="Expression[1]" getOperator] } OrExpr ::= Expression '||' Expression AndExpr ::= Expression '&&' Expression UnaryExpr ::= UnaryOp Expression {methods=[getOperator]} ConditionalExpr ::= Expression RelOp Expression AddExpr ::= Expression AddOp Expression MulExpr ::= Expression MulOp Expression ParenthesesExpr ::= '(' <> Expression <>')' {pin=1} BuiltinCallExpr ::= ReferenceExpression <> BuiltinArgumentList {pin=2} BuiltinArgumentList ::= '(' [ BuiltinArgsInner ','? ] ')' {pin=1 extends=ArgumentList} private BuiltinArgsInner ::= Type [ ',' BuiltinArgsTail ] | BuiltinArgsTail private BuiltinArgsTail ::= ExpressionList '...'? private MaxGroup ::= CompositeLit | OperandName | BuiltinCallExpr | CallExpr | TypeAssertionExpr | SelectorExpr | IndexOrSliceExpr | Literal | FunctionLit private RelOp ::= '==' | '!=' | '<' | '<=' | '>' | '>=' private AddOp ::= '+' | '-' | '|' | '^' private MulOp ::= '*' | '/' | '%' | '<<' | '>>' | '&' | '&^' private UnaryOp ::= '+' | '-' | '!' | '^' | '*' | '&' | '<-' SelectorExpr ::= Expression '.' !('(' 'type') Expression IndexOrSliceExpr ::= Expression '[' <> (SliceExprBody | IndexExprBody) <> ']' {pin=2 methods = [getExpression getIndices]} private IndexExprBody ::= Expression SliceExprBodyInner? private inner SliceExprBodyInner ::= SliceExprBody private SliceExprBody ::= &':' (':' Expression ':' Expression) | (':' Expression?) TypeAssertionExpr ::= Expression '.' '(' &(!'type') Type ')' CallExpr ::= Expression ArgumentList ArgumentList ::= '(' [ ExpressionArgList '...'? ','? ] ')' {pin=1} ConversionExpr ::= &ConversionPredicate Type ConversionTail private ConversionPredicate ::= ConversionStart | '(' ConversionStart private ConversionTail ::= '(' Expression ','? ')' {pin=1} private ConversionStart ::= '*' | '<-' | '[' | chan | func | interface | map | struct LabeledStatement ::= LabelDefinition ':' Statement? {pin=2} LabelDefinition ::= identifier { stubClass="com.goide.stubs.GoLabelDefinitionStub" // todo: remove when you'll have some spare time } left SendStatement ::= '<-' Expression {pin=1 methods=[getSendExpression]} left AssignmentStatement ::= assign_op ExpressionList {pin=1} IncDecStatement ::= Expression ('++' | '--') {pin=2} assign_op ::= '=' | '+=' | '-=' | '|=' | '^=' | '*=' | '/=' | '%=' | '<<=' | '>>=' | '&=' | '&^=' IfStatement ::= if Condition Block ElseStatement? ElseStatement ::= else (IfStatement | Block) SwitchStatement ::= SwitchStart (TypeSwitchStatement | ExprSwitchStatement) SwitchStart ::= switch left ExprSwitchStatement ::= Condition '{' ExprCaseClause* '}' {pin=2 extends=SwitchStatement} private Condition ::= <> SimpleStatementOpt Expression? <> private SimpleStatementOpt ::= [SimpleStatement ';'?] // todo: remove ? ExprCaseClause ::= !'}' ExprSwitchCase ':' Statements? {pin=1 implements="com.goide.psi.GoCaseClause"} private ExprSwitchCase ::= case ExpressionList | default {pin(".*")=1} left TypeSwitchStatement ::= (TypeSwitchGuard | SimpleStatement ';'? TypeSwitchGuard) '{' ( TypeCaseClause )* '}' {pin=1 extends=SwitchStatement} TypeSwitchGuard ::= [ VarDefinition ':=' ] Expression '.' TypeGuard TypeGuard ::= '(' 'type' ')' {pin=2} TypeCaseClause ::= !'}' TypeSwitchCase ':' Statements? {pin=1 implements="com.goide.psi.GoCaseClause"} private TypeSwitchCase ::= case TypeList | default {pin(".*")=1} TypeList ::= Type ( ',' Type )* ','? TypeListNoPin ::= Type ( ',' Type )* ','? {elementType=TypeList} ForStatement ::= for <> (ForOrRangeClause Block | Block | Expression Block) <> {pin(".*")="for|ForOrRangeClause"} private ForOrRangeClause ::= (ForClause | RangeClause) ForClause ::= SimpleStatement? ';' Expression? ';' SimpleStatement? {methods=[processDeclarations]} RangeClause ::= range Expression | ExpressionsOrVariables range Expression {pin(".*")=1 extends=VarSpec methods=[getRangeExpression getLeftExpressionsList getRightExpressionsList]} private ExpressionsOrVariables ::= ExpressionList '=' | VarDefinitionList ':=' GoStatement ::= go Expression SelectStatement ::= select '{' CommClause* '}' CommClause ::= CommCase ':' Statements? {pin=1} CommCase ::= case ( Expression SendStatement | RecvStatement ) | default {pin(".*")="case"} RecvStatement ::= ExpressionsOrVariables? Expression {pin=0 extends=VarSpec methods=[getRecvExpression getLeftExpressionsList getRightExpressionsList]} ReturnStatement ::= return ExpressionList? LabelRef ::= identifier { methods=[getReference] } BreakStatement ::= break LabelRef? ContinueStatement ::= continue LabelRef? GotoStatement ::= goto LabelRef FallthroughStatement ::= fallthrough DeferStatement ::= defer Expression ================================================ FILE: plan9/build.gradle ================================================ //version '0.10.SNAPSHOT' // //apply plugin: 'java' // //sourceCompatibility = 1.5 // //repositories { // mavenCentral() //} // //dependencies { // testCompile group: 'junit', name: 'junit', version: '4.11' //} ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/lexer/_AsmIntelHighlightingLexer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ /* The following code was generated by JFlex 1.4.3 on 3/26/16 7:41 PM */ package com.plan9.intel.lang.core.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.util.text.CharArrayUtil; import java.io.IOException; import java.io.Reader; import static com.plan9.intel.ide.highlighting.AsmIntelLexerTokens.*; /** * This class is a scanner generated by * JFlex 1.4.3 * on 3/26/16 7:41 PM from the specification file * /Users/zolotov/dev/intellij-plugins/intellij-go/plan9/src/com/plan9/intel/ide/highlighting/AsmIntelHighlightingLexer.flex */ public class _AsmIntelHighlightingLexer implements FlexLexer { /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\3\1\1\1\0\1\2\1\1\22\0\1\3\1\0\1\5"+ "\1\60\1\0\2\12\1\0\1\72\1\72\2\12\1\73\1\12\1\0"+ "\1\4\1\13\1\41\1\42\1\43\1\44\1\45\1\47\1\11\1\37"+ "\1\40\1\16\1\0\1\74\1\0\1\75\2\0\1\26\1\24\1\30"+ "\1\25\1\20\1\31\1\21\1\46\1\35\1\53\1\52\1\22\1\50"+ "\1\33\1\23\1\27\1\54\1\36\1\34\1\17\1\32\1\56\1\51"+ "\1\15\1\55\1\57\3\0\1\12\1\6\1\0\2\10\1\63\1\66"+ "\1\67\1\70\2\6\1\61\2\6\1\64\1\6\1\62\4\6\1\71"+ "\1\6\1\65\2\6\1\14\2\6\1\0\1\12\1\0\1\12\53\0"+ "\1\6\12\0\1\6\1\0\1\6\2\0\1\6\5\0\27\6\1\0"+ "\37\6\1\0\u01ca\6\4\0\14\6\16\0\5\6\7\0\1\6\1\0"+ "\1\6\201\0\5\6\1\0\2\6\2\0\4\6\10\0\1\6\1\0"+ "\3\6\1\0\1\6\1\0\24\6\1\0\123\6\1\0\213\6\10\0"+ "\236\6\11\0\46\6\2\0\1\6\7\0\47\6\110\0\33\6\5\0"+ "\3\6\55\0\53\6\25\0\12\7\4\0\2\6\1\0\143\6\1\0"+ "\1\6\17\0\2\6\7\0\2\6\12\7\3\6\2\0\1\6\20\0"+ "\1\6\1\0\36\6\35\0\131\6\13\0\1\6\16\0\12\7\41\6"+ "\11\0\2\6\4\0\1\6\5\0\26\6\4\0\1\6\11\0\1\6"+ "\3\0\1\6\27\0\31\6\107\0\1\6\1\0\13\6\127\0\66\6"+ "\3\0\1\6\22\0\1\6\7\0\12\6\4\0\12\7\1\0\7\6"+ "\1\0\7\6\5\0\10\6\2\0\2\6\2\0\26\6\1\0\7\6"+ "\1\0\1\6\3\0\4\6\3\0\1\6\20\0\1\6\15\0\2\6"+ "\1\0\3\6\4\0\12\7\2\6\23\0\6\6\4\0\2\6\2\0"+ "\26\6\1\0\7\6\1\0\2\6\1\0\2\6\1\0\2\6\37\0"+ "\4\6\1\0\1\6\7\0\12\7\2\0\3\6\20\0\11\6\1\0"+ "\3\6\1\0\26\6\1\0\7\6\1\0\2\6\1\0\5\6\3\0"+ "\1\6\22\0\1\6\17\0\2\6\4\0\12\7\25\0\10\6\2\0"+ "\2\6\2\0\26\6\1\0\7\6\1\0\2\6\1\0\5\6\3\0"+ "\1\6\36\0\2\6\1\0\3\6\4\0\12\7\1\0\1\6\21\0"+ "\1\6\1\0\6\6\3\0\3\6\1\0\4\6\3\0\2\6\1\0"+ "\1\6\1\0\2\6\3\0\2\6\3\0\3\6\3\0\14\6\26\0"+ "\1\6\25\0\12\7\25\0\10\6\1\0\3\6\1\0\27\6\1\0"+ "\12\6\1\0\5\6\3\0\1\6\32\0\2\6\6\0\2\6\4\0"+ "\12\7\25\0\10\6\1\0\3\6\1\0\27\6\1\0\12\6\1\0"+ "\5\6\3\0\1\6\40\0\1\6\1\0\2\6\4\0\12\7\1\0"+ "\2\6\22\0\10\6\1\0\3\6\1\0\51\6\2\0\1\6\20\0"+ "\1\6\21\0\2\6\4\0\12\7\12\0\6\6\5\0\22\6\3\0"+ "\30\6\1\0\11\6\1\0\1\6\2\0\7\6\72\0\60\6\1\0"+ "\2\6\14\0\7\6\11\0\12\7\47\0\2\6\1\0\1\6\2\0"+ "\2\6\1\0\1\6\2\0\1\6\6\0\4\6\1\0\7\6\1\0"+ "\3\6\1\0\1\6\1\0\1\6\2\0\2\6\1\0\4\6\1\0"+ "\2\6\11\0\1\6\2\0\5\6\1\0\1\6\11\0\12\7\2\0"+ "\4\6\40\0\1\6\37\0\12\7\26\0\10\6\1\0\44\6\33\0"+ "\5\6\163\0\53\6\24\0\1\6\12\7\6\0\6\6\4\0\4\6"+ "\3\0\1\6\3\0\2\6\7\0\3\6\4\0\15\6\14\0\1\6"+ "\1\0\12\7\6\0\46\6\1\0\1\6\5\0\1\6\2\0\53\6"+ "\1\0\u014d\6\1\0\4\6\2\0\7\6\1\0\1\6\1\0\4\6"+ "\2\0\51\6\1\0\4\6\2\0\41\6\1\0\4\6\2\0\7\6"+ "\1\0\1\6\1\0\4\6\2\0\17\6\1\0\71\6\1\0\4\6"+ "\2\0\103\6\45\0\20\6\20\0\125\6\14\0\u026c\6\2\0\21\6"+ "\1\0\32\6\5\0\113\6\25\0\15\6\1\0\4\6\16\0\22\6"+ "\16\0\22\6\16\0\15\6\1\0\3\6\17\0\64\6\43\0\1\6"+ "\4\0\1\6\3\0\12\7\46\0\12\7\6\0\130\6\10\0\51\6"+ "\1\0\1\6\5\0\106\6\12\0\35\6\51\0\12\7\36\6\2\0"+ "\5\6\13\0\54\6\25\0\7\6\10\0\12\7\46\0\27\6\11\0"+ "\65\6\53\0\12\7\6\0\12\7\15\0\1\6\135\0\57\6\21\0"+ "\7\6\4\0\12\7\51\0\36\6\15\0\2\6\12\7\54\6\32\0"+ "\44\6\34\0\12\7\3\0\3\6\12\7\44\6\153\0\4\6\1\0"+ "\4\6\3\0\2\6\11\0\300\6\100\0\u0116\6\2\0\6\6\2\0"+ "\46\6\2\0\6\6\2\0\10\6\1\0\1\6\1\0\1\6\1\0"+ "\1\6\1\0\37\6\2\0\65\6\1\0\7\6\1\0\1\6\3\0"+ "\3\6\1\0\7\6\3\0\4\6\2\0\6\6\4\0\15\6\5\0"+ "\3\6\1\0\7\6\164\0\1\6\15\0\1\6\20\0\15\6\145\0"+ "\1\6\4\0\1\6\2\0\12\6\1\0\1\6\3\0\5\6\6\0"+ "\1\6\1\0\1\6\1\0\1\6\1\0\4\6\1\0\13\6\2\0"+ "\4\6\5\0\5\6\4\0\1\6\64\0\2\6\220\0\1\6\u09ea\0"+ "\57\6\1\0\57\6\1\0\205\6\6\0\4\6\3\0\2\6\14\0"+ "\46\6\1\0\1\6\5\0\1\6\2\0\70\6\7\0\1\6\20\0"+ "\27\6\11\0\7\6\1\0\7\6\1\0\7\6\1\0\7\6\1\0"+ "\7\6\1\0\7\6\1\0\7\6\1\0\7\6\120\0\1\6\u01d5\0"+ "\2\6\52\0\5\6\5\0\2\6\4\0\126\6\6\0\3\6\1\0"+ "\132\6\1\0\4\6\5\0\51\6\3\0\136\6\21\0\33\6\65\0"+ "\20\6\u0200\0\u19b6\6\112\0\u51cd\6\63\0\u048d\6\103\0\56\6\2\0"+ "\u010d\6\3\0\20\6\12\7\2\6\24\0\57\6\20\0\31\6\10\0"+ "\106\6\61\0\11\6\2\0\147\6\2\0\4\6\1\0\4\6\14\0"+ "\13\6\115\0\12\6\1\0\3\6\1\0\4\6\1\0\27\6\35\0"+ "\64\6\16\0\62\6\34\0\12\7\30\0\6\6\3\0\1\6\4\0"+ "\12\7\34\6\12\0\27\6\31\0\35\6\7\0\57\6\34\0\1\6"+ "\12\7\46\0\51\6\27\0\3\6\1\0\10\6\4\0\12\7\6\0"+ "\27\6\3\0\1\6\5\0\60\6\1\0\1\6\3\0\2\6\2\0"+ "\5\6\2\0\1\6\1\0\1\6\30\0\3\6\2\0\13\6\7\0"+ "\3\6\14\0\6\6\2\0\6\6\2\0\6\6\11\0\7\6\1\0"+ "\7\6\221\0\43\6\15\0\12\7\6\0\u2ba4\6\14\0\27\6\4\0"+ "\61\6\u2104\0\u016e\6\2\0\152\6\46\0\7\6\14\0\5\6\5\0"+ "\1\6\1\0\12\6\1\0\15\6\1\0\5\6\1\0\1\6\1\0"+ "\2\6\1\0\2\6\1\0\154\6\41\0\u016b\6\22\0\100\6\2\0"+ "\66\6\50\0\14\6\164\0\5\6\1\0\207\6\23\0\12\7\7\0"+ "\32\6\6\0\32\6\13\0\131\6\3\0\6\6\2\0\6\6\2\0"+ "\6\6\2\0\3\6\43\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\2\2\1\3\1\1\1\4\1\5\1\3"+ "\1\5\27\4\1\1\1\6\1\7\2\1\1\10\1\0"+ "\1\11\1\12\1\0\1\13\10\4\1\13\22\4\1\13"+ "\5\4\1\13\11\4\1\14\6\4\1\13\16\4\1\14"+ "\4\4\1\13\2\4\1\13\10\4\1\14\1\4\1\14"+ "\32\4\7\15\1\4\1\15\6\4\4\0\1\16\10\4"+ "\1\13\2\4\1\17\145\4\1\17\10\4\1\15\4\4"+ "\1\17\1\15\22\4\5\0\3\4\1\20\3\4\1\15"+ "\14\4\1\15\57\4\1\15\26\4\4\15\3\4\2\15"+ "\6\4\5\0\4\4\1\21\11\4\2\15\32\4\3\15"+ "\1\4\1\15\2\4\1\15\23\4\3\0\1\22\1\4"+ "\1\15\7\4\1\15\11\4\1\15\11\4\1\0\35\4"; private static int [] zzUnpackAction() { int [] result = new int[570]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\76\0\174\0\76\0\272\0\370\0\u0136\0\u0174"+ "\0\76\0\u01b2\0\u01f0\0\u022e\0\u026c\0\u02aa\0\u02e8\0\u0326"+ "\0\u0364\0\u03a2\0\u03e0\0\u041e\0\u045c\0\u049a\0\u04d8\0\u0516"+ "\0\u0554\0\u0592\0\u05d0\0\u060e\0\u064c\0\u068a\0\u06c8\0\u0706"+ "\0\u0744\0\u0782\0\76\0\76\0\u07c0\0\u07fe\0\u083c\0\370"+ "\0\76\0\76\0\u087a\0\u0136\0\u08b8\0\u08f6\0\u0934\0\u0972"+ "\0\u09b0\0\u09ee\0\u0a2c\0\u0a6a\0\u0aa8\0\u0ae6\0\u0b24\0\u0b62"+ "\0\u0ba0\0\u0bde\0\u0c1c\0\u0c5a\0\u0c98\0\u0cd6\0\u0d14\0\u0d52"+ "\0\u0d90\0\u0dce\0\u0e0c\0\u0e4a\0\u0e88\0\u0ec6\0\u0f04\0\u0f42"+ "\0\u0f80\0\u0fbe\0\u0ffc\0\u103a\0\u1078\0\u10b6\0\u10f4\0\u1132"+ "\0\u1170\0\u11ae\0\u11ec\0\u122a\0\u1268\0\u12a6\0\u12e4\0\u1322"+ "\0\u1360\0\u139e\0\u13dc\0\u141a\0\u1458\0\u1496\0\u14d4\0\u1512"+ "\0\u1550\0\u158e\0\u15cc\0\u160a\0\u1648\0\u1686\0\u16c4\0\u1702"+ "\0\u1740\0\u177e\0\u17bc\0\u17fa\0\u1838\0\u1876\0\u18b4\0\u18f2"+ "\0\u1930\0\u196e\0\u19ac\0\u19ea\0\u1a28\0\u1a66\0\u1aa4\0\u1ae2"+ "\0\u1b20\0\u1b5e\0\u1b9c\0\u1bda\0\u1c18\0\u1c56\0\u1c94\0\u1cd2"+ "\0\u0f42\0\u1d10\0\u1d4e\0\u1d8c\0\u1dca\0\u1e08\0\u1e46\0\u1e84"+ "\0\u1ec2\0\u1f00\0\u1f3e\0\u1f7c\0\u1fba\0\u1ff8\0\u2036\0\u2074"+ "\0\u20b2\0\u20f0\0\u212e\0\u216c\0\u21aa\0\u21e8\0\u2226\0\u2264"+ "\0\u22a2\0\u22e0\0\u231e\0\u1550\0\u235c\0\u239a\0\u23d8\0\u2416"+ "\0\u2454\0\u2492\0\u24d0\0\u0136\0\u250e\0\u254c\0\u258a\0\u25c8"+ "\0\u2606\0\u2644\0\u2682\0\u26c0\0\u26fe\0\u273c\0\u087a\0\u277a"+ "\0\u27b8\0\u27f6\0\u2834\0\u2872\0\u28b0\0\u28ee\0\u292c\0\u296a"+ "\0\u29a8\0\u29e6\0\u0136\0\u2a24\0\u2a62\0\u2aa0\0\u2ade\0\u2b1c"+ "\0\u2b5a\0\u2b98\0\u2bd6\0\u2c14\0\u2c52\0\u2c90\0\u2cce\0\u2d0c"+ "\0\u2d4a\0\u2d88\0\u2dc6\0\u2e04\0\u2416\0\u2e42\0\u2e80\0\u2ebe"+ "\0\u2efc\0\u2f3a\0\u2f78\0\u2fb6\0\u2ff4\0\u3032\0\u3070\0\u30ae"+ "\0\u30ec\0\u312a\0\u3168\0\u31a6\0\u31e4\0\u3222\0\u3260\0\u329e"+ "\0\u32dc\0\u331a\0\u3358\0\u3396\0\u33d4\0\u3412\0\u3450\0\u348e"+ "\0\u34cc\0\u350a\0\u3548\0\u3586\0\u35c4\0\u3602\0\u3640\0\u367e"+ "\0\u36bc\0\u36fa\0\u3738\0\u3776\0\u37b4\0\u37f2\0\u3830\0\u386e"+ "\0\u38ac\0\u38ea\0\u3928\0\u3966\0\u39a4\0\u39e2\0\u3a20\0\u3a5e"+ "\0\u3a9c\0\u3ada\0\u3b18\0\u3b56\0\u3b94\0\u3bd2\0\u3c10\0\u3c4e"+ "\0\u3c8c\0\u3cca\0\u3d08\0\u3d46\0\u3d84\0\u3dc2\0\u3e00\0\u3e3e"+ "\0\u3e7c\0\u3eba\0\u3ef8\0\u3f36\0\u3f74\0\u3fb2\0\u3ff0\0\u402e"+ "\0\u406c\0\u40aa\0\u40e8\0\u4126\0\u4164\0\u41a2\0\u41e0\0\u421e"+ "\0\u425c\0\u429a\0\u42d8\0\u4316\0\u4354\0\u4392\0\u43d0\0\u440e"+ "\0\u444c\0\u16c4\0\u448a\0\u44c8\0\u4506\0\u4544\0\u4582\0\u45c0"+ "\0\u45fe\0\u463c\0\u467a\0\u46b8\0\u46f6\0\u4734\0\u4772\0\u47b0"+ "\0\u47ee\0\u482c\0\u486a\0\u48a8\0\u48e6\0\u4924\0\u4962\0\u49a0"+ "\0\u49de\0\u4a1c\0\u4a5a\0\u4a98\0\u4ad6\0\u4b14\0\u4b52\0\u4b90"+ "\0\u4bce\0\u4c0c\0\u0136\0\u4c4a\0\u4c88\0\u4cc6\0\u4d04\0\u4d42"+ "\0\u4d80\0\u4dbe\0\u4dfc\0\u4e3a\0\u4e78\0\u4eb6\0\u4ef4\0\u4f32"+ "\0\u4f70\0\u4fae\0\u4fec\0\u502a\0\u5068\0\u50a6\0\u50e4\0\u5122"+ "\0\u5160\0\u519e\0\u51dc\0\u521a\0\u5258\0\u5296\0\u52d4\0\u5312"+ "\0\u45c0\0\u5350\0\u538e\0\u53cc\0\u540a\0\u5448\0\u5486\0\u54c4"+ "\0\u5502\0\u5540\0\u557e\0\u55bc\0\u55fa\0\u5638\0\u5676\0\u56b4"+ "\0\u56f2\0\u5730\0\u576e\0\u57ac\0\u57ea\0\u5828\0\u5866\0\u58a4"+ "\0\u58e2\0\u5920\0\u595e\0\u599c\0\u59da\0\u5a18\0\u5a56\0\u5a94"+ "\0\u5ad2\0\u5b10\0\u5b4e\0\u5b8c\0\u5bca\0\u5c08\0\u5c46\0\u5c84"+ "\0\u5cc2\0\u5d00\0\u5d3e\0\u5d7c\0\u5dba\0\u5df8\0\u235c\0\u5e36"+ "\0\u23d8\0\u5e74\0\u5eb2\0\u5ef0\0\u5f2e\0\u5f6c\0\u5faa\0\u5fe8"+ "\0\u6026\0\u6064\0\u60a2\0\u60e0\0\u611e\0\u615c\0\u619a\0\u61d8"+ "\0\u6216\0\u6254\0\u6292\0\u62d0\0\u630e\0\u634c\0\u638a\0\u63c8"+ "\0\u6406\0\u6444\0\u6482\0\u64c0\0\u64fe\0\u653c\0\u657a\0\u65b8"+ "\0\u65f6\0\u6634\0\u0136\0\u6672\0\u66b0\0\u66ee\0\u672c\0\u676a"+ "\0\u67a8\0\u67e6\0\u6824\0\u6862\0\u3032\0\u68a0\0\u68de\0\u691c"+ "\0\u695a\0\u6998\0\u69d6\0\u6a14\0\u6a52\0\u6a90\0\u6ace\0\u6b0c"+ "\0\u6b4a\0\u6b88\0\u6bc6\0\u6c04\0\u6c42\0\u6c80\0\u6cbe\0\u6cfc"+ "\0\u6d3a\0\u6d78\0\u6db6\0\u6df4\0\u6e32\0\u6e70\0\u6eae\0\u6eec"+ "\0\u3e7c\0\u5c08\0\u6f2a\0\u6f68\0\u6fa6\0\u6fe4\0\u7022\0\u7060"+ "\0\u709e\0\u70dc\0\u711a\0\u7158\0\u7196\0\u71d4\0\u7212\0\u7250"+ "\0\u728e\0\u72cc\0\u730a\0\u60e0\0\u7348\0\u7386\0\u73c4\0\u7402"+ "\0\u7440\0\u747e\0\u74bc\0\u74fa\0\u7538\0\u7576\0\76\0\u75b4"+ "\0\u75f2\0\u7630\0\u766e\0\u76ac\0\u76ea\0\u7728\0\u7766\0\u77a4"+ "\0\u5920\0\u77e2\0\u7820\0\u785e\0\u789c\0\u78da\0\u7918\0\u7956"+ "\0\u7994\0\u79d2\0\u7a10\0\u7a4e\0\u7a8c\0\u7aca\0\u7b08\0\u7b46"+ "\0\u7b84\0\u7bc2\0\u7c00\0\u7c3e\0\u7c7c\0\u7cba\0\u7cf8\0\u7d36"+ "\0\u7d74\0\u7db2\0\u7df0\0\u7e2e\0\u7e6c\0\u7eaa\0\u7ee8\0\u7f26"+ "\0\u7f64\0\u7fa2\0\u7fe0\0\u801e\0\u805c\0\u809a\0\u80d8\0\u8116"+ "\0\u8154\0\u8192\0\u81d0\0\u820e\0\u824c\0\u828a\0\u82c8\0\u8306"+ "\0\u8344\0\u8382"; private static int [] zzUnpackRowMap() { int [] result = new int[570]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\2\1\3\1\4\1\3\1\5\1\6\1\7\1\2"+ "\1\7\1\10\1\11\1\12\1\7\1\13\1\2\1\14"+ "\1\15\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ "\1\25\1\26\1\27\1\30\1\31\1\32\1\33\7\10"+ "\1\34\1\10\1\35\1\36\1\7\1\37\1\40\1\7"+ "\1\41\1\7\1\42\11\7\1\43\1\44\1\45\1\46"+ "\77\0\1\3\1\0\1\3\76\0\1\47\71\0\5\50"+ "\1\51\70\50\6\0\4\7\1\0\3\7\1\52\41\7"+ "\1\0\11\7\15\0\1\10\1\0\1\10\23\0\7\10"+ "\1\0\1\10\42\0\2\53\66\0\3\7\1\54\1\0"+ "\1\54\2\7\1\52\1\55\1\56\1\7\1\57\1\60"+ "\1\61\1\7\1\62\1\7\1\63\5\7\1\64\2\54"+ "\1\65\4\54\1\7\1\54\10\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\66\1\7\1\67"+ "\3\7\1\70\7\7\1\71\21\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\72\1\54\13\7"+ "\1\73\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\74\2\7\1\75\6\7\1\54\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\7"+ "\1\76\2\7\1\77\1\7\1\100\1\101\2\7\1\102"+ "\2\7\1\103\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\13\7\1\104\3\7\1\105\21\7\1\0"+ "\11\7\12\0\4\7\1\0\2\7\1\54\1\52\1\106"+ "\2\7\1\54\1\107\3\7\1\110\4\7\1\111\11\7"+ "\1\54\6\7\1\112\2\7\1\0\11\7\12\0\4\7"+ "\1\0\2\7\1\54\1\52\1\7\1\113\1\7\1\54"+ "\3\7\1\114\3\7\1\115\1\7\1\54\1\116\1\71"+ "\7\7\1\54\11\7\1\0\11\7\12\0\4\7\1\0"+ "\2\7\1\54\1\52\1\7\1\117\1\7\1\54\2\7"+ "\1\120\1\121\4\7\1\122\2\7\1\123\7\7\1\54"+ "\11\7\1\0\11\7\12\0\4\7\1\0\2\7\1\124"+ "\1\52\1\7\1\125\2\7\1\126\2\7\1\127\1\7"+ "\1\130\1\131\1\132\1\7\1\133\1\134\1\135\11\7"+ "\1\136\7\7\1\0\11\7\12\0\4\7\1\0\2\7"+ "\1\54\1\52\3\7\1\137\1\140\1\7\1\141\1\142"+ "\1\143\4\7\1\54\1\7\1\144\7\7\1\54\1\7"+ "\1\145\1\146\2\7\1\147\1\7\1\150\1\7\1\0"+ "\11\7\12\0\3\7\1\54\1\0\1\54\1\7\1\151"+ "\1\52\1\152\2\7\1\153\2\7\1\154\1\155\1\156"+ "\1\157\1\160\1\161\1\162\1\163\1\164\1\165\2\7"+ "\1\54\1\166\3\54\1\7\1\54\1\167\4\7\1\170"+ "\2\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\11\7\1\171\2\7\1\172\24\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\173\2\7\1\174"+ "\34\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\175\1\176\3\7\1\177\1\7\1\200\1\201\1\202"+ "\1\102\1\203\1\7\1\54\1\110\10\7\1\204\2\7"+ "\1\205\2\7\1\206\1\207\2\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\6\7\1\210\5\7\1\211"+ "\2\7\1\212\11\7\1\213\7\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\214\2\7\1\215"+ "\1\7\1\216\2\7\1\217\3\7\1\220\2\7\2\110"+ "\1\221\16\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\222\35\7\1\0\11\7\12\0\3\7"+ "\1\54\1\0\1\54\2\7\1\52\4\7\1\223\2\7"+ "\1\224\2\7\1\102\1\225\1\7\1\226\1\227\3\7"+ "\5\54\1\7\1\54\10\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\4\7\1\230\1\231\1\7\1\232"+ "\7\7\1\233\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\234\1\235\1\236\1\237\1\240"+ "\1\7\1\240\1\241\1\242\2\7\1\243\1\244\11\7"+ "\1\245\1\7\1\246\6\7\1\244\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\13\7\1\247\25\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\7\1\250"+ "\6\7\1\251\27\7\1\252\1\0\11\7\65\0\1\253"+ "\3\0\1\254\1\255\1\256\102\0\1\11\76\0\1\11"+ "\1\47\1\0\74\47\10\0\2\257\1\0\1\257\4\0"+ "\1\257\3\0\3\257\1\0\2\257\5\0\7\257\1\0"+ "\1\257\13\0\1\257\2\0\3\257\13\0\4\7\1\0"+ "\3\7\1\52\1\7\1\152\37\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\146\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\7\7\1\222"+ "\31\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\17\7\1\105\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\260\37\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\5\7\1\261\1\262\2\7"+ "\1\263\27\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\27\7\1\264\11\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\265\37\7\1\0\11\7"+ "\12\0\4\7\1\0\1\54\2\7\1\52\22\7\5\54"+ "\12\7\1\0\11\7\12\0\4\7\1\0\2\7\1\266"+ "\1\52\15\7\1\267\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\270\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\1\271\23\7"+ "\1\0\11\7\12\0\3\7\1\54\1\0\1\54\2\7"+ "\1\52\22\7\5\54\1\7\1\54\10\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\272\5\7\1\273"+ "\32\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\31\7\1\274\7\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\4\7\1\275\34\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\276\40\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\277\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\4\7"+ "\1\300\1\7\1\301\2\7\1\302\2\7\1\303\24\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\276"+ "\30\7\1\304\7\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\15\7\1\222\1\7\1\305\7\7\1\306"+ "\11\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\7\1\307\37\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\305\35\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\310\40\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\244\1\7"+ "\1\244\2\7\1\311\21\7\1\244\2\7\1\244\3\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\244\5\7\1\312\3\7\1\312\1\7\1\312\12\7"+ "\1\244\2\7\1\244\3\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\13\7\1\313\25\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\54\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\12\7"+ "\1\312\4\7\1\312\12\7\1\314\6\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\315\40\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\11\7\1\316"+ "\27\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\317\6\7\1\244\5\7\1\244\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\10\7\1\320\30\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\5\7"+ "\1\54\31\7\1\321\1\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\322\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\6\7\1\321\2\7"+ "\1\316\22\7\1\323\4\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\2\244\5\7\1\244\13\7"+ "\1\244\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\6\7\1\324\32\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\325\30\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\4\7\1\326\34\7"+ "\1\0\11\7\12\0\4\7\1\0\2\7\1\327\1\52"+ "\41\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\10\7\1\330\6\7\1\244\21\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\6\7\1\331\2\7\1\332"+ "\1\7\1\333\1\334\22\7\1\335\1\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\336\2\7"+ "\1\337\22\7\1\340\7\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\7\7\1\341\1\342\1\343\2\7"+ "\1\344\1\345\1\7\1\346\3\7\1\347\5\7\1\350"+ "\7\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\14\7\1\351\1\352\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\353\3\7\1\354\3\7"+ "\1\355\3\7\1\356\7\7\1\357\2\7\1\360\6\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\14\7"+ "\1\361\6\7\1\362\15\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\363\37\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\4\7\1\364\2\7"+ "\1\365\3\7\1\366\2\7\1\367\22\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\274\5\7\1\244"+ "\2\7\1\244\4\7\1\244\22\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\31\7\1\370\7\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\35\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\371\35\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\13\7\1\372\25\7\1\0\11\7\12\0"+ "\3\7\1\54\1\0\1\54\2\7\1\52\11\7\1\373"+ "\6\7\2\54\1\65\4\54\1\7\1\54\10\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\4\7\1\374"+ "\3\7\1\375\1\244\27\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\244\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\4\7\1\244\34\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\376"+ "\40\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\377\6\7\1\u0100\1\7\1\u0101\3\7\1\u0102\1\7"+ "\1\u0103\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\15\7\1\222\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\u0104\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\7\1\u0105\14\7"+ "\1\u0106\22\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\5\7\1\274\1\u0107\32\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\u0108\6\7\1\u0109\7\7"+ "\1\u010a\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\u010b\1\u010c\22\7\1\274\1\7\1\u010d"+ "\7\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\17\7\1\u010e\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\11\7\1\u010f\2\7\1\u0110\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\4\7\1\u0111"+ "\34\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\u0112\6\7\1\u0113\1\7\1\u0114\1\7\1\u0115\2\7"+ "\1\u0116\16\7\1\u0117\3\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\14\7\1\u0118\24\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\14\7\1\u0119\1\u011a"+ "\23\7\1\0\11\7\12\0\4\7\1\0\2\7\1\u011b"+ "\1\52\41\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\4\7\1\u011c\6\7\1\u011d\25\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\u011e\35\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\4\7"+ "\1\140\34\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\u011f\30\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\u0120\1\316\36\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\316\7\7"+ "\1\u0121\1\7\1\u0122\2\7\1\u0123\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\4\7\1\301\1\7"+ "\1\244\2\7\1\244\4\7\1\244\12\7\1\304\7\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\u0124"+ "\40\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\5\7\1\316\33\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\316\13\7\1\316\7\7\1\306"+ "\11\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\7\7\1\301\31\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\5\7\1\321\33\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\316\7\7\1\u0125"+ "\3\7\1\316\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\7\7\1\u0126\31\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\17\7\1\u0127\21\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\15\7\1\u0128"+ "\23\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\276\15\7\1\u0129\22\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\u012a\2\7\1\244\1\7\1\244"+ "\3\7\1\316\3\7\1\u012b\14\7\1\244\4\7\1\u012c"+ "\1\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\7\1\u012d\37\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\13\7\1\u012e\25\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\u012f\7\7\1\u0130\30\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\316\2\7\1\u0131\4\7\1\u0132\3\7\1\316\21\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\u0133"+ "\7\7\1\u0134\20\7\1\u0135\7\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\316\4\7\1\u0136"+ "\6\7\1\316\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\31\7\1\244\3\7\1\u0137\3\7\1\0"+ "\11\7\12\0\4\7\1\0\1\110\2\7\1\52\22\7"+ "\5\110\12\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\244\40\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\6\7\1\315\30\7\1\u0138\1\7\1\0"+ "\11\7\12\0\4\7\1\0\2\7\1\u0139\1\52\15\7"+ "\1\u013a\23\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\321\35\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\32\7\1\54\6\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\14\7\1\u0139\24\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\17\7"+ "\1\146\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\16\7\1\u013b\22\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\16\7\1\222\22\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\u013c\21\7"+ "\1\u0135\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\2\244\37\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\2\244\2\7\1\244\10\7\1\244\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\11\7"+ "\1\244\3\7\1\244\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\244\37\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\7\1\244\1\7"+ "\2\244\4\7\1\244\3\7\1\244\23\7\1\0\11\7"+ "\12\0\4\7\1\0\2\7\1\u013d\1\52\11\7\1\244"+ "\3\7\1\244\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\244\2\240\1\244\1\240\1\7"+ "\1\240\2\244\3\7\1\244\22\7\1\244\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\2\244\22\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\273\5\7\1\244\22\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\7\7\1\146\31\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\17\7\1\u013e\21\7"+ "\1\0\11\7\12\0\4\7\1\0\2\7\1\124\1\52"+ "\1\55\4\7\1\u013f\1\7\1\56\1\7\1\u0140\17\7"+ "\1\u0141\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\u0142\37\7\1\0\11\7\66\0\1\u0143"+ "\5\0\1\u0144\67\0\1\u0144\102\0\1\u0145\70\0\1\u0146"+ "\1\0\1\u0147\17\0\4\7\1\0\3\7\1\52\2\7"+ "\1\u0148\36\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\4\7\1\u0117\34\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\316\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\35\7\1\u0149\3\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\2\7"+ "\1\316\36\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\u014a\35\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\u014b\40\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\316\40\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\u014c\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\33\7"+ "\1\54\5\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\326\37\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\244\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\u014d\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\17\7"+ "\1\54\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\244\26\7\1\244\2\7\1\244\1\7"+ "\1\u014e\1\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\u014f\30\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\316\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\33\7\1\244\5\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\2\7"+ "\1\244\36\7\1\0\11\7\12\0\4\7\1\0\2\7"+ "\1\u0150\1\52\41\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\244\26\7\1\244\6\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\12\7\1\244"+ "\26\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\14\7\1\u0151\24\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\244\1\7\1\244\7\7\1\u012b"+ "\14\7\1\244\6\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\6\7\1\244\6\7\1\244\23\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\3\7\1\244"+ "\26\7\1\244\2\7\1\244\3\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\u0152\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\7\7\1\u0153"+ "\31\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\244\1\7\1\244\24\7\1\244\2\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\7\7\1\u014b\31\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\4\7\1\u0154\34\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\244\1\7\1\244"+ "\2\7\1\311\4\7\1\311\14\7\1\244\2\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\7\1\u0155\4\7\1\u0156\7\7\1\u0134\14\7\1\u0157"+ "\5\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\15\7\1\u0111\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\244\1\7\1\244\2\7\1\311"+ "\3\7\1\u0158\15\7\1\244\2\7\1\244\3\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\3\7\1\244"+ "\35\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\17\7\1\244\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\u0159\40\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\244\3\7\1\305\2\7"+ "\1\312\17\7\1\244\2\7\1\244\3\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\6\7\1\u015a\32\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\33\7"+ "\1\u015b\5\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\15\7\1\315\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\u015c\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\2\7\1\u015d\36\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\31\7"+ "\1\u015e\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\7\7\1\u015f\31\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\u0160\30\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\6\7\1\146\2\7"+ "\1\u0161\27\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\14\7\1\344\24\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\31\7\1\u0162\7\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\u0163\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\13\7"+ "\1\u0164\25\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\11\7\1\u0165\3\7\1\u0166\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\16\7\1\u0167\22\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\7\7"+ "\1\u0168\3\7\1\325\2\7\1\u0169\22\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\10\7\1\u016a\30\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\27\7"+ "\1\330\11\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\u016b\35\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\u016c\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\u015a\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\u016b\3\7\1\305\31\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\13\7\1\u016d\25\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\123\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\15\7"+ "\1\u016e\23\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\12\7\1\u0167\26\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\12\7\1\u016f\26\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\37\7\1\u0170\1\7"+ "\1\0\11\7\12\0\4\7\1\0\2\7\1\u0171\1\52"+ "\6\7\1\u0172\32\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\u0173\35\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\u0171\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\16\7\1\u0174"+ "\22\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\273\35\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\16\7\1\146\22\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\24\7\1\u0175\14\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\37\7\1\u0176"+ "\1\7\1\0\11\7\12\0\4\7\1\0\2\7\1\u0177"+ "\1\52\3\7\1\244\1\7\1\244\2\7\1\311\4\7"+ "\1\u0178\14\7\1\244\2\7\1\244\3\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\u0179\7\7\1\u017a"+ "\4\7\1\u017b\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\17\7\1\u017c\21\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\31\7\1\244\7\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\27\7\1\146"+ "\11\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\7\7\1\u017d\31\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\15\7\1\u017e\23\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\u017f\1\7\1\u0180"+ "\4\7\1\u0181\1\u0182\10\7\1\244\15\7\1\244\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\11\7\1\u0183"+ "\27\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\37\7\1\u0184\1\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\6\7\1\u0185\32\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\7\7\1\u0169\31\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\u0108\40\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\7"+ "\1\u0186\37\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\u0168\37\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\244\13\7\1\u0187\7\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\4\7"+ "\1\u0188\34\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\315\37\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\4\7\1\u0189\34\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\11\7\1\u018a\27\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\244\30\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\u017f\7\7\1\u0182\3\7\1\u0182\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\37\7"+ "\1\315\1\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\7\7\1\u018b\31\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\5\7\1\u0184\33\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\14\7\1\u018c\24\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\17\7"+ "\1\222\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\11\7\1\u0183\4\7\1\222\22\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\6\7\1\u018d\32\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\124"+ "\40\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\31\7\1\u018e\7\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\37\7\1\u018f\1\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u0185\35\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\23\7\1\u0190"+ "\15\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\11\7\1\u0191\27\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\6\7\1\u0192\32\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\u0193\16\7\1\u0194\21\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\17\7"+ "\1\u0195\21\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\u0196\30\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\141\1\u0197\1\u0198\1\u0199"+ "\3\7\1\u019a\1\u0199\2\7\1\315\12\7\1\u0181\1\7"+ "\1\u0181\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\12\7\1\u0158\26\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\u019b\30\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\u0139\40\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\11\7\1\u019c"+ "\5\7\1\u019d\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\37\7\1\316\1\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\244\1\7\1\244"+ "\24\7\1\244\6\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\u019e\2\7\1\244\32\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\312\40\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\u019f\35\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\12\7\1\312\26\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\14\7\1\244\24\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\u01a0\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\14\7"+ "\1\u01a1\24\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\15\7\1\u0161\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\31\7\1\u0161\7\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\1\326\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\274\4\7\1\274\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\17\7\1\u01a2\21\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\u01a3\1\u01a4"+ "\1\u01a5\1\u01a6\1\u0158\3\7\1\u0158\1\u01a7\1\u0178\11\7"+ "\1\u01a8\1\7\1\u01a9\1\u01aa\2\7\1\u01ab\3\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\10\7\1\311"+ "\4\7\1\311\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\33\7\1\u01ac\5\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\u01ad\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\10\7\1\u01ae"+ "\30\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\40\7\1\312\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\17\7\1\244\12\7\1\244\6\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\17\7\1\u01af\21\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\31\7"+ "\1\u01b0\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\4\7\1\364\34\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\17\7\1\u01b1\21\7\1\0\11\7"+ "\67\0\1\u01b2\100\0\1\u01b3\77\0\1\u01b4\73\0\1\u01b5"+ "\100\0\1\u01b6\12\0\4\7\1\0\3\7\1\52\16\7"+ "\1\u0169\22\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\13\7\1\u01b7\25\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\u01b8\37\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\1\u01b9\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\u014b\35\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\7\1\312\37\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\141\12\7\1\315\24\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\11\7"+ "\1\u0135\27\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\11\7\1\315\27\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\305\32\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\10\7\1\u01ba\30\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\33\7"+ "\1\u01bb\5\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\14\7\1\u01bc\24\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\u01bc\37\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\7\1\u01bd\37\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\311\30\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\17\7\1\u0182\21\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\244\1\7\1\244\5\7"+ "\1\u01be\1\7\1\u015d\14\7\1\244\2\7\1\244\3\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\13\7"+ "\1\u01bf\1\7\1\u01c0\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\244\1\7\1\244\5\7"+ "\1\u01be\1\244\1\u015d\14\7\1\244\6\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\244\24\7"+ "\1\244\6\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\13\7\1\u01c1\25\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\317\40\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\u01c2\1\u01c3\36\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\11\7"+ "\1\244\27\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\u01c4\30\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\11\7\1\u0161\27\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\u01c5\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\u01c6\30\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\35\7\1\u01c7\3\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\244\2\7\1\244\23\7"+ "\1\244\6\7\1\0\11\7\12\0\4\7\1\0\2\7"+ "\1\244\1\52\41\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\11\7\1\u01c8\27\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\2\244\1\7\1\141"+ "\23\7\1\244\2\7\1\244\3\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\5\7\1\u0182\33\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\12\7\1\u01c9"+ "\26\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\17\7\1\u01ca\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\u01cb\37\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\31\7\1\u01cc\7\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\13\7\1\u01cd"+ "\1\7\1\u0182\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\6\7\1\u01ce\32\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u0182\7\7\1\u01cf"+ "\13\7\1\u01d0\11\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\15\7\1\311\23\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\23\7\1\u01d1\15\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\3\7\1\u0124"+ "\26\7\1\u0124\2\7\1\u0124\3\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\11\7\1\u01d2\27\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\3\7\1\244"+ "\1\7\2\244\6\7\1\244\14\7\1\244\2\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\10\7\1\u01d3\4\7\1\u01d4\23\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u01d5\2\7\1\u01d6"+ "\6\7\1\u01d7\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\u01d8\2\7\1\u01d9\6\7\1\u01da"+ "\17\7\1\u01d8\3\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\7\7\1\u01db\31\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\37\7\1\u01dc\1\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\u01dd\40\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\14\7"+ "\1\u01de\24\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\2\7\1\u01df\11\7\1\u01df\6\7\1\u0197\15\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\16\7"+ "\1\244\22\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\32\7\1\244\6\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\u01e0\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\244\2\7"+ "\1\u01e1\3\7\1\244\4\7\1\u0185\12\7\1\244\6\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\244\2\7\1\u01e1\3\7\1\244\17\7\1\244\6\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\31\7"+ "\1\u01e2\7\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\u01e1\1\7\1\u01e1\1\u01e3\3\7\1\u01e1"+ "\3\7\1\u01e1\13\7\1\u01e1\6\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\37\7\1\u01e4\1\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\31\7\1\u01e5"+ "\7\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\6\7\1\337\32\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\315\35\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\11\7\1\u01e6\27\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\16\7\1\u01e7"+ "\22\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\22\7\1\244\16\7\1\0\11\7\12\0\4\7\1\0"+ "\2\7\1\u01e1\1\52\3\7\1\u01e1\1\7\2\u01e1\3\7"+ "\1\u01e1\17\7\1\u01e1\4\7\1\u01e1\1\7\1\0\11\7"+ "\12\0\4\7\1\0\2\7\1\u01e8\1\52\41\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\33\7\1\u01e9"+ "\5\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\11\7\1\u01ea\27\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\17\7\1\u01bb\21\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\4\7\1\u01eb\34\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\7\7\1\u01ec"+ "\31\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\u01ed\35\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\2\244\13\7\1\244\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\244\5\7"+ "\1\244\3\7\1\244\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\2\7\1\274\36\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\u01ee\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\1\7"+ "\1\222\37\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\303\30\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\244\1\7\1\244\16\7"+ "\1\141\5\7\1\244\2\7\1\244\3\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\u01ef\40\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\6\7\1\u0139"+ "\32\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\u0136\40\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\10\7\1\311\16\7\1\u01f0\5\7\1\u01f1\3\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\7\7"+ "\1\244\3\7\1\244\25\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\3\7\1\u01f1\26\7\1\u01f1\2\7"+ "\1\u01f1\3\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\35\7\1\u01f2\3\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\u01f3\40\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u01f0\2\7\1\u01f4"+ "\1\7\1\311\30\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\15\7\1\u01f5\23\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u01f1\31\7\1\u01f1"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\244\1\u01f6\34\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\31\7\1\u01f7\7\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\37\7\1\146\1\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\10\7"+ "\1\u01f8\30\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\4\7\1\u01f9\34\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\u01fa\30\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\4\7\1\u01fb\34\7"+ "\1\0\11\7\70\0\1\u01fc\100\0\1\u01fd\67\0\1\u01fe"+ "\75\0\1\u01fd\103\0\1\u01ff\14\0\4\7\1\0\3\7"+ "\1\52\16\7\1\u0200\22\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\7\7\1\333\31\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\1\u01bb\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\3\7"+ "\1\244\31\7\1\244\3\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\11\7\1\u0201\27\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\36\7\1\u0202\2\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\15\7"+ "\1\u015d\23\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\15\7\1\u0203\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\u0204\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\u0205\35\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\35\7"+ "\1\u012b\3\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\u012b\40\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\141\1\u0197\36\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\16\7\1\u0206\22\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\16\7"+ "\1\u0207\1\222\21\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\33\7\1\u0208\5\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u0209\1\7\2\244"+ "\20\7\1\u0182\2\7\1\244\6\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\6\7\1\244\23\7\1\244"+ "\2\7\1\244\3\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\u020a\40\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\15\7\1\u020b\23\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\5\7\1\244\33\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\32\7"+ "\1\325\6\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\3\7\1\141\35\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\13\7\1\u0182\3\7\1\u0182\12\7"+ "\1\244\6\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\5\7\1\244\27\7\1\244\3\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\27\7\1\u020c\11\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\6\7"+ "\1\u020d\6\7\1\u020d\23\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\6\7\1\u020e\6\7\1\u020e\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\23\7"+ "\1\u0158\15\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\23\7\1\u020f\15\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\23\7\1\u0210\15\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\23\7\1\u0174\15\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\23\7"+ "\1\u0211\15\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\23\7\1\u0212\15\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\11\7\1\222\27\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\7\1\u0213\37\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\4\7"+ "\1\u0214\34\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\37\7\1\244\1\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\23\7\1\244\15\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\u0111\40\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\10\7\1\u01e1"+ "\30\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\7\1\141\1\7\1\274\5\7\1\u0199\1\7\1\u0169"+ "\1\u0215\12\7\1\u0181\11\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\u01e1\5\7\1\u01e1\22\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\4\7"+ "\1\274\34\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\14\7\1\222\24\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\10\7\1\u018e\30\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\3\7\1\u0158\23\7"+ "\1\u0158\11\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\1\u0216\40\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\12\7\1\u01bb\26\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\31\7\1\u0217\7\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\16\7\1\u0218"+ "\22\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\325\35\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\7\7\1\u01bb\31\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\10\7\1\274\30\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\15\7\1\u0168"+ "\22\7\1\u0168\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\23\7\1\141\15\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\4\7\1\244\1\7\1\141\1\7"+ "\1\311\5\7\1\u01ba\10\7\1\146\5\7\1\244\3\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\33\7"+ "\1\u0158\5\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\40\7\1\u0168\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\4\7\1\u0219\34\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\7\1\u0193\37\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\7\7\1\u021a"+ "\31\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\7\1\u021b\37\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\13\7\1\u021c\25\7\1\0\11\7\71\0"+ "\1\u021d\100\0\1\u01ff\67\0\1\u01b6\21\0\4\7\1\0"+ "\3\7\1\52\17\7\1\315\21\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u021e\35\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\2\7\1\u021f"+ "\36\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\32\7\1\u01cd\6\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\u0182\26\7\1\u01cd\6\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\35\7\1\u0220"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\1\u018e\22\7\1\222\15\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\u018e\40\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\u0221\23\7\1\u0221"+ "\11\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\11\7\1\u0222\27\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\33\7\1\u01cd\5\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\2\7\1\u0223\36\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\23\7\1\123"+ "\15\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\23\7\1\u0224\15\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\10\7\1\u0225\30\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\10\7\1\u0226\30\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\15\7\1\u0227"+ "\23\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\15\7\1\u0228\23\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\30\7\1\u0229\10\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\17\7\1\u0213\21\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\7\1\244"+ "\11\7\1\244\25\7\1\0\11\7\12\0\4\7\1\0"+ "\2\7\1\u0218\1\52\41\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\7\1\u01bb\37\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\1\u01bb\40\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\37\7\1\u022a"+ "\1\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\6\7\1\u022b\32\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\35\7\1\u01cd\3\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\10\7\1\u022c\30\7\1\0"+ "\11\7\72\0\1\u01b6\15\0\4\7\1\0\3\7\1\52"+ "\7\7\1\152\31\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\1\7\1\u022d\37\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\6\7\1\141\32\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\3\7\1\141"+ "\1\7\1\u0182\24\7\1\325\2\7\1\u0220\3\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\27\7\1\u022e"+ "\11\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\244\1\7\1\244\12\7\1\u01cd\11\7\1\244"+ "\2\7\1\244\3\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\15\7\1\u01ba\23\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\244\11\7\1\244"+ "\23\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\3\7\1\244\2\7\1\244\32\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\3\7\1\244\11\7\1\244"+ "\17\7\1\244\3\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\3\7\1\244\2\7\1\244\26\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\25\7\1\244\13\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\4\7\1\u022f\1\7\1\u0230\26\7\1\244"+ "\3\7\1\0\11\7\12\0\4\7\1\0\3\7\1\52"+ "\11\7\1\u0231\27\7\1\0\11\7\12\0\4\7\1\0"+ "\3\7\1\52\10\7\1\272\30\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\14\7\1\u0232\24\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\1\u0233\13\7"+ "\1\u0234\24\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\13\7\1\244\25\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\35\7\1\u022f\3\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\7\7\1\u0235\31\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\7\7"+ "\1\u0236\31\7\1\0\11\7\12\0\4\7\1\0\1\244"+ "\2\7\1\52\22\7\2\244\15\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\1\u0237\40\7\1\0\11\7"+ "\12\0\4\7\1\0\3\7\1\52\15\7\1\u0238\23\7"+ "\1\0\11\7\12\0\4\7\1\0\3\7\1\52\15\7"+ "\1\u0239\23\7\1\0\11\7\12\0\4\7\1\0\3\7"+ "\1\52\7\7\1\244\31\7\1\0\11\7\12\0\4\7"+ "\1\0\3\7\1\52\1\u01cd\40\7\1\0\11\7\12\0"+ "\4\7\1\0\3\7\1\52\15\7\1\u023a\23\7\1\0"+ "\11\7\12\0\4\7\1\0\3\7\1\52\16\7\1\152"+ "\22\7\1\0\11\7\4\0"; private static int [] zzUnpackTrans() { int [] result = new int[33728]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; private static final char[] EMPTY_BUFFER = new char[0]; private static final int YYEOF = -1; private static Reader zzReader; // Fake /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state aState */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\1\1\1\11\4\1\1\11\31\1\2\11"+ "\3\1\1\0\2\11\1\0\177\1\4\0\224\1\5\0"+ "\152\1\5\0\105\1\3\0\1\11\35\1\1\0\35\1"; private static int [] zzUnpackAttribute() { int [] result = new int[570]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** this buffer may contains the current text array to be matched when it is cheap to acquire it */ private char[] zzBufferArray; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /* user code: */ public _AsmIntelHighlightingLexer() { this(null); } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public _AsmIntelHighlightingLexer(Reader in) { zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 1768) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } @Override public final int getTokenStart(){ return zzStartRead; } @Override public final int getTokenEnd(){ return getTokenStart() + yylength(); } @Override public void reset(CharSequence buffer, int start, int end, int initialState){ zzBuffer = buffer; zzBufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; zzPushbackPos = 0; zzAtEOF = false; zzAtBOL = true; zzEndRead = end; yybegin(initialState); } /** * Refills the input buffer. * * @return false, iff there was new input. * * @exception IOException if any I/O-Error occurs */ private boolean zzRefill() throws IOException { return true; } /** * Returns the current lexical state. */ @Override public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ @Override public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position pos from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception IOException if any I/O-Error occurs */ @Override public IElementType advance() throws IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; char[] zzBufferArrayL = zzBufferArray; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++); else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 17: return FLAG; case 19: break; case 7: return COMMA; case 20: break; case 5: return INT; case 21: break; case 8: return LINE_COMMENT; case 22: break; case 11: return REGISTER; case 23: break; case 4: return IDENTIFIER; case 24: break; case 10: return LABEL; case 25: break; case 1: return TokenType.BAD_CHARACTER; case 26: break; case 14: return HEX; case 27: break; case 18: return PREPROCESSOR; case 28: break; case 2: return TokenType.WHITE_SPACE; case 29: break; case 3: return OPERATOR; case 30: break; case 16: return DIRECTIVE; case 31: break; case 15: return PSEUDO_INS; case 32: break; case 9: return STRING; case 33: break; case 6: return PAREN; case 34: break; case 13: return INSTRUCTION; case 35: break; case 12: return PSEUDO_REG; case 36: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; return null; } else { zzScanError(ZZ_NO_MATCH); } } } } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/lexer/_AsmIntelLexer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ /* The following code was generated by JFlex 1.4.3 on 3/26/16 7:42 PM */ package com.plan9.intel.lang.core.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.util.text.CharArrayUtil; import com.plan9.intel.lang.core.psi.AsmIntelTypes; import java.io.IOException; import java.io.Reader; import static com.plan9.intel.lang.core.AsmIntelParserDefinition.LINE_COMMENT; /** * This class is a scanner generated by * JFlex 1.4.3 * on 3/26/16 7:42 PM from the specification file * /Users/zolotov/dev/intellij-plugins/intellij-go/plan9/src/com/plan9/intel/lang/core/lexer/AsmIntelLexer.flex */ public class _AsmIntelLexer implements FlexLexer, AsmIntelTypes { /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\3\1\1\1\0\1\2\1\1\22\0\1\3\1\0\1\5"+ "\1\55\4\0\1\64\1\65\2\0\1\66\2\0\1\4\1\12\1\50"+ "\1\47\1\54\1\53\1\11\1\52\1\11\1\51\1\11\1\15\6\0"+ "\1\23\1\22\1\20\1\24\1\37\1\16\1\45\1\43\1\40\1\30"+ "\1\46\1\26\1\25\1\31\1\33\1\17\1\41\1\32\1\21\1\35"+ "\1\34\1\42\1\27\1\14\1\36\1\44\4\0\1\6\1\0\6\10"+ "\2\6\1\56\3\6\1\57\1\6\1\61\1\60\1\6\1\62\1\6"+ "\1\63\3\6\1\13\2\6\1\0\1\67\55\0\1\6\12\0\1\6"+ "\4\0\1\6\5\0\27\6\1\0\37\6\1\0\u01ca\6\4\0\14\6"+ "\16\0\5\6\7\0\1\6\1\0\1\6\201\0\5\6\1\0\2\6"+ "\2\0\4\6\10\0\1\6\1\0\3\6\1\0\1\6\1\0\24\6"+ "\1\0\123\6\1\0\213\6\10\0\236\6\11\0\46\6\2\0\1\6"+ "\7\0\47\6\110\0\33\6\5\0\3\6\55\0\53\6\25\0\12\7"+ "\4\0\2\6\1\0\143\6\1\0\1\6\17\0\2\6\7\0\2\6"+ "\12\7\3\6\2\0\1\6\20\0\1\6\1\0\36\6\35\0\131\6"+ "\13\0\1\6\16\0\12\7\41\6\11\0\2\6\4\0\1\6\5\0"+ "\26\6\4\0\1\6\11\0\1\6\3\0\1\6\27\0\31\6\107\0"+ "\1\6\1\0\13\6\127\0\66\6\3\0\1\6\22\0\1\6\7\0"+ "\12\6\4\0\12\7\1\0\7\6\1\0\7\6\5\0\10\6\2\0"+ "\2\6\2\0\26\6\1\0\7\6\1\0\1\6\3\0\4\6\3\0"+ "\1\6\20\0\1\6\15\0\2\6\1\0\3\6\4\0\12\7\2\6"+ "\23\0\6\6\4\0\2\6\2\0\26\6\1\0\7\6\1\0\2\6"+ "\1\0\2\6\1\0\2\6\37\0\4\6\1\0\1\6\7\0\12\7"+ "\2\0\3\6\20\0\11\6\1\0\3\6\1\0\26\6\1\0\7\6"+ "\1\0\2\6\1\0\5\6\3\0\1\6\22\0\1\6\17\0\2\6"+ "\4\0\12\7\25\0\10\6\2\0\2\6\2\0\26\6\1\0\7\6"+ "\1\0\2\6\1\0\5\6\3\0\1\6\36\0\2\6\1\0\3\6"+ "\4\0\12\7\1\0\1\6\21\0\1\6\1\0\6\6\3\0\3\6"+ "\1\0\4\6\3\0\2\6\1\0\1\6\1\0\2\6\3\0\2\6"+ "\3\0\3\6\3\0\14\6\26\0\1\6\25\0\12\7\25\0\10\6"+ "\1\0\3\6\1\0\27\6\1\0\12\6\1\0\5\6\3\0\1\6"+ "\32\0\2\6\6\0\2\6\4\0\12\7\25\0\10\6\1\0\3\6"+ "\1\0\27\6\1\0\12\6\1\0\5\6\3\0\1\6\40\0\1\6"+ "\1\0\2\6\4\0\12\7\1\0\2\6\22\0\10\6\1\0\3\6"+ "\1\0\51\6\2\0\1\6\20\0\1\6\21\0\2\6\4\0\12\7"+ "\12\0\6\6\5\0\22\6\3\0\30\6\1\0\11\6\1\0\1\6"+ "\2\0\7\6\72\0\60\6\1\0\2\6\14\0\7\6\11\0\12\7"+ "\47\0\2\6\1\0\1\6\2\0\2\6\1\0\1\6\2\0\1\6"+ "\6\0\4\6\1\0\7\6\1\0\3\6\1\0\1\6\1\0\1\6"+ "\2\0\2\6\1\0\4\6\1\0\2\6\11\0\1\6\2\0\5\6"+ "\1\0\1\6\11\0\12\7\2\0\4\6\40\0\1\6\37\0\12\7"+ "\26\0\10\6\1\0\44\6\33\0\5\6\163\0\53\6\24\0\1\6"+ "\12\7\6\0\6\6\4\0\4\6\3\0\1\6\3\0\2\6\7\0"+ "\3\6\4\0\15\6\14\0\1\6\1\0\12\7\6\0\46\6\1\0"+ "\1\6\5\0\1\6\2\0\53\6\1\0\u014d\6\1\0\4\6\2\0"+ "\7\6\1\0\1\6\1\0\4\6\2\0\51\6\1\0\4\6\2\0"+ "\41\6\1\0\4\6\2\0\7\6\1\0\1\6\1\0\4\6\2\0"+ "\17\6\1\0\71\6\1\0\4\6\2\0\103\6\45\0\20\6\20\0"+ "\125\6\14\0\u026c\6\2\0\21\6\1\0\32\6\5\0\113\6\25\0"+ "\15\6\1\0\4\6\16\0\22\6\16\0\22\6\16\0\15\6\1\0"+ "\3\6\17\0\64\6\43\0\1\6\4\0\1\6\3\0\12\7\46\0"+ "\12\7\6\0\130\6\10\0\51\6\1\0\1\6\5\0\106\6\12\0"+ "\35\6\51\0\12\7\36\6\2\0\5\6\13\0\54\6\25\0\7\6"+ "\10\0\12\7\46\0\27\6\11\0\65\6\53\0\12\7\6\0\12\7"+ "\15\0\1\6\135\0\57\6\21\0\7\6\4\0\12\7\51\0\36\6"+ "\15\0\2\6\12\7\54\6\32\0\44\6\34\0\12\7\3\0\3\6"+ "\12\7\44\6\153\0\4\6\1\0\4\6\3\0\2\6\11\0\300\6"+ "\100\0\u0116\6\2\0\6\6\2\0\46\6\2\0\6\6\2\0\10\6"+ "\1\0\1\6\1\0\1\6\1\0\1\6\1\0\37\6\2\0\65\6"+ "\1\0\7\6\1\0\1\6\3\0\3\6\1\0\7\6\3\0\4\6"+ "\2\0\6\6\4\0\15\6\5\0\3\6\1\0\7\6\164\0\1\6"+ "\15\0\1\6\20\0\15\6\145\0\1\6\4\0\1\6\2\0\12\6"+ "\1\0\1\6\3\0\5\6\6\0\1\6\1\0\1\6\1\0\1\6"+ "\1\0\4\6\1\0\13\6\2\0\4\6\5\0\5\6\4\0\1\6"+ "\64\0\2\6\u0a7b\0\57\6\1\0\57\6\1\0\205\6\6\0\4\6"+ "\3\0\2\6\14\0\46\6\1\0\1\6\5\0\1\6\2\0\70\6"+ "\7\0\1\6\20\0\27\6\11\0\7\6\1\0\7\6\1\0\7\6"+ "\1\0\7\6\1\0\7\6\1\0\7\6\1\0\7\6\1\0\7\6"+ "\120\0\1\6\u01d5\0\2\6\52\0\5\6\5\0\2\6\4\0\126\6"+ "\6\0\3\6\1\0\132\6\1\0\4\6\5\0\51\6\3\0\136\6"+ "\21\0\33\6\65\0\20\6\u0200\0\u19b6\6\112\0\u51cd\6\63\0\u048d\6"+ "\103\0\56\6\2\0\u010d\6\3\0\20\6\12\7\2\6\24\0\57\6"+ "\20\0\31\6\10\0\106\6\61\0\11\6\2\0\147\6\2\0\4\6"+ "\1\0\4\6\14\0\13\6\115\0\12\6\1\0\3\6\1\0\4\6"+ "\1\0\27\6\35\0\64\6\16\0\62\6\34\0\12\7\30\0\6\6"+ "\3\0\1\6\4\0\12\7\34\6\12\0\27\6\31\0\35\6\7\0"+ "\57\6\34\0\1\6\12\7\46\0\51\6\27\0\3\6\1\0\10\6"+ "\4\0\12\7\6\0\27\6\3\0\1\6\5\0\60\6\1\0\1\6"+ "\3\0\2\6\2\0\5\6\2\0\1\6\1\0\1\6\30\0\3\6"+ "\2\0\13\6\7\0\3\6\14\0\6\6\2\0\6\6\2\0\6\6"+ "\11\0\7\6\1\0\7\6\221\0\43\6\15\0\12\7\6\0\u2ba4\6"+ "\14\0\27\6\4\0\61\6\u2104\0\u016e\6\2\0\152\6\46\0\7\6"+ "\14\0\5\6\5\0\1\6\1\0\12\6\1\0\15\6\1\0\5\6"+ "\1\0\1\6\1\0\2\6\1\0\2\6\1\0\154\6\41\0\u016b\6"+ "\22\0\100\6\2\0\66\6\50\0\14\6\164\0\5\6\1\0\207\6"+ "\23\0\12\7\7\0\32\6\6\0\32\6\13\0\131\6\3\0\6\6"+ "\2\0\6\6\2\0\6\6\2\0\3\6\43\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\2\2\2\1\1\3\2\4\1\3\1\5"+ "\25\3\1\1\1\6\1\7\1\10\1\11\1\12\1\0"+ "\1\13\1\14\1\0\12\3\1\15\17\3\1\15\22\3"+ "\1\15\1\3\1\15\101\3\1\0\1\16\102\3\1\17"+ "\64\3\1\17\13\3\1\17\7\3\1\0\17\3\1\17"+ "\25\3\1\17\36\3\1\17\1\3\2\17\1\3\2\17"+ "\1\3\1\17\15\3\1\20\5\3\1\0\5\3\1\17"+ "\1\3\2\17\5\3\2\17\1\3\2\17\36\3\1\21"+ "\22\3\1\0\1\3\1\17\5\3\1\17\14\3\1\17"+ "\10\3\1\0\17\3\1\22\15\3"; private static int [] zzUnpackAction() { int [] result = new int[522]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\70\0\160\0\70\0\250\0\340\0\u0118\0\u0150"+ "\0\u0188\0\u01c0\0\70\0\u01f8\0\u0230\0\u0268\0\u02a0\0\u02d8"+ "\0\u0310\0\u0348\0\u0380\0\u03b8\0\u03f0\0\u0428\0\u0460\0\u0498"+ "\0\u04d0\0\u0508\0\u0540\0\u0578\0\u05b0\0\u05e8\0\u0620\0\u0658"+ "\0\u0690\0\70\0\70\0\70\0\70\0\u06c8\0\340\0\70"+ "\0\70\0\u0700\0\u0738\0\u0770\0\u07a8\0\u07e0\0\u0818\0\u0850"+ "\0\u0888\0\u08c0\0\u08f8\0\u0930\0\u0968\0\u09a0\0\u09d8\0\u0a10"+ "\0\u0a48\0\u0a80\0\u0ab8\0\u0af0\0\u0b28\0\u0b60\0\u0b98\0\u0bd0"+ "\0\u0c08\0\u0c40\0\u0c78\0\u0cb0\0\u0ce8\0\u0d20\0\u0d58\0\u0d90"+ "\0\u0dc8\0\u0e00\0\u0e38\0\u0e70\0\u0ea8\0\u0ee0\0\u0f18\0\u0f50"+ "\0\u0f88\0\u0fc0\0\u0ff8\0\u1030\0\u1068\0\u10a0\0\u10d8\0\u0118"+ "\0\u1110\0\u1148\0\u1180\0\u11b8\0\u11f0\0\u1228\0\u1260\0\u1298"+ "\0\u12d0\0\u1308\0\u1340\0\u1378\0\u13b0\0\u13e8\0\u1420\0\u1458"+ "\0\u1490\0\u14c8\0\u1500\0\u1538\0\u1570\0\u15a8\0\u15e0\0\u1618"+ "\0\u1650\0\u1688\0\u16c0\0\u16f8\0\u1730\0\u1768\0\u17a0\0\u17d8"+ "\0\u1810\0\u1848\0\u1880\0\u18b8\0\u18f0\0\u1928\0\u1960\0\u1998"+ "\0\u19d0\0\u1a08\0\u1a40\0\u1a78\0\u1ab0\0\u1ae8\0\u1b20\0\u1b58"+ "\0\u1b90\0\u1bc8\0\u1c00\0\u1c38\0\u1c70\0\u1ca8\0\u1ce0\0\u1d18"+ "\0\u1d50\0\u1d88\0\u1dc0\0\u1df8\0\u1e30\0\u1e68\0\u1ea0\0\u1ed8"+ "\0\u1f10\0\u1f48\0\u1f80\0\u1fb8\0\u0700\0\u1ff0\0\u2028\0\u2060"+ "\0\u2098\0\u20d0\0\u2108\0\u2140\0\u2178\0\u21b0\0\u21e8\0\u2220"+ "\0\u2258\0\u2290\0\u22c8\0\u2300\0\u2338\0\u2370\0\u23a8\0\u23e0"+ "\0\u2418\0\u2450\0\u2488\0\u24c0\0\u24f8\0\u2530\0\u2568\0\u25a0"+ "\0\u25d8\0\u2610\0\u2648\0\u2680\0\u26b8\0\u26f0\0\u2728\0\u2760"+ "\0\u2798\0\u27d0\0\u2808\0\u2840\0\u2878\0\u28b0\0\u28e8\0\u2920"+ "\0\u2958\0\u2990\0\u29c8\0\u2a00\0\u2a38\0\u2a70\0\u2aa8\0\u2ae0"+ "\0\u2b18\0\u2b50\0\u2b88\0\u2bc0\0\u2bf8\0\u2c30\0\u2c68\0\u2ca0"+ "\0\u2cd8\0\u2d10\0\u2d48\0\u2d80\0\u2db8\0\u2df0\0\u2e28\0\u0118"+ "\0\u2e60\0\u2e98\0\u2ed0\0\u2f08\0\u2f40\0\u2f78\0\u2fb0\0\u2fe8"+ "\0\u3020\0\u3058\0\u3090\0\u30c8\0\u3100\0\u3138\0\u3170\0\u31a8"+ "\0\u31e0\0\u3218\0\u3250\0\u3288\0\u32c0\0\u32f8\0\u3330\0\u3368"+ "\0\u33a0\0\u33d8\0\u3410\0\u3448\0\u3480\0\u34b8\0\u34f0\0\u3528"+ "\0\u3560\0\u3598\0\u35d0\0\u3608\0\u3640\0\u3678\0\u36b0\0\u36e8"+ "\0\u3720\0\u3758\0\u3790\0\u37c8\0\u3800\0\u3838\0\u3870\0\u38a8"+ "\0\u38e0\0\u3918\0\u3950\0\u3988\0\u39c0\0\u39f8\0\u3a30\0\u3a68"+ "\0\u3aa0\0\u3ad8\0\u3b10\0\u3b48\0\u3b80\0\u3bb8\0\u3bf0\0\u3c28"+ "\0\u1068\0\u3c60\0\u3c98\0\u3cd0\0\u3d08\0\u3d40\0\u3d78\0\u3db0"+ "\0\u3de8\0\u3e20\0\u3e58\0\u3e90\0\u3ec8\0\u3f00\0\u3f38\0\u3f70"+ "\0\u39c0\0\u3fa8\0\u3fe0\0\u4018\0\u4050\0\u4088\0\u40c0\0\u40f8"+ "\0\u4130\0\u4168\0\u41a0\0\u41d8\0\u4210\0\u4248\0\u4280\0\u42b8"+ "\0\u42f0\0\u4328\0\u4360\0\u4398\0\u43d0\0\u4408\0\u4440\0\u4478"+ "\0\u44b0\0\u44e8\0\u4520\0\u4558\0\u4590\0\u45c8\0\u4600\0\u4638"+ "\0\u4670\0\u46a8\0\u46e0\0\u4718\0\u4750\0\u4788\0\u47c0\0\u47f8"+ "\0\u4830\0\u4868\0\u48a0\0\u48d8\0\u4910\0\u4948\0\u4980\0\u49b8"+ "\0\u49f0\0\u4a28\0\u4a60\0\u4a98\0\u4ad0\0\u4b08\0\u4b40\0\u4b78"+ "\0\u4bb0\0\u4be8\0\u4c20\0\u4c58\0\u4c90\0\u4cc8\0\u4d00\0\u4d38"+ "\0\u4d70\0\u4da8\0\u4de0\0\u4e18\0\u4e50\0\u4e88\0\u4ec0\0\u4ef8"+ "\0\u4f30\0\u4f68\0\u4fa0\0\u4fd8\0\u5010\0\u5048\0\u5080\0\u50b8"+ "\0\u50f0\0\u5128\0\u5160\0\u0118\0\u5198\0\u51d0\0\u5208\0\u5240"+ "\0\u5278\0\u52b0\0\u52e8\0\u5320\0\u5358\0\u5390\0\u53c8\0\u42f0"+ "\0\u5400\0\u26b8\0\u5438\0\u5470\0\u54a8\0\u54e0\0\u5518\0\u5550"+ "\0\u5588\0\u55c0\0\u55f8\0\u2840\0\u5630\0\u5668\0\u56a0\0\u56d8"+ "\0\u5710\0\u5748\0\u5780\0\u57b8\0\u57f0\0\u5828\0\u5860\0\u5898"+ "\0\u58d0\0\u5908\0\u5940\0\u5978\0\u59b0\0\u59e8\0\u5a20\0\u5a58"+ "\0\u5a90\0\u5ac8\0\u5b00\0\u5b38\0\u5b70\0\u5ba8\0\u5be0\0\u5c18"+ "\0\u5c50\0\u5c88\0\u5cc0\0\u0118\0\u5cf8\0\u5d30\0\u5d68\0\u5da0"+ "\0\u5dd8\0\u5e10\0\u5e48\0\u5e80\0\u5eb8\0\u5ef0\0\u5f28\0\u5f60"+ "\0\u5f98\0\u5fd0\0\u6008\0\u6040\0\u6078\0\u60b0\0\u60e8\0\u6120"+ "\0\u6158\0\u6190\0\u61c8\0\u6200\0\u6238\0\u6270\0\u40c0\0\u62a8"+ "\0\u62e0\0\u6318\0\u6350\0\u6388\0\u63c0\0\u63f8\0\u6430\0\u6468"+ "\0\u64a0\0\u64d8\0\u6510\0\u6548\0\u6580\0\u65b8\0\u65f0\0\u6628"+ "\0\u6660\0\u6698\0\u66d0\0\u6708\0\u6740\0\u6778\0\u67b0\0\u67e8"+ "\0\u6820\0\u6858\0\u6890\0\u68c8\0\u6900\0\u6938\0\u6970\0\u69a8"+ "\0\u69e0\0\u6a18\0\u6a50\0\u6a88\0\70\0\u6ac0\0\u6af8\0\u4de0"+ "\0\u6b30\0\u6b68\0\u6ba0\0\u6bd8\0\u6c10\0\u6c48\0\u6c80\0\u6cb8"+ "\0\u6cf0\0\u6d28"; private static int [] zzUnpackRowMap() { int [] result = new int[522]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\2\1\3\1\4\1\3\1\5\1\6\1\7\1\2"+ "\1\7\1\10\1\11\1\7\1\12\1\13\1\14\1\15"+ "\1\16\1\17\1\20\1\21\1\22\1\23\1\24\1\25"+ "\1\26\1\27\1\30\1\31\1\32\1\33\1\7\1\34"+ "\1\35\1\36\1\37\1\40\3\7\6\10\1\41\6\7"+ "\1\42\1\43\1\44\1\45\71\0\1\3\1\0\1\3"+ "\70\0\1\46\63\0\5\47\1\50\62\47\6\0\7\7"+ "\1\51\37\7\1\0\6\7\15\0\2\10\34\0\6\10"+ "\26\0\2\52\61\0\7\7\1\51\2\7\1\53\1\7"+ "\1\54\1\55\2\7\1\56\3\7\1\57\1\60\1\7"+ "\1\61\1\7\1\62\15\7\1\0\6\7\12\0\6\7"+ "\1\63\1\51\1\64\1\65\1\66\1\67\1\7\1\70"+ "\1\71\1\72\1\73\2\7\1\74\1\75\1\7\1\76"+ "\1\77\1\100\1\7\1\101\6\7\1\102\5\7\1\0"+ "\6\7\12\0\6\7\1\103\1\51\1\104\1\7\1\105"+ "\1\106\1\7\1\107\1\7\1\110\4\7\1\111\1\112"+ "\1\113\2\7\1\114\1\115\14\7\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\116\4\7\1\117\1\120\1\121"+ "\1\122\2\7\1\123\1\124\5\7\1\125\1\126\12\7"+ "\1\0\6\7\12\0\7\7\1\51\1\127\1\130\1\131"+ "\1\7\1\132\1\133\3\7\1\134\4\7\1\135\1\136"+ "\1\137\1\140\1\7\1\141\1\7\1\142\11\7\1\0"+ "\6\7\12\0\7\7\1\51\3\7\1\143\11\7\1\144"+ "\1\7\1\145\1\146\16\7\1\0\6\7\12\0\7\7"+ "\1\51\5\7\1\147\1\150\4\7\1\151\1\152\4\7"+ "\1\153\15\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\154\10\7\1\155\2\7\1\156\1\157\14\7\1\0"+ "\6\7\12\0\7\7\1\51\1\127\4\7\1\160\7\7"+ "\1\161\1\162\3\7\1\163\14\7\1\0\6\7\12\0"+ "\7\7\1\51\1\127\2\7\1\164\1\7\1\165\1\166"+ "\6\7\1\167\3\7\1\170\15\7\1\0\6\7\12\0"+ "\7\7\1\51\4\7\1\171\1\172\6\7\1\173\1\174"+ "\21\7\1\0\6\7\12\0\7\7\1\51\1\7\1\175"+ "\1\176\4\7\1\177\1\200\2\7\1\201\1\7\1\202"+ "\3\7\1\117\3\7\1\177\1\7\1\203\7\7\1\0"+ "\6\7\12\0\7\7\1\51\15\7\1\204\3\7\1\205"+ "\15\7\1\0\6\7\12\0\7\7\1\51\2\7\1\206"+ "\1\207\2\7\1\210\6\7\1\211\3\7\1\212\15\7"+ "\1\0\6\7\12\0\7\7\1\51\14\7\1\213\1\7"+ "\1\214\20\7\1\0\6\7\12\0\7\7\1\51\2\7"+ "\1\215\10\7\1\216\23\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\217\10\7\1\220\15\7\1\0\6\7"+ "\12\0\7\7\1\51\7\7\1\221\3\7\1\222\23\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\223\1\224"+ "\3\7\1\225\1\226\22\7\1\0\6\7\12\0\7\7"+ "\1\51\16\7\1\227\20\7\1\0\6\7\12\0\7\7"+ "\1\51\1\7\1\230\17\7\1\231\4\7\1\232\10\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\233\26\7"+ "\1\0\6\7\62\0\1\234\11\0\1\46\1\0\66\46"+ "\10\0\3\235\3\0\1\235\1\0\1\235\1\0\3\235"+ "\12\0\1\235\7\0\6\235\21\0\7\7\1\51\25\7"+ "\1\236\11\7\1\0\6\7\12\0\7\7\1\51\21\7"+ "\1\237\15\7\1\0\6\7\12\0\7\7\1\51\2\7"+ "\1\240\1\7\1\241\1\7\1\242\30\7\1\0\6\7"+ "\12\0\7\7\1\51\5\7\1\233\31\7\1\0\6\7"+ "\12\0\7\7\1\51\21\7\1\243\15\7\1\0\6\7"+ "\12\0\7\7\1\51\14\7\1\213\22\7\1\0\6\7"+ "\12\0\7\7\1\51\21\7\1\77\15\7\1\0\6\7"+ "\12\0\7\7\1\51\13\7\1\122\23\7\1\0\6\7"+ "\12\0\7\7\1\51\2\7\1\244\1\245\1\7\1\246"+ "\6\7\1\247\2\7\1\250\17\7\1\0\6\7\12\0"+ "\7\7\1\51\14\7\1\251\22\7\1\0\6\7\12\0"+ "\7\7\1\51\5\7\1\252\6\7\1\253\2\7\1\254"+ "\17\7\1\0\6\7\12\0\7\7\1\51\7\7\1\255"+ "\1\256\4\7\1\257\7\7\1\260\11\7\1\0\6\7"+ "\12\0\7\7\1\51\2\7\1\261\2\7\1\262\10\7"+ "\1\263\1\264\2\7\1\265\1\266\13\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\260\1\7\1\267\30\7"+ "\1\0\6\7\12\0\7\7\1\51\21\7\1\270\1\271"+ "\14\7\1\0\6\7\12\0\7\7\1\51\15\7\1\272"+ "\1\273\20\7\1\0\6\7\12\0\7\7\1\51\6\7"+ "\1\274\30\7\1\0\6\7\12\0\7\7\1\51\15\7"+ "\1\275\21\7\1\0\6\7\12\0\7\7\1\51\3\7"+ "\1\276\7\7\1\277\23\7\1\0\6\7\12\0\7\7"+ "\1\51\2\7\1\300\34\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\233\33\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\301\26\7\1\0\6\7\12\0\7\7"+ "\1\51\13\7\1\302\23\7\1\0\6\7\12\0\6\7"+ "\1\303\1\51\37\7\1\0\6\7\12\0\7\7\1\51"+ "\15\7\1\304\21\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\305\1\306\1\307\1\7\1\310\1\7\1\311"+ "\3\7\1\312\1\313\14\7\1\314\5\7\1\0\6\7"+ "\12\0\7\7\1\51\7\7\1\315\1\316\26\7\1\0"+ "\6\7\12\0\7\7\1\51\5\7\1\317\2\7\1\320"+ "\1\321\2\7\1\322\1\7\1\323\6\7\1\324\11\7"+ "\1\0\6\7\12\0\7\7\1\51\2\7\1\325\3\7"+ "\1\326\4\7\1\327\2\7\1\330\5\7\1\331\12\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\332\7\7"+ "\1\333\1\334\3\7\1\335\14\7\1\0\6\7\12\0"+ "\7\7\1\51\21\7\1\336\15\7\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\337\12\7\1\340\22\7\1\0"+ "\6\7\12\0\7\7\1\51\3\7\1\341\7\7\1\342"+ "\23\7\1\0\6\7\12\0\6\7\1\343\1\51\37\7"+ "\1\0\6\7\12\0\7\7\1\51\13\7\1\344\15\7"+ "\1\345\5\7\1\0\6\7\12\0\7\7\1\51\16\7"+ "\1\346\20\7\1\0\6\7\12\0\7\7\1\51\23\7"+ "\1\340\13\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\347\1\340\12\7\1\350\21\7\1\0\6\7\12\0"+ "\7\7\1\51\2\7\1\340\3\7\1\340\10\7\1\260"+ "\2\7\1\340\14\7\1\0\6\7\12\0\7\7\1\51"+ "\6\7\1\340\30\7\1\0\6\7\12\0\7\7\1\51"+ "\2\7\1\351\34\7\1\0\6\7\12\0\7\7\1\51"+ "\7\7\1\352\27\7\1\0\6\7\12\0\7\7\1\51"+ "\15\7\1\340\21\7\1\0\6\7\12\0\7\7\1\51"+ "\17\7\1\353\17\7\1\0\6\7\12\0\7\7\1\51"+ "\21\7\1\354\15\7\1\0\6\7\12\0\7\7\1\51"+ "\5\7\1\355\31\7\1\0\6\7\12\0\7\7\1\51"+ "\4\7\1\356\32\7\1\0\6\7\12\0\7\7\1\51"+ "\10\7\1\356\3\7\1\356\10\7\1\357\11\7\1\0"+ "\6\7\12\0\7\7\1\51\5\7\1\360\31\7\1\0"+ "\6\7\12\0\7\7\1\51\4\7\1\361\32\7\1\0"+ "\6\7\12\0\7\7\1\51\2\7\1\340\3\7\1\340"+ "\1\362\5\7\1\355\4\7\1\340\14\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\363\33\7\1\0\6\7"+ "\12\0\7\7\1\51\17\7\1\364\17\7\1\0\6\7"+ "\12\0\7\7\1\51\14\7\1\365\22\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\356\3\7\1\356\1\7"+ "\1\366\20\7\1\0\6\7\12\0\7\7\1\51\1\367"+ "\10\7\1\370\2\7\1\367\22\7\1\0\6\7\12\0"+ "\7\7\1\51\16\7\1\371\20\7\1\0\6\7\12\0"+ "\7\7\1\51\2\7\2\367\4\7\2\340\2\7\1\367"+ "\6\7\1\340\13\7\1\0\6\7\12\0\7\7\1\51"+ "\17\7\1\201\17\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\340\1\7\3\340\27\7\1\0\6\7\12\0"+ "\7\7\1\51\2\7\1\356\3\7\1\361\3\7\1\372"+ "\24\7\1\0\6\7\12\0\7\7\1\51\6\7\1\373"+ "\30\7\1\0\6\7\12\0\7\7\1\51\1\7\1\374"+ "\35\7\1\0\6\7\12\0\7\7\1\51\3\7\1\375"+ "\33\7\1\0\6\7\12\0\7\7\1\51\3\7\1\340"+ "\1\7\1\340\31\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\376\35\7\1\0\6\7\12\0\7\7\1\51"+ "\2\7\1\356\34\7\1\0\6\7\12\0\7\7\1\51"+ "\24\7\1\361\12\7\1\0\6\7\12\0\6\7\1\377"+ "\1\51\3\7\1\u0100\33\7\1\0\6\7\12\0\7\7"+ "\1\51\6\7\1\201\15\7\1\u0101\12\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\361\26\7\1\0\6\7"+ "\12\0\7\7\1\51\13\7\1\377\23\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\u0102\26\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\233\10\7\1\u0102\10\7"+ "\1\357\11\7\1\0\6\7\12\0\7\7\1\51\7\7"+ "\1\362\27\7\1\0\6\7\12\0\7\7\1\51\2\7"+ "\1\u0103\3\7\1\355\4\7\1\u0104\1\7\1\u0105\21\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\u0106\31\7"+ "\1\0\6\7\12\0\7\7\1\51\22\7\1\u0107\14\7"+ "\1\0\6\7\12\0\7\7\1\51\22\7\1\233\14\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\u0108\1\7"+ "\1\u0109\27\7\1\0\6\7\12\0\7\7\1\51\14\7"+ "\1\122\22\7\1\0\6\7\12\0\7\7\1\51\2\7"+ "\2\340\4\7\1\340\26\7\1\0\6\7\12\0\6\7"+ "\1\u010a\1\51\2\7\2\340\33\7\1\0\6\7\12\0"+ "\7\7\1\51\22\7\1\340\14\7\1\0\6\7\12\0"+ "\7\7\1\51\3\7\1\340\13\7\1\340\1\7\1\340"+ "\15\7\1\0\6\7\12\0\7\7\1\51\21\7\1\340"+ "\15\7\1\0\6\7\12\0\7\7\1\51\2\7\2\340"+ "\33\7\1\0\6\7\12\0\7\7\1\51\17\7\1\340"+ "\1\7\1\340\15\7\1\0\6\7\12\0\7\7\1\51"+ "\1\u010b\1\u010c\1\7\1\u010d\13\7\1\356\17\7\1\0"+ "\6\7\12\0\7\7\1\51\21\7\1\u010e\5\7\1\356"+ "\7\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u010f"+ "\6\7\1\356\3\7\1\356\22\7\1\0\6\7\12\0"+ "\7\7\1\51\7\7\1\340\13\7\1\u0110\13\7\1\0"+ "\6\7\12\0\7\7\1\51\1\7\1\u0111\5\7\1\u0109"+ "\7\7\1\u0112\17\7\1\0\6\7\12\0\7\7\1\51"+ "\6\7\1\u0113\1\7\1\356\3\7\1\356\1\7\1\u0114"+ "\20\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u0115"+ "\15\7\1\u0116\17\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\u0117\2\7\1\340\3\7\2\340\11\7\1\340"+ "\13\7\1\0\6\7\12\0\7\7\1\51\17\7\1\u0118"+ "\17\7\1\0\6\7\12\0\7\7\1\51\15\7\1\124"+ "\21\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u0119"+ "\35\7\1\0\6\7\12\0\7\7\1\51\3\7\1\u011a"+ "\33\7\1\0\6\7\12\0\6\7\1\u011b\1\51\3\7"+ "\1\u011c\33\7\1\0\6\7\12\0\7\7\1\51\7\7"+ "\1\260\27\7\1\0\6\7\12\0\7\7\1\51\17\7"+ "\1\u011d\17\7\1\0\6\7\12\0\7\7\1\51\22\7"+ "\1\u011e\14\7\1\0\6\7\12\0\7\7\1\51\16\7"+ "\1\u011f\20\7\1\0\6\7\12\0\7\7\1\51\2\7"+ "\1\356\1\u0120\1\340\3\7\2\340\5\7\1\u0121\4\7"+ "\1\u0122\12\7\1\0\6\7\12\0\7\7\1\51\21\7"+ "\1\u0123\15\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\122\31\7\1\0\6\7\12\0\6\7\1\103\1\51"+ "\2\7\1\u0124\1\7\1\u0125\1\62\1\7\1\u0126\7\7"+ "\1\61\17\7\1\0\6\7\12\0\7\7\1\51\14\7"+ "\1\u0127\22\7\1\0\6\7\12\0\7\7\1\51\21\7"+ "\1\u0128\15\7\1\0\6\7\12\0\7\7\1\51\17\7"+ "\1\340\17\7\1\0\6\7\63\0\1\u0129\16\0\7\7"+ "\1\51\27\7\1\356\7\7\1\0\6\7\12\0\7\7"+ "\1\51\27\7\1\u012a\7\7\1\0\6\7\12\0\7\7"+ "\1\51\23\7\1\u012b\13\7\1\0\6\7\12\0\7\7"+ "\1\51\15\7\1\266\21\7\1\0\6\7\12\0\7\7"+ "\1\51\6\7\1\356\30\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\u012c\26\7\1\0\6\7\12\0\7\7"+ "\1\51\25\7\1\122\11\7\1\0\6\7\12\0\7\7"+ "\1\51\5\7\1\u012d\31\7\1\0\6\7\12\0\7\7"+ "\1\51\7\7\1\340\27\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\u012e\33\7\1\0\6\7\12\0\7\7"+ "\1\51\14\7\1\u012f\22\7\1\0\6\7\12\0\7\7"+ "\1\51\21\7\1\201\15\7\1\0\6\7\12\0\7\7"+ "\1\51\17\7\1\254\17\7\1\0\6\7\12\0\7\7"+ "\1\51\21\7\1\u0130\15\7\1\0\6\7\12\0\7\7"+ "\1\51\5\7\1\u0131\31\7\1\0\6\7\12\0\7\7"+ "\1\51\15\7\1\u0132\21\7\1\0\6\7\12\0\7\7"+ "\1\51\21\7\1\u0133\15\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\340\3\7\1\u0134\27\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\340\33\7\1\0\6\7"+ "\12\0\7\7\1\51\5\7\1\u0135\31\7\1\0\6\7"+ "\12\0\7\7\1\51\24\7\1\201\12\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\u0136\32\7\1\0\6\7"+ "\12\0\7\7\1\51\2\7\2\u0137\15\7\1\u0138\15\7"+ "\1\0\6\7\12\0\7\7\1\51\13\7\1\u0139\23\7"+ "\1\0\6\7\12\0\7\7\1\51\14\7\1\233\22\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\u013a\30\7"+ "\1\0\6\7\12\0\7\7\1\51\2\7\1\u013b\34\7"+ "\1\0\6\7\12\0\7\7\1\51\24\7\1\u0136\12\7"+ "\1\0\6\7\12\0\7\7\1\51\24\7\1\u013c\12\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\u013a\26\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\177\1\u0137"+ "\5\7\1\u013d\10\7\1\u0138\4\7\1\340\3\7\1\340"+ "\4\7\1\0\6\7\12\0\7\7\1\51\1\7\1\340"+ "\35\7\1\0\6\7\12\0\7\7\1\51\17\7\1\103"+ "\17\7\1\0\6\7\12\0\7\7\1\51\6\7\1\u013e"+ "\30\7\1\0\6\7\12\0\7\7\1\51\15\7\1\u013f"+ "\21\7\1\0\6\7\12\0\7\7\1\51\31\7\1\u0140"+ "\5\7\1\0\6\7\12\0\7\7\1\51\2\7\1\u013b"+ "\17\7\1\233\14\7\1\0\6\7\12\0\7\7\1\51"+ "\7\7\1\u0141\27\7\1\0\6\7\12\0\7\7\1\51"+ "\14\7\1\340\22\7\1\0\6\7\12\0\7\7\1\51"+ "\13\7\1\312\23\7\1\0\6\7\12\0\7\7\1\51"+ "\7\7\1\u0142\27\7\1\0\6\7\12\0\7\7\1\51"+ "\16\7\1\u0143\20\7\1\0\6\7\12\0\7\7\1\51"+ "\2\7\1\u0144\3\7\1\122\30\7\1\0\6\7\12\0"+ "\7\7\1\51\5\7\1\u0133\10\7\1\374\3\7\1\u0131"+ "\14\7\1\0\6\7\12\0\7\7\1\51\5\7\1\u0145"+ "\31\7\1\0\6\7\12\0\7\7\1\51\2\7\1\u0146"+ "\1\u0147\33\7\1\0\6\7\12\0\7\7\1\51\22\7"+ "\1\u0102\14\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\u0148\35\7\1\0\6\7\12\0\7\7\1\51\7\7"+ "\1\u0149\27\7\1\0\6\7\12\0\7\7\1\51\6\7"+ "\1\u014a\30\7\1\0\6\7\12\0\7\7\1\51\10\7"+ "\1\u014b\26\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\152\31\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\u0102\2\7\1\u014b\26\7\1\0\6\7\12\0\7\7"+ "\1\51\4\7\1\u014c\32\7\1\0\6\7\12\0\7\7"+ "\1\51\16\7\1\u014d\20\7\1\0\6\7\12\0\7\7"+ "\1\51\30\7\1\u014e\6\7\1\0\6\7\12\0\7\7"+ "\1\51\6\7\1\u014c\30\7\1\0\6\7\12\0\7\7"+ "\1\51\6\7\1\u014f\30\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\201\33\7\1\0\6\7\12\0\7\7"+ "\1\51\27\7\1\u0150\7\7\1\0\6\7\12\0\6\7"+ "\1\u0151\1\51\6\7\1\u0152\30\7\1\0\6\7\12\0"+ "\7\7\1\51\24\7\1\u0153\12\7\1\0\6\7\12\0"+ "\7\7\1\51\10\7\1\u0154\26\7\1\0\6\7\12\0"+ "\7\7\1\51\13\7\1\u0151\23\7\1\0\6\7\12\0"+ "\7\7\1\51\1\u0155\36\7\1\0\6\7\12\0\7\7"+ "\1\51\1\367\4\7\1\u0102\2\7\2\340\11\7\1\340"+ "\13\7\1\0\6\7\12\0\7\7\1\51\25\7\1\337"+ "\11\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u0156"+ "\35\7\1\0\6\7\12\0\7\7\1\51\17\7\1\u0157"+ "\17\7\1\0\6\7\12\0\7\7\1\51\3\7\1\u0158"+ "\33\7\1\0\6\7\12\0\7\7\1\51\1\u0102\36\7"+ "\1\0\6\7\12\0\7\7\1\51\22\7\1\122\14\7"+ "\1\0\6\7\12\0\6\7\1\u0159\1\51\1\7\1\u0117"+ "\1\7\1\u015a\1\340\3\7\2\340\11\7\1\340\13\7"+ "\1\0\6\7\12\0\7\7\1\51\24\7\1\u015b\12\7"+ "\1\0\6\7\12\0\7\7\1\51\36\7\1\u015c\1\0"+ "\6\7\12\0\7\7\1\51\22\7\1\u015d\14\7\1\0"+ "\6\7\12\0\7\7\1\51\1\7\1\u015e\1\7\1\u015f"+ "\13\7\1\u0160\17\7\1\0\6\7\12\0\7\7\1\51"+ "\13\7\1\u0161\23\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\356\33\7\1\0\6\7\12\0\7\7\1\51"+ "\4\7\1\340\3\7\2\340\11\7\1\340\13\7\1\0"+ "\6\7\12\0\7\7\1\51\1\340\36\7\1\0\6\7"+ "\12\0\7\7\1\51\1\7\1\u0162\35\7\1\0\6\7"+ "\12\0\7\7\1\51\1\7\1\u0117\1\7\1\u0117\1\340"+ "\3\7\2\340\11\7\1\340\13\7\1\0\6\7\12\0"+ "\6\7\1\u0163\1\51\37\7\1\0\6\7\12\0\7\7"+ "\1\51\2\7\1\u0164\11\7\1\u0165\22\7\1\0\6\7"+ "\12\0\7\7\1\51\1\7\1\175\1\202\4\7\1\177"+ "\1\200\2\7\1\201\1\7\1\202\3\7\1\117\3\7"+ "\1\177\1\7\1\203\7\7\1\0\6\7\12\0\7\7"+ "\1\51\17\7\1\377\17\7\1\0\6\7\12\0\7\7"+ "\1\51\1\u0166\36\7\1\0\6\7\12\0\7\7\1\51"+ "\10\7\2\340\11\7\1\340\13\7\1\0\6\7\12\0"+ "\7\7\1\51\5\7\1\u0167\31\7\1\0\6\7\12\0"+ "\7\7\1\51\13\7\1\u0168\23\7\1\0\6\7\12\0"+ "\7\7\1\51\3\7\1\275\33\7\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\u0117\2\7\1\340\3\7\2\340"+ "\1\7\1\u0166\7\7\1\340\13\7\1\0\6\7\12\0"+ "\7\7\1\51\10\7\1\340\26\7\1\0\6\7\12\0"+ "\7\7\1\51\6\7\1\u0169\12\7\1\u016a\1\u0111\5\7"+ "\1\u016b\6\7\1\0\6\7\12\0\7\7\1\51\15\7"+ "\1\u016c\21\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\u0117\1\7\1\u0117\33\7\1\0\6\7\12\0\7\7"+ "\1\51\30\7\1\u016d\6\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\u015a\1\u016e\1\u0166\1\7\1\u016f\1\u0170"+ "\1\u0171\1\7\1\u0172\1\7\1\u0173\1\u0166\4\7\1\u0174"+ "\1\7\1\u0175\11\7\1\0\6\7\12\0\7\7\1\51"+ "\10\7\2\340\25\7\1\0\6\7\12\0\7\7\1\51"+ "\30\7\1\340\6\7\1\0\6\7\12\0\7\7\1\51"+ "\27\7\1\340\7\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\u0176\35\7\1\0\6\7\12\0\7\7\1\51"+ "\10\7\2\340\11\7\1\340\1\u0177\12\7\1\0\6\7"+ "\12\0\7\7\1\51\13\7\1\u0178\23\7\1\0\6\7"+ "\12\0\7\7\1\51\1\7\1\u0179\35\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\304\33\7\1\0\6\7"+ "\12\0\7\7\1\51\26\7\1\367\10\7\1\0\6\7"+ "\12\0\7\7\1\51\14\7\1\u017a\22\7\1\0\6\7"+ "\12\0\7\7\1\51\14\7\1\u017b\2\7\1\u017c\17\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\u017d\35\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\u017e\30\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\260\1\7"+ "\1\260\33\7\1\0\6\7\12\0\7\7\1\51\14\7"+ "\1\u017f\22\7\1\0\6\7\12\0\7\7\1\51\7\7"+ "\1\u0144\27\7\1\0\6\7\12\0\7\7\1\51\3\7"+ "\1\u0144\33\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\u0180\31\7\1\0\6\7\12\0\7\7\1\51\13\7"+ "\1\u0181\23\7\1\0\6\7\12\0\7\7\1\51\13\7"+ "\1\340\23\7\1\0\6\7\12\0\7\7\1\51\1\367"+ "\36\7\1\0\6\7\12\0\7\7\1\51\3\7\1\340"+ "\2\7\1\340\30\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\u0120\1\340\3\7\2\340\25\7\1\0\6\7"+ "\12\0\7\7\1\51\2\7\1\u0182\34\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\u0183\32\7\1\0\6\7"+ "\12\0\7\7\1\51\17\7\1\u0184\17\7\1\0\6\7"+ "\12\0\7\7\1\51\17\7\1\356\17\7\1\0\6\7"+ "\12\0\7\7\1\51\21\7\1\304\15\7\1\0\6\7"+ "\12\0\7\7\1\51\24\7\1\356\12\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\u0185\26\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\340\3\7\2\340\25\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\340\1\7"+ "\1\u0186\26\7\1\0\6\7\12\0\7\7\1\51\17\7"+ "\1\367\17\7\1\0\6\7\12\0\7\7\1\51\7\7"+ "\1\u0187\27\7\1\0\6\7\12\0\7\7\1\51\14\7"+ "\1\u0188\22\7\1\0\6\7\12\0\7\7\1\51\15\7"+ "\1\333\21\7\1\0\6\7\12\0\7\7\1\51\11\7"+ "\1\340\2\7\1\340\22\7\1\0\6\7\12\0\7\7"+ "\1\51\14\7\1\u0189\22\7\1\0\6\7\64\0\1\u018a"+ "\15\0\7\7\1\51\22\7\1\u0131\14\7\1\0\6\7"+ "\12\0\7\7\1\51\16\7\1\u018b\20\7\1\0\6\7"+ "\12\0\7\7\1\51\21\7\1\u018c\15\7\1\0\6\7"+ "\12\0\7\7\1\51\24\7\1\u018d\12\7\1\0\6\7"+ "\12\0\7\7\1\51\17\7\1\u018e\17\7\1\0\6\7"+ "\12\0\7\7\1\51\5\7\1\u018f\31\7\1\0\6\7"+ "\12\0\7\7\1\51\7\7\1\u0190\27\7\1\0\6\7"+ "\12\0\7\7\1\51\24\7\1\u0191\12\7\1\0\6\7"+ "\12\0\6\7\1\340\1\51\37\7\1\0\6\7\12\0"+ "\7\7\1\51\1\u0192\3\7\1\u0192\1\7\1\u0193\1\7"+ "\2\u0192\10\7\1\u0192\14\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\201\26\7\1\0\6\7\12\0\7\7"+ "\1\51\1\340\5\7\1\u0192\1\7\2\340\2\7\1\u013a"+ "\22\7\1\0\6\7\12\0\7\7\1\51\11\7\1\340"+ "\25\7\1\0\6\7\12\0\7\7\1\51\13\7\1\u0194"+ "\23\7\1\0\6\7\12\0\7\7\1\51\2\7\1\u0195"+ "\34\7\1\0\6\7\12\0\7\7\1\51\1\340\5\7"+ "\1\u0192\1\7\2\340\25\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\u0196\33\7\1\0\6\7\12\0\6\7"+ "\1\u0192\1\51\1\u0192\3\7\1\u0192\1\7\1\u0192\1\7"+ "\2\u0192\12\7\1\u0192\12\7\1\0\6\7\12\0\7\7"+ "\1\51\13\7\1\u0197\13\7\1\u0197\1\7\1\203\5\7"+ "\1\0\6\7\12\0\7\7\1\51\22\7\1\u0198\14\7"+ "\1\0\6\7\12\0\7\7\1\51\7\7\1\u0199\27\7"+ "\1\0\6\7\12\0\6\7\1\u019a\1\51\37\7\1\0"+ "\6\7\12\0\7\7\1\51\32\7\1\340\4\7\1\0"+ "\6\7\12\0\7\7\1\51\1\7\1\u019b\35\7\1\0"+ "\6\7\12\0\7\7\1\51\4\7\1\u019c\32\7\1\0"+ "\6\7\12\0\7\7\1\51\2\7\1\340\34\7\1\0"+ "\6\7\12\0\7\7\1\51\2\7\1\u0144\34\7\1\0"+ "\6\7\12\0\7\7\1\51\1\7\1\u019d\35\7\1\0"+ "\6\7\12\0\7\7\1\51\23\7\1\u019e\13\7\1\0"+ "\6\7\12\0\7\7\1\51\21\7\1\u019f\5\7\1\u01a0"+ "\7\7\1\0\6\7\12\0\7\7\1\51\16\7\1\u01a1"+ "\20\7\1\0\6\7\12\0\7\7\1\51\4\7\1\u0137"+ "\32\7\1\0\6\7\12\0\7\7\1\51\10\7\2\340"+ "\3\7\1\340\5\7\1\340\13\7\1\0\6\7\12\0"+ "\7\7\1\51\3\7\1\u0150\1\340\3\7\2\340\4\7"+ "\1\u01a2\4\7\1\340\13\7\1\0\6\7\12\0\7\7"+ "\1\51\1\u01a3\36\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\u01a4\12\7\1\u01a5\20\7\1\0\6\7\12\0"+ "\7\7\1\51\3\7\1\u0150\1\340\3\7\2\340\1\7"+ "\1\340\2\7\1\u01a2\20\7\1\0\6\7\12\0\7\7"+ "\1\51\4\7\1\340\4\7\1\340\25\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\u0137\12\7\1\u01a6\20\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\u01a7\30\7"+ "\1\0\6\7\12\0\7\7\1\51\7\7\1\u01a8\27\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\u0137\5\7"+ "\1\u01a9\6\7\1\u01aa\11\7\1\0\6\7\12\0\7\7"+ "\1\51\21\7\1\u01ab\15\7\1\0\6\7\12\0\7\7"+ "\1\51\2\7\1\u01ac\34\7\1\0\6\7\12\0\7\7"+ "\1\51\14\7\1\u0137\22\7\1\0\6\7\12\0\7\7"+ "\1\51\14\7\1\u01ad\22\7\1\0\6\7\12\0\7\7"+ "\1\51\2\7\1\u01ae\34\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\2\340\1\7\1\340\1\7\2\340\11\7"+ "\1\340\13\7\1\0\6\7\12\0\7\7\1\51\10\7"+ "\2\364\11\7\1\364\13\7\1\0\6\7\12\0\7\7"+ "\1\51\31\7\1\u01af\5\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\u0117\33\7\1\0\6\7\12\0\7\7"+ "\1\51\3\7\1\u01b0\2\7\1\u01b1\1\7\1\u01b2\26\7"+ "\1\0\6\7\12\0\7\7\1\51\3\7\1\u01b3\2\7"+ "\1\u01b4\1\7\1\u01b5\12\7\1\u01b5\13\7\1\0\6\7"+ "\12\0\7\7\1\51\1\7\1\u01b6\1\7\1\u01b7\33\7"+ "\1\0\6\7\12\0\7\7\1\51\2\7\1\201\34\7"+ "\1\0\6\7\12\0\7\7\1\51\27\7\1\260\7\7"+ "\1\0\6\7\12\0\7\7\1\51\2\7\1\u0109\34\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\u01b8\31\7"+ "\1\0\6\7\12\0\7\7\1\51\21\7\1\233\15\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\u0117\35\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\u01b9\35\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\u0102\30\7"+ "\1\0\6\7\12\0\7\7\1\51\21\7\1\u01ba\15\7"+ "\1\0\6\7\12\0\7\7\1\51\13\7\1\u01ba\23\7"+ "\1\0\6\7\12\0\7\7\1\51\21\7\1\u01bb\15\7"+ "\1\0\6\7\12\0\7\7\1\51\30\7\1\u01bc\6\7"+ "\1\0\6\7\12\0\7\7\1\51\7\7\1\u01bd\27\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\2\u01be\11\7"+ "\1\u01be\13\7\1\0\6\7\12\0\7\7\1\51\3\7"+ "\1\u01bf\33\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\u0117\21\7\1\u01be\1\7\1\u01c0\11\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\u01be\12\7\1\u01be\13\7"+ "\1\0\6\7\12\0\7\7\1\51\17\7\1\u01c1\17\7"+ "\1\0\6\7\12\0\7\7\1\51\16\7\1\340\20\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\340\4\7"+ "\1\u01c2\21\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\u0117\4\7\1\u01c3\1\7\1\u01c0\26\7\1\0\6\7"+ "\12\0\7\7\1\51\13\7\1\201\5\7\1\117\15\7"+ "\1\0\6\7\12\0\7\7\1\51\21\7\1\367\15\7"+ "\1\0\6\7\12\0\7\7\1\51\24\7\1\122\12\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\u01c4\35\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\u01c5\31\7"+ "\1\0\6\7\12\0\7\7\1\51\15\7\1\u01c6\21\7"+ "\1\0\6\7\12\0\7\7\1\51\14\7\1\u01bc\22\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\u01c7\26\7"+ "\1\0\6\7\12\0\7\7\1\51\2\7\1\u01c8\34\7"+ "\1\0\6\7\12\0\7\7\1\51\17\7\1\u010f\17\7"+ "\1\0\6\7\12\0\7\7\1\51\17\7\1\u01c9\17\7"+ "\1\0\6\7\12\0\7\7\1\51\6\7\1\377\30\7"+ "\1\0\6\7\12\0\7\7\1\51\30\7\1\u01ca\6\7"+ "\1\0\6\7\12\0\7\7\1\51\3\7\1\u01cb\33\7"+ "\1\0\6\7\12\0\7\7\1\51\4\7\1\340\3\7"+ "\2\340\11\7\1\340\12\7\1\117\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\u0104\35\7\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\u01cc\35\7\1\0\6\7\12\0"+ "\7\7\1\51\15\7\1\u01cd\21\7\1\0\6\7\12\0"+ "\7\7\1\51\15\7\1\u01ce\21\7\1\0\6\7\65\0"+ "\1\u01cf\14\0\7\7\1\51\22\7\1\u01d0\14\7\1\0"+ "\6\7\12\0\7\7\1\51\5\7\1\330\31\7\1\0"+ "\6\7\12\0\7\7\1\51\21\7\1\u01d1\15\7\1\0"+ "\6\7\12\0\7\7\1\51\15\7\1\u01d2\21\7\1\0"+ "\6\7\12\0\7\7\1\51\2\7\1\233\34\7\1\0"+ "\6\7\12\0\7\7\1\51\2\7\1\202\5\7\1\260"+ "\2\7\1\u01d3\2\7\1\u0131\2\7\1\117\3\7\1\177"+ "\11\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u0192"+ "\35\7\1\0\6\7\12\0\7\7\1\51\24\7\1\340"+ "\12\7\1\0\6\7\12\0\7\7\1\51\15\7\1\260"+ "\21\7\1\0\6\7\12\0\7\7\1\51\17\7\1\275"+ "\17\7\1\0\6\7\12\0\7\7\1\51\31\7\1\340"+ "\5\7\1\0\6\7\12\0\7\7\1\51\13\7\1\233"+ "\23\7\1\0\6\7\12\0\7\7\1\51\1\7\1\u0192"+ "\20\7\1\u0192\14\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\u0141\35\7\1\0\6\7\12\0\7\7\1\51"+ "\21\7\1\117\5\7\1\203\7\7\1\0\6\7\12\0"+ "\7\7\1\51\22\7\1\u01d4\14\7\1\0\6\7\12\0"+ "\7\7\1\51\14\7\1\233\5\7\1\u01d5\14\7\1\0"+ "\6\7\12\0\7\7\1\51\23\7\1\u0120\13\7\1\0"+ "\6\7\12\0\7\7\1\51\17\7\1\u0120\17\7\1\0"+ "\6\7\12\0\7\7\1\51\10\7\1\u01d6\26\7\1\0"+ "\6\7\12\0\7\7\1\51\3\7\1\u0150\33\7\1\0"+ "\6\7\12\0\7\7\1\51\4\7\1\340\1\7\1\340"+ "\1\7\1\u01d7\1\340\13\7\1\u0137\11\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\u01d8\33\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\u01d9\33\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\340\32\7\1\0\6\7"+ "\12\0\7\7\1\51\11\7\1\374\25\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\u01da\33\7\1\0\6\7"+ "\12\0\7\7\1\51\10\7\1\117\26\7\1\0\6\7"+ "\12\0\7\7\1\51\11\7\1\340\2\7\1\u0137\1\7"+ "\1\u0137\20\7\1\0\6\7\12\0\7\7\1\51\17\7"+ "\1\u01db\17\7\1\0\6\7\12\0\7\7\1\51\30\7"+ "\1\u01dc\6\7\1\0\6\7\12\0\7\7\1\51\6\7"+ "\1\340\2\7\1\340\11\7\1\340\13\7\1\0\6\7"+ "\12\0\7\7\1\51\25\7\1\u01dd\11\7\1\0\6\7"+ "\12\0\7\7\1\51\4\7\1\340\16\7\1\340\13\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u01de\5\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u01df\5\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u0166\5\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u01e0\5\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u01e1\5\7"+ "\1\0\6\7\12\0\7\7\1\51\31\7\1\u015d\5\7"+ "\1\0\6\7\12\0\7\7\1\51\3\7\1\u01e2\2\7"+ "\1\u01e2\30\7\1\0\6\7\12\0\7\7\1\51\3\7"+ "\1\u01e3\2\7\1\u01e3\30\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\374\26\7\1\0\6\7\12\0\7\7"+ "\1\51\10\7\1\340\12\7\1\340\13\7\1\0\6\7"+ "\12\0\7\7\1\51\2\7\1\u01e4\34\7\1\0\6\7"+ "\12\0\7\7\1\51\20\7\1\u01e5\16\7\1\0\6\7"+ "\12\0\7\7\1\51\15\7\1\u01e6\21\7\1\0\6\7"+ "\12\0\7\7\1\51\3\7\1\u0133\22\7\1\u0133\10\7"+ "\1\0\6\7\12\0\7\7\1\51\30\7\1\u0166\6\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\260\35\7"+ "\1\0\6\7\12\0\7\7\1\51\1\7\1\u0117\13\7"+ "\1\340\4\7\1\u01b9\1\340\1\7\1\122\11\7\1\0"+ "\6\7\12\0\7\7\1\51\26\7\1\u0133\10\7\1\0"+ "\6\7\12\0\7\7\1\51\5\7\1\340\10\7\1\340"+ "\20\7\1\0\6\7\12\0\7\7\1\51\21\7\1\u017c"+ "\15\7\1\0\6\7\12\0\7\7\1\51\7\7\1\u01e7"+ "\27\7\1\0\6\7\12\0\7\7\1\51\1\u01bc\36\7"+ "\1\0\6\7\12\0\7\7\1\51\22\7\1\u01e8\14\7"+ "\1\0\6\7\12\0\7\7\1\51\17\7\1\u01e9\17\7"+ "\1\0\6\7\12\0\7\7\1\51\5\7\1\u01bc\31\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\u0166\14\7"+ "\1\u0166\11\7\1\0\6\7\12\0\7\7\1\51\3\7"+ "\1\u01bc\33\7\1\0\6\7\12\0\7\7\1\51\21\7"+ "\1\u01ea\15\7\1\0\6\7\12\0\7\7\1\51\5\7"+ "\1\u01eb\31\7\1\0\6\7\12\0\7\7\1\51\16\7"+ "\1\u01ec\20\7\1\0\6\7\66\0\1\u01ed\13\0\7\7"+ "\1\51\14\7\1\201\22\7\1\0\6\7\12\0\7\7"+ "\1\51\34\7\1\u01ee\2\7\1\0\6\7\12\0\7\7"+ "\1\51\14\7\1\u01d1\22\7\1\0\6\7\12\0\7\7"+ "\1\51\16\7\1\340\2\7\1\340\15\7\1\0\6\7"+ "\12\0\7\7\1\51\17\7\1\u0141\11\7\1\233\5\7"+ "\1\0\6\7\12\0\7\7\1\51\17\7\1\u0141\17\7"+ "\1\0\6\7\12\0\7\7\1\51\23\7\1\u01ef\13\7"+ "\1\0\6\7\12\0\7\7\1\51\10\7\1\u0137\1\u01a6"+ "\25\7\1\0\6\7\12\0\7\7\1\51\11\7\1\u01a6"+ "\25\7\1\0\6\7\12\0\7\7\1\51\30\7\1\u01a6"+ "\6\7\1\0\6\7\12\0\7\7\1\51\2\7\1\u01f0"+ "\34\7\1\0\6\7\12\0\7\7\1\51\10\7\1\u01f1"+ "\14\7\1\u01f1\11\7\1\0\6\7\12\0\7\7\1\51"+ "\27\7\1\u01f2\7\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\u01f3\35\7\1\0\6\7\12\0\7\7\1\51"+ "\1\7\1\u01f4\35\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\u01f5\33\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\u01f6\33\7\1\0\6\7\12\0\7\7\1\51"+ "\31\7\1\152\5\7\1\0\6\7\12\0\7\7\1\51"+ "\31\7\1\u01f7\5\7\1\0\6\7\12\0\7\7\1\51"+ "\10\7\1\u01f8\26\7\1\0\6\7\12\0\7\7\1\51"+ "\27\7\1\u01f9\7\7\1\0\6\7\12\0\7\7\1\51"+ "\24\7\1\u01fa\12\7\1\0\6\7\12\0\7\7\1\51"+ "\21\7\1\u01bc\15\7\1\0\6\7\12\0\7\7\1\51"+ "\17\7\1\u01bc\17\7\1\0\6\7\12\0\6\7\1\u01e8"+ "\1\51\37\7\1\0\6\7\12\0\7\7\1\51\23\7"+ "\1\u01a6\13\7\1\0\6\7\12\0\7\7\1\51\6\7"+ "\1\u01fb\30\7\1\0\6\7\12\0\7\7\1\51\1\7"+ "\1\u01fc\35\7\1\0\6\7\67\0\1\u01fd\12\0\7\7"+ "\1\51\35\7\1\340\1\7\1\0\6\7\12\0\7\7"+ "\1\51\6\7\1\117\30\7\1\0\6\7\12\0\7\7"+ "\1\51\25\7\1\u01fe\11\7\1\0\6\7\12\0\7\7"+ "\1\51\4\7\1\u0137\3\7\1\117\1\374\11\7\1\u01ef"+ "\13\7\1\0\6\7\12\0\7\7\1\51\4\7\1\340"+ "\3\7\2\340\11\7\1\340\7\7\1\u01a6\3\7\1\0"+ "\6\7\12\0\7\7\1\51\6\7\1\340\1\7\1\340"+ "\26\7\1\0\6\7\12\0\7\7\1\51\3\7\1\340"+ "\4\7\1\340\26\7\1\0\6\7\12\0\7\7\1\51"+ "\6\7\1\340\1\7\1\340\12\7\1\340\13\7\1\0"+ "\6\7\12\0\7\7\1\51\3\7\1\340\4\7\1\340"+ "\12\7\1\340\13\7\1\0\6\7\12\0\7\7\1\51"+ "\3\7\1\u01b9\33\7\1\0\6\7\12\0\7\7\1\51"+ "\5\7\1\77\31\7\1\0\6\7\12\0\7\7\1\51"+ "\21\7\1\u01ff\15\7\1\0\6\7\12\0\7\7\1\51"+ "\15\7\1\u0200\5\7\1\340\13\7\1\0\6\7\12\0"+ "\7\7\1\51\2\7\1\u0201\34\7\1\0\6\7\12\0"+ "\7\7\1\51\1\7\1\u011d\35\7\1\0\6\7\12\0"+ "\7\7\1\51\13\7\1\u0202\3\7\1\u0203\17\7\1\0"+ "\6\7\12\0\7\7\1\51\13\7\1\u0204\23\7\1\0"+ "\6\7\12\0\7\7\1\51\5\7\1\u0205\31\7\1\0"+ "\6\7\12\0\7\7\1\51\17\7\1\u0206\17\7\1\0"+ "\6\7\12\0\4\7\1\340\2\7\1\51\31\7\2\340"+ "\4\7\1\0\6\7\12\0\7\7\1\51\5\7\1\u0207"+ "\31\7\1\0\6\7\12\0\7\7\1\51\3\7\1\u0208"+ "\33\7\1\0\6\7\12\0\7\7\1\51\5\7\1\340"+ "\31\7\1\0\6\7\12\0\7\7\1\51\3\7\1\u0209"+ "\33\7\1\0\6\7\12\0\7\7\1\51\17\7\1\u01a6"+ "\17\7\1\0\6\7\12\0\7\7\1\51\3\7\1\u020a"+ "\33\7\1\0\6\7\12\0\7\7\1\51\22\7\1\77"+ "\14\7\1\0\6\7\4\0"; private static int [] zzUnpackTrans() { int [] result = new int[28000]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; private static final char[] EMPTY_BUFFER = new char[0]; private static final int YYEOF = -1; private static Reader zzReader; // Fake /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state aState */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\1\1\1\11\6\1\1\11\26\1\4\11"+ "\1\1\1\0\2\11\1\0\161\1\1\0\214\1\1\0"+ "\140\1\1\0\104\1\1\0\35\1\1\0\17\1\1\11"+ "\15\1"; private static int [] zzUnpackAttribute() { int [] result = new int[522]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** this buffer may contains the current text array to be matched when it is cheap to acquire it */ private char[] zzBufferArray; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /* user code: */ public _AsmIntelLexer() { this(null); } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public _AsmIntelLexer(Reader in) { zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 1734) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } @Override public final int getTokenStart(){ return zzStartRead; } @Override public final int getTokenEnd(){ return getTokenStart() + yylength(); } @Override public void reset(CharSequence buffer, int start, int end, int initialState){ zzBuffer = buffer; zzBufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; zzPushbackPos = 0; zzAtEOF = false; zzAtBOL = true; zzEndRead = end; yybegin(initialState); } /** * Refills the input buffer. * * @return false, iff there was new input. * * @exception IOException if any I/O-Error occurs */ private boolean zzRefill() throws IOException { return true; } /** * Returns the current lexical state. */ @Override public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ @Override public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position pos from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception IOException if any I/O-Error occurs */ @Override public IElementType advance() throws IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; char[] zzBufferArrayL = zzBufferArray; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++); else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 17: return FLAG; case 19: break; case 8: return COMMA; case 20: break; case 4: return INT; case 21: break; case 10: return LINE_COMMENT; case 22: break; case 3: return IDENTIFIER; case 23: break; case 12: return LABEL; case 24: break; case 1: return TokenType.BAD_CHARACTER; case 25: break; case 14: return HEX; case 26: break; case 2: return TokenType.WHITE_SPACE; case 27: break; case 5: return COLON; case 28: break; case 6: return LPAREN; case 29: break; case 7: return RPAREN; case 30: break; case 16: return TEXT; case 31: break; case 11: return STRING; case 32: break; case 9: return BIT_OR; case 33: break; case 18: return IMPORT; case 34: break; case 15: return INSTRUCTION; case 35: break; case 13: return PSEUDO_REG; case 36: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; return null; } else { zzScanError(ZZ_NO_MATCH); } } } } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/parser/AsmIntelParser.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.parser; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiBuilder.Marker; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import static com.intellij.lang.parser.GeneratedParserUtilBase.*; import com.intellij.psi.tree.IElementType; import com.intellij.lang.ASTNode; import com.intellij.psi.tree.TokenSet; import com.intellij.lang.PsiParser; import com.intellij.lang.LightPsiParser; @SuppressWarnings({"SimplifiableIfStatement", "UnusedAssignment"}) public class AsmIntelParser implements PsiParser, LightPsiParser { public ASTNode parse(IElementType t, PsiBuilder b) { parseLight(t, b); return b.getTreeBuilt(); } public void parseLight(IElementType t, PsiBuilder b) { boolean r; b = adapt_builder_(t, b, this, null); Marker m = enter_section_(b, 0, _COLLAPSE_, null); if (t == FRAME_SIZE) { r = FrameSize(b, 0); } else if (t == FUNCTION) { r = Function(b, 0); } else if (t == FUNCTION_BODY) { r = FunctionBody(b, 0); } else if (t == FUNCTION_FLAGS) { r = FunctionFlags(b, 0); } else if (t == FUNCTION_HEADER) { r = FunctionHeader(b, 0); } else if (t == INSTRUCTION_STMT) { r = InstructionStmt(b, 0); } else if (t == LITERAL) { r = Literal(b, 0); } else if (t == OPERANDS) { r = Operands(b, 0); } else if (t == PREPROCESSOR_DIRECTIVE) { r = PreprocessorDirective(b, 0); } else if (t == STATEMENT) { r = Statement(b, 0); } else { r = parse_root_(t, b, 0); } exit_section_(b, 0, m, t, r, true, TRUE_CONDITION); } protected boolean parse_root_(IElementType t, PsiBuilder b, int l) { return File(b, l + 1); } /* ********************************************************** */ // Statement* static boolean File(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "File")) return false; int c = current_position_(b); while (true) { if (!Statement(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "File", c)) break; c = current_position_(b); } return true; } /* ********************************************************** */ // '$' Literal ['-' Literal] public static boolean FrameSize(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FrameSize")) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FRAME_SIZE, ""); r = consumeToken(b, "$"); r = r && Literal(b, l + 1); r = r && FrameSize_2(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // ['-' Literal] private static boolean FrameSize_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FrameSize_2")) return false; FrameSize_2_0(b, l + 1); return true; } // '-' Literal private static boolean FrameSize_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FrameSize_2_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, "-"); r = r && Literal(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // FunctionHeader FunctionBody public static boolean Function(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Function")) return false; if (!nextTokenIs(b, TEXT)) return false; boolean r; Marker m = enter_section_(b); r = FunctionHeader(b, l + 1); r = r && FunctionBody(b, l + 1); exit_section_(b, m, FUNCTION, r); return r; } /* ********************************************************** */ // ( InstructionStmt | LABEL )* public static boolean FunctionBody(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionBody")) return false; Marker m = enter_section_(b, l, _NONE_, FUNCTION_BODY, ""); int c = current_position_(b); while (true) { if (!FunctionBody_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "FunctionBody", c)) break; c = current_position_(b); } exit_section_(b, l, m, true, false, null); return true; } // InstructionStmt | LABEL private static boolean FunctionBody_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionBody_0")) return false; boolean r; Marker m = enter_section_(b); r = InstructionStmt(b, l + 1); if (!r) r = consumeToken(b, LABEL); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // FLAG | '(' FLAG ( '|' FLAG )* ')' public static boolean FunctionFlags(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionFlags")) return false; if (!nextTokenIs(b, "", LPAREN, FLAG)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, FUNCTION_FLAGS, ""); r = consumeToken(b, FLAG); if (!r) r = FunctionFlags_1(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } // '(' FLAG ( '|' FLAG )* ')' private static boolean FunctionFlags_1(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionFlags_1")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, LPAREN); r = r && consumeToken(b, FLAG); r = r && FunctionFlags_1_2(b, l + 1); r = r && consumeToken(b, RPAREN); exit_section_(b, m, null, r); return r; } // ( '|' FLAG )* private static boolean FunctionFlags_1_2(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionFlags_1_2")) return false; int c = current_position_(b); while (true) { if (!FunctionFlags_1_2_0(b, l + 1)) break; if (!empty_element_parsed_guard_(b, "FunctionFlags_1_2", c)) break; c = current_position_(b); } return true; } // '|' FLAG private static boolean FunctionFlags_1_2_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionFlags_1_2_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, BIT_OR); r = r && consumeToken(b, FLAG); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // TEXT identifier '(' PSEUDO_REG ')' ',' FunctionFlags [',' FrameSize] public static boolean FunctionHeader(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionHeader")) return false; if (!nextTokenIs(b, TEXT)) return false; boolean r; Marker m = enter_section_(b); r = consumeTokens(b, 0, TEXT, IDENTIFIER); r = r && consumeToken(b, LPAREN); r = r && consumeToken(b, PSEUDO_REG); r = r && consumeToken(b, RPAREN); r = r && consumeToken(b, COMMA); r = r && FunctionFlags(b, l + 1); r = r && FunctionHeader_7(b, l + 1); exit_section_(b, m, FUNCTION_HEADER, r); return r; } // [',' FrameSize] private static boolean FunctionHeader_7(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionHeader_7")) return false; FunctionHeader_7_0(b, l + 1); return true; } // ',' FrameSize private static boolean FunctionHeader_7_0(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "FunctionHeader_7_0")) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, COMMA); r = r && FrameSize(b, l + 1); exit_section_(b, m, null, r); return r; } /* ********************************************************** */ // INSTRUCTION Operands public static boolean InstructionStmt(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "InstructionStmt")) return false; if (!nextTokenIs(b, INSTRUCTION)) return false; boolean r; Marker m = enter_section_(b); r = consumeToken(b, INSTRUCTION); r = r && Operands(b, l + 1); exit_section_(b, m, INSTRUCTION_STMT, r); return r; } /* ********************************************************** */ // int | hex public static boolean Literal(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Literal")) return false; if (!nextTokenIs(b, "", HEX, INT)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, LITERAL, ""); r = consumeToken(b, INT); if (!r) r = consumeToken(b, HEX); exit_section_(b, l, m, r, false, null); return r; } /* ********************************************************** */ public static boolean Operands(PsiBuilder b, int l) { Marker m = enter_section_(b); exit_section_(b, m, OPERANDS, true); return true; } /* ********************************************************** */ // import STRING public static boolean PreprocessorDirective(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "PreprocessorDirective")) return false; if (!nextTokenIs(b, IMPORT)) return false; boolean r; Marker m = enter_section_(b); r = consumeTokens(b, 0, IMPORT, STRING); exit_section_(b, m, PREPROCESSOR_DIRECTIVE, r); return r; } /* ********************************************************** */ // PreprocessorDirective | Function public static boolean Statement(PsiBuilder b, int l) { if (!recursion_guard_(b, l, "Statement")) return false; if (!nextTokenIs(b, "", TEXT, IMPORT)) return false; boolean r; Marker m = enter_section_(b, l, _NONE_, STATEMENT, ""); r = PreprocessorDirective(b, l + 1); if (!r) r = Function(b, l + 1); exit_section_(b, l, m, r, false, null); return r; } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelFrameSize.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelFrameSize extends PsiElement { @NotNull List getLiteralList(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelFunction.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelFunction extends PsiElement { @NotNull AsmIntelFunctionBody getFunctionBody(); @NotNull AsmIntelFunctionHeader getFunctionHeader(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelFunctionBody.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelFunctionBody extends PsiElement { @NotNull List getInstructionStmtList(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelFunctionFlags.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelFunctionFlags extends PsiElement { } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelFunctionHeader.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelFunctionHeader extends PsiElement { @Nullable AsmIntelFrameSize getFrameSize(); @NotNull AsmIntelFunctionFlags getFunctionFlags(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelInstructionStmt.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelInstructionStmt extends PsiElement { @NotNull AsmIntelOperands getOperands(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelLiteral.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelLiteral extends PsiElement { } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelOperands.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelOperands extends PsiElement { } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelPreprocessorDirective.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelPreprocessorDirective extends PsiElement { } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelStatement.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface AsmIntelStatement extends PsiElement { @Nullable AsmIntelFunction getFunction(); @Nullable AsmIntelPreprocessorDirective getPreprocessorDirective(); } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelTypes.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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. */ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import com.intellij.psi.tree.IElementType; import com.intellij.psi.PsiElement; import com.intellij.lang.ASTNode; import com.plan9.intel.lang.core.lexer.AsmIntelTokenType; import com.plan9.intel.lang.core.psi.impl.*; public interface AsmIntelTypes { IElementType FRAME_SIZE = new AsmIntelElementType("FRAME_SIZE"); IElementType FUNCTION = new AsmIntelElementType("FUNCTION"); IElementType FUNCTION_BODY = new AsmIntelElementType("FUNCTION_BODY"); IElementType FUNCTION_FLAGS = new AsmIntelElementType("FUNCTION_FLAGS"); IElementType FUNCTION_HEADER = new AsmIntelElementType("FUNCTION_HEADER"); IElementType INSTRUCTION_STMT = new AsmIntelElementType("INSTRUCTION_STMT"); IElementType LITERAL = new AsmIntelElementType("LITERAL"); IElementType OPERANDS = new AsmIntelElementType("OPERANDS"); IElementType PREPROCESSOR_DIRECTIVE = new AsmIntelElementType("PREPROCESSOR_DIRECTIVE"); IElementType STATEMENT = new AsmIntelElementType("STATEMENT"); IElementType BIT_OR = new AsmIntelTokenType("|"); IElementType COLON = new AsmIntelTokenType(":"); IElementType COMMA = new AsmIntelTokenType(","); IElementType FLAG = new AsmIntelTokenType("FLAG"); IElementType HEX = new AsmIntelTokenType("hex"); IElementType IDENTIFIER = new AsmIntelTokenType("identifier"); IElementType IMPORT = new AsmIntelTokenType("import"); IElementType INSTRUCTION = new AsmIntelTokenType("INSTRUCTION"); IElementType INT = new AsmIntelTokenType("int"); IElementType LABEL = new AsmIntelTokenType("LABEL"); IElementType LPAREN = new AsmIntelTokenType("("); IElementType PSEUDO_REG = new AsmIntelTokenType("PSEUDO_REG"); IElementType RPAREN = new AsmIntelTokenType(")"); IElementType STRING = new AsmIntelTokenType("STRING"); IElementType TEXT = new AsmIntelTokenType("TEXT"); class Factory { public static PsiElement createElement(ASTNode node) { IElementType type = node.getElementType(); if (type == FRAME_SIZE) { return new AsmIntelFrameSizeImpl(node); } else if (type == FUNCTION) { return new AsmIntelFunctionImpl(node); } else if (type == FUNCTION_BODY) { return new AsmIntelFunctionBodyImpl(node); } else if (type == FUNCTION_FLAGS) { return new AsmIntelFunctionFlagsImpl(node); } else if (type == FUNCTION_HEADER) { return new AsmIntelFunctionHeaderImpl(node); } else if (type == INSTRUCTION_STMT) { return new AsmIntelInstructionStmtImpl(node); } else if (type == LITERAL) { return new AsmIntelLiteralImpl(node); } else if (type == OPERANDS) { return new AsmIntelOperandsImpl(node); } else if (type == PREPROCESSOR_DIRECTIVE) { return new AsmIntelPreprocessorDirectiveImpl(node); } else if (type == STATEMENT) { return new AsmIntelStatementImpl(node); } throw new AssertionError("Unknown element type: " + type); } } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/AsmIntelVisitor.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiElement; public class AsmIntelVisitor extends PsiElementVisitor { public void visitFrameSize(@NotNull AsmIntelFrameSize o) { visitPsiElement(o); } public void visitFunction(@NotNull AsmIntelFunction o) { visitPsiElement(o); } public void visitFunctionBody(@NotNull AsmIntelFunctionBody o) { visitPsiElement(o); } public void visitFunctionFlags(@NotNull AsmIntelFunctionFlags o) { visitPsiElement(o); } public void visitFunctionHeader(@NotNull AsmIntelFunctionHeader o) { visitPsiElement(o); } public void visitInstructionStmt(@NotNull AsmIntelInstructionStmt o) { visitPsiElement(o); } public void visitLiteral(@NotNull AsmIntelLiteral o) { visitPsiElement(o); } public void visitOperands(@NotNull AsmIntelOperands o) { visitPsiElement(o); } public void visitPreprocessorDirective(@NotNull AsmIntelPreprocessorDirective o) { visitPsiElement(o); } public void visitStatement(@NotNull AsmIntelStatement o) { visitPsiElement(o); } public void visitPsiElement(@NotNull PsiElement o) { visitElement(o); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelFrameSizeImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelFrameSizeImpl extends AsmIntelElementImpl implements AsmIntelFrameSize { public AsmIntelFrameSizeImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitFrameSize(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getLiteralList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, AsmIntelLiteral.class); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelFunctionBodyImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelFunctionBodyImpl extends AsmIntelElementImpl implements AsmIntelFunctionBody { public AsmIntelFunctionBodyImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitFunctionBody(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List getInstructionStmtList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, AsmIntelInstructionStmt.class); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelFunctionFlagsImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelFunctionFlagsImpl extends AsmIntelElementImpl implements AsmIntelFunctionFlags { public AsmIntelFunctionFlagsImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitFunctionFlags(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelFunctionHeaderImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelFunctionHeaderImpl extends AsmIntelElementImpl implements AsmIntelFunctionHeader { public AsmIntelFunctionHeaderImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitFunctionHeader(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @Nullable public AsmIntelFrameSize getFrameSize() { return findChildByClass(AsmIntelFrameSize.class); } @Override @NotNull public AsmIntelFunctionFlags getFunctionFlags() { return findNotNullChildByClass(AsmIntelFunctionFlags.class); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelFunctionImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelFunctionImpl extends AsmIntelElementImpl implements AsmIntelFunction { public AsmIntelFunctionImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitFunction(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @NotNull public AsmIntelFunctionBody getFunctionBody() { return findNotNullChildByClass(AsmIntelFunctionBody.class); } @Override @NotNull public AsmIntelFunctionHeader getFunctionHeader() { return findNotNullChildByClass(AsmIntelFunctionHeader.class); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelInstructionStmtImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelInstructionStmtImpl extends AsmIntelElementImpl implements AsmIntelInstructionStmt { public AsmIntelInstructionStmtImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitInstructionStmt(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @NotNull public AsmIntelOperands getOperands() { return findNotNullChildByClass(AsmIntelOperands.class); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelLiteralImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelLiteralImpl extends AsmIntelElementImpl implements AsmIntelLiteral { public AsmIntelLiteralImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitLiteral(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelOperandsImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelOperandsImpl extends AsmIntelElementImpl implements AsmIntelOperands { public AsmIntelOperandsImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitOperands(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelPreprocessorDirectiveImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelPreprocessorDirectiveImpl extends AsmIntelElementImpl implements AsmIntelPreprocessorDirective { public AsmIntelPreprocessorDirectiveImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitPreprocessorDirective(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } } ================================================ FILE: plan9/gen/com/plan9/intel/lang/core/psi/impl/AsmIntelStatementImpl.java ================================================ // This is a generated file. Not intended for manual editing. package com.plan9.intel.lang.core.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; import com.plan9.intel.lang.core.psi.*; public class AsmIntelStatementImpl extends AsmIntelElementImpl implements AsmIntelStatement { public AsmIntelStatementImpl(ASTNode node) { super(node); } public void accept(@NotNull AsmIntelVisitor visitor) { visitor.visitStatement(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof AsmIntelVisitor) accept((AsmIntelVisitor)visitor); else super.accept(visitor); } @Override @Nullable public AsmIntelFunction getFunction() { return findChildByClass(AsmIntelFunction.class); } @Override @Nullable public AsmIntelPreprocessorDirective getPreprocessorDirective() { return findChildByClass(AsmIntelPreprocessorDirective.class); } } ================================================ FILE: plan9/resources/colorscheme/AsmIntelDarcula.xml ================================================ ================================================ FILE: plan9/resources/colorscheme/AsmIntelDefault.xml ================================================ ================================================ FILE: plan9/resources/colorscheme/highlighterDemoText.s ================================================ // a line comment TEXT foo(SB),NOSPLIT,$24-8 label: MOVB (SI)(BX*1), CX XORL $0xffff, BX // convert EQ to NE ANDL $0x0f0f >> 1, CX CLD CALL runtime·args(SB) RET DATA bad_proc_msg<>+0x00(SB)/8, $"This pro" DATA bad_proc_msg<>+0x08(SB)/8, $"gram can" ================================================ FILE: plan9/src/com/plan9/intel/AsmIntelFileType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel; import com.plan9.intel.lang.AsmIntelLanguage; import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class AsmIntelFileType extends LanguageFileType { public static final AsmIntelFileType INSTANCE = new AsmIntelFileType(); private AsmIntelFileType() { super(AsmIntelLanguage.INSTANCE); } @NotNull @Override public String getName() { return "x86 Plan9 Assembly"; } @NotNull @Override public String getDescription() { return "x86 Plan9 Assembly file"; } @NotNull @Override public String getDefaultExtension() { return "s"; } @Nullable @Override public Icon getIcon() { return Icons.FILE; } } ================================================ FILE: plan9/src/com/plan9/intel/AsmIntelFileTypeFactory.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import com.intellij.openapi.fileTypes.WildcardFileNameMatcher; import org.jetbrains.annotations.NotNull; public class AsmIntelFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer consumer) { consumer.consume(AsmIntelFileType.INSTANCE, new WildcardFileNameMatcher("*_amd64.s"), new WildcardFileNameMatcher("*_amd64p32.s"), new WildcardFileNameMatcher("*_386.s")); } } ================================================ FILE: plan9/src/com/plan9/intel/Icons.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel; import com.intellij.openapi.util.IconLoader; import javax.swing.*; public class Icons { public static final Icon FILE = IconLoader.getIcon("/icons/CPU.png"); private Icons() {} } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelColorsAndFontsPage.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.ide.highlighting; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.ResourceUtil; import com.plan9.intel.Icons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.IOException; import java.net.URL; import java.util.Map; import static com.plan9.intel.ide.highlighting.AsmIntelSyntaxHighlightingColors.*; public class AsmIntelColorsAndFontsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Keyword", KEYWORD), new AttributesDescriptor("Line Comment", LINE_COMMENT), new AttributesDescriptor("Instruction", INSTRUCTION), new AttributesDescriptor("Pseudo Instruction", PSEUDO_INSTRUCTION), new AttributesDescriptor("String", STRING), new AttributesDescriptor("Label", LABEL), new AttributesDescriptor("Flags", FLAG), new AttributesDescriptor("Registers", REGISTER), new AttributesDescriptor("Parenthesis", PARENTHESIS), new AttributesDescriptor("Operator", OPERATOR), new AttributesDescriptor("Identifier", IDENTIFIER), }; @Nullable @Override public Icon getIcon() { return Icons.FILE; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new AsmIntelSyntaxHighlighter(); } private String DEMO_TEXT; @NotNull @Override public String getDemoText() { if (DEMO_TEXT == null) { try { URL resource = getClass().getClassLoader().getResource("colorscheme/highlighterDemoText.s"); DEMO_TEXT = resource != null ? ResourceUtil.loadText(resource) : ""; } catch (IOException e) { DEMO_TEXT = ""; } } return DEMO_TEXT; } @Nullable @Override public Map getAdditionalHighlightingTagToDescriptorMap() { return null; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "x86 Assembler"; } } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelHighlightingLexer.flex ================================================ package com.plan9.intel.lang.core.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.tree.IElementType; import com.intellij.psi.TokenType; import static com.plan9.intel.ide.highlighting.AsmIntelLexerTokens.*; %% %public %class _AsmIntelHighlightingLexer %implements FlexLexer %unicode %function advance %type IElementType %{ public _AsmIntelHighlightingLexer() { this((java.io.Reader)null); } %} WSNL = [ \r\n\t]+ WS = [ \t\f] LINE_COMMENT = "//" [^\r\n]* STR = "\"" LETTER = [:letter:] | "_" | \u00B7 | \u2215 DIGIT = [:digit:] HEX_DIGIT = [0-9A-Fa-f] INT_DIGIT = [0-9] OPERATOR = [*/%&|+~\^-] NUM_INT = "0" | ([1-9] {INT_DIGIT}*) NUM_HEX = ("0x" | "0X") {HEX_DIGIT}+ IDENT = {LETTER} ( {LETTER} | {DIGIT} )* LABEL = {IDENT} ":" DIRECTIVE = "TEXT" | "GLOBL" | "DATA" | "PCDATA" | "FUNCDATA" PSEUDO_REG = "FP" | "PC" | "SB" | "SP" REG = "AL" | "CL" | "DL" | "BL" | "SPB" | "BPB" | "SIB" | "DIB" | "R8B" | "R9B" | "R10B" | "R11B" | "R12B" | "R13B" | "R14B" | "R15B" | "AX" | "CX" | "DX" | "BX" | "SP" | "BP" | "SI" | "DI" | "R8" | "R9" | "R10" | "R11" | "R12" | "R13" | "R14" | "R15" | "AH" | "CH" | "DH" | "BH" | "F0" | "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "M0" | "M1" | "M2" | "M3" | "M4" | "M5" | "M6" | "M7" | "X0" | "X1" | "X2" | "X3" | "X4" | "X5" | "X6" | "X7" | "X8" | "X9" | "X10" | "X11" | "X12" | "X13" | "X14" | "X15" | "CS" | "SS" | "DS" | "ES" | "FS" | "GS" | "GDTR" | "IDTR" | "LDTR" | "MSW" | "TASK" | "CR0" | "CR1" | "CR2" | "CR3" | "CR4" | "CR5" | "CR6" | "CR7" | "CR8" | "CR9" | "CR10" | "CR11" | "CR12" | "CR13" | "CR14" | "CR15" | "DR0" | "DR1" | "DR2" | "DR3" | "DR4" | "DR5" | "DR6" | "DR7" | "TR0" | "TR1" | "TR2" | "TR3" | "TR4" | "TR5" | "TR6" | "TR7" | "TLS" PSEUDO_INS = "CALL" | "END" | "JMP" | "NOP" | "RET" // all instructions, including alternates per https://github.com/golang/go/blob/8db371b3d58a1c139f0854738f9962de05ca5d7a/src/cmd/asm/internal/arch/arch.go#L114 INS = "AAA" | "AAD" | "AAM" | "AAS" | "ADCB" | "ADCL" | "ADCQ" | "ADCW" | "ADDB" | "ADDL" | "ADDPD" | "ADDPS" | "ADDQ" | "ADDSD" | "ADDSS" | "ADDW" | "ADJSP" | "AESDEC" | "AESDECLAST" | "AESENC" | "AESENCLAST" | "AESIMC" | "AESKEYGENASSIST" | "ANDB" | "ANDL" | "ANDNPD" | "ANDNPS" | "ANDPD" | "ANDPS" | "ANDQ" | "ANDW" | "ARPL" | "BOUNDL" | "BOUNDW" | "BSFL" | "BSFQ" | "BSFW" | "BSRL" | "BSRQ" | "BSRW" | "BSWAPL" | "BSWAPQ" | "BTCL" | "BTCQ" | "BTCW" | "BTL" | "BTQ" | "BTRL" | "BTRQ" | "BTRW" | "BTSL" | "BTSQ" | "BTSW" | "BTW" | "BYTE" | "CDQ" | "CLC" | "CLD" | "CLI" | "CLTS" | "CMC" | "CMOVLCC" | "CMOVLCS" | "CMOVLEQ" | "CMOVLGE" | "CMOVLGT" | "CMOVLHI" | "CMOVLLE" | "CMOVLLS" | "CMOVLLT" | "CMOVLMI" | "CMOVLNE" | "CMOVLOC" | "CMOVLOS" | "CMOVLPC" | "CMOVLPL" | "CMOVLPS" | "CMOVQCC" | "CMOVQCS" | "CMOVQEQ" | "CMOVQGE" | "CMOVQGT" | "CMOVQHI" | "CMOVQLE" | "CMOVQLS" | "CMOVQLT" | "CMOVQMI" | "CMOVQNE" | "CMOVQOC" | "CMOVQOS" | "CMOVQPC" | "CMOVQPL" | "CMOVQPS" | "CMOVWCC" | "CMOVWCS" | "CMOVWEQ" | "CMOVWGE" | "CMOVWGT" | "CMOVWHI" | "CMOVWLE" | "CMOVWLS" | "CMOVWLT" | "CMOVWMI" | "CMOVWNE" | "CMOVWOC" | "CMOVWOS" | "CMOVWPC" | "CMOVWPL" | "CMOVWPS" | "CMPB" | "CMPL" | "CMPPD" | "CMPPS" | "CMPQ" | "CMPSB" | "CMPSD" | "CMPSL" | "CMPSQ" | "CMPSS" | "CMPSW" | "CMPW" | "CMPXCHG8B" | "CMPXCHGB" | "CMPXCHGL" | "CMPXCHGQ" | "CMPXCHGW" | "COMISD" | "COMISS" | "CPUID" | "CQO" | "CRC32B" | "CRC32Q" | "CVTPD2PL" | "CVTPD2PS" | "CVTPL2PD" | "CVTPL2PS" | "CVTPS2PD" | "CVTPS2PL" | "CVTSD2SL" | "CVTSD2SQ" | "CVTSD2SS" | "CVTSL2SD" | "CVTSL2SS" | "CVTSQ2SD" | "CVTSQ2SS" | "CVTSS2SD" | "CVTSS2SL" | "CVTSS2SQ" | "CVTTPD2PL" | "CVTTPS2PL" | "CVTTSD2SL" | "CVTTSD2SQ" | "CVTTSS2SL" | "CVTTSS2SQ" | "CWD" | "DAA" | "DAS" | "DECB" | "DECL" | "DECQ" | "DECW" | "DIVB" | "DIVL" | "DIVPD" | "DIVPS" | "DIVQ" | "DIVSD" | "DIVSS" | "DIVW" | "EMMS" | "ENTER" | "F2XM1" | "FABS" | "FADDD" | "FADDDP" | "FADDF" | "FADDL" | "FADDW" | "FCHS" | "FCLEX" | "FCMOVCC" | "FCMOVCS" | "FCMOVEQ" | "FCMOVHI" | "FCMOVLS" | "FCMOVNE" | "FCMOVNU" | "FCMOVUN" | "FCOMB" | "FCOMBP" | "FCOMD" | "FCOMDP" | "FCOMDPP" | "FCOMF" | "FCOMFP" | "FCOMI" | "FCOMIP" | "FCOML" | "FCOMLP" | "FCOMW" | "FCOMWP" | "FCOS" | "FDECSTP" | "FDIVD" | "FDIVDP" | "FDIVF" | "FDIVL" | "FDIVRD" | "FDIVRDP" | "FDIVRF" | "FDIVRL" | "FDIVRW" | "FDIVW" | "FFREE" | "FINCSTP" | "FINIT" | "FLD1" | "FLDCW" | "FLDENV" | "FLDL2E" | "FLDL2T" | "FLDLG2" | "FLDLN2" | "FLDPI" | "FLDZ" | "FMOVB" | "FMOVBP" | "FMOVD" | "FMOVDP" | "FMOVF" | "FMOVFP" | "FMOVL" | "FMOVLP" | "FMOVV" | "FMOVVP" | "FMOVW" | "FMOVWP" | "FMOVX" | "FMOVXP" | "FMULD" | "FMULDP" | "FMULF" | "FMULL" | "FMULW" | "FNOP" | "FPATAN" | "FPREM" | "FPREM1" | "FPTAN" | "FRNDINT" | "FRSTOR" | "FSAVE" | "FSCALE" | "FSIN" | "FSINCOS" | "FSQRT" | "FSTCW" | "FSTENV" | "FSTSW" | "FSUBD" | "FSUBDP" | "FSUBF" | "FSUBL" | "FSUBRD" | "FSUBRDP" | "FSUBRF" | "FSUBRL" | "FSUBRW" | "FSUBW" | "FTST" | "FUCOM" | "FUCOMI" | "FUCOMIP" | "FUCOMP" | "FUCOMPP" | "FXAM" | "FXCHD" | "FXRSTOR" | "FXRSTOR64" | "FXSAVE" | "FXSAVE64" | "FXTRACT" | "FYL2X" | "FYL2XP1" | "HLT" | "IDIVB" | "IDIVL" | "IDIVQ" | "IDIVW" | "IMUL3Q" | "IMULB" | "IMULL" | "IMULQ" | "IMULW" | "INB" | "INCB" | "INCL" | "INCQ" | "INCW" | "INL" | "INSB" | "INSL" | "INSW" | "INT" | "INTO" | "INVD" | "INVLPG" | "INW" | "IRETL" | "IRETQ" | "IRETW" | "JA" | "JAE" | "JB" | "JBE" | "JC" | "JCC" | "JCS" | "JCXZL" | "JCXZQ" | "JCXZW" | "JE" | "JEQ" | "JG" | "JGE" | "JGT" | "JHI" | "JHS" | "JL" | "JLE" | "JLO" | "JLS" | "JLT" | "JMI" | "JNA" | "JNAE" | "JNB" | "JNBE" | "JNC" | "JNE" | "JNG" | "JNGE" | "JNL" | "JNLE" | "JNO" | "JNP" | "JNS" | "JNZ" | "JO" | "JOC" | "JOS" | "JP" | "JPC" | "JPE" | "JPL" | "JPO" | "JPS" | "JS" | "JZ" | "LAHF" | "LARL" | "LARW" | "LAST" | "LDMXCSR" | "LEAL" | "LEAQ" | "LEAVEL" | "LEAVEQ" | "LEAVEW" | "LEAW" | "LFENCE" | "LOCK" | "LODSB" | "LODSL" | "LODSQ" | "LODSW" | "LONG" | "LOOP" | "LOOPEQ" | "LOOPNE" | "LSLL" | "LSLW" | "MASKMOVDQU" | "MASKMOVOU" | "MASKMOVQ" | "MAXPD" | "MAXPS" | "MAXSD" | "MAXSS" | "MFENCE" | "MINPD" | "MINPS" | "MINSD" | "MINSS" | "MODE" | "MOVAPD" | "MOVAPS" | "MOVB" | "MOVBLSX" | "MOVBLZX" | "MOVBQSX" | "MOVBQZX" | "MOVBWSX" | "MOVBWZX" | "MOVD" | "MOVDQ2Q" | "MOVHDA" | "MOVHDU" | "MOVHLPS" | "MOVHPD" | "MOVHPS" | "MOVL" | "MOVLHPS" | "MOVLPD" | "MOVLPS" | "MOVLQSX" | "MOVLQZX" | "MOVMSKPD" | "MOVMSKPS" | "MOVNTDQ" | "MOVNTHD" | "MOVNTIL" | "MOVNTIQ" | "MOVNTO" | "MOVNTPD" | "MOVNTPS" | "MOVNTQ" | "MOVO" | "MOVOA" | "MOVOU" | "MOVQ" | "MOVQL" | "MOVQOZX" | "MOVSB" | "MOVSD" | "MOVSL" | "MOVSQ" | "MOVSS" | "MOVSW" | "MOVUPD" | "MOVUPS" | "MOVW" | "MOVWLSX" | "MOVWLZX" | "MOVWQSX" | "MOVWQZX" | "MULB" | "MULL" | "MULPD" | "MULPS" | "MULQ" | "MULSD" | "MULSS" | "MULW" | "NEGB" | "NEGL" | "NEGQ" | "NEGW" | "NOTB" | "NOTL" | "NOTQ" | "NOTW" | "ORB" | "ORL" | "ORPD" | "ORPS" | "ORQ" | "ORW" | "OUTB" | "OUTL" | "OUTSB" | "OUTSL" | "OUTSW" | "OUTW" | "PACKSSLW" | "PACKSSWB" | "PACKUSWB" | "PADDB" | "PADDL" | "PADDQ" | "PADDSB" | "PADDSW" | "PADDUSB" | "PADDUSW" | "PADDW" | "PAND" | "PANDB" | "PANDL" | "PANDN" | "PANDSB" | "PANDSW" | "PANDUSB" | "PANDUSW" | "PANDW" | "PAUSE" | "PAVGB" | "PAVGW" | "PCLMULQDQ" | "PCMPEQB" | "PCMPEQL" | "PCMPEQW" | "PCMPGTB" | "PCMPGTL" | "PCMPGTW" | "PEXTRW" | "PF2ID" | "PF2IL" | "PF2IW" | "PFACC" | "PFADD" | "PFCMPEQ" | "PFCMPGE" | "PFCMPGT" | "PFMAX" | "PFMIN" | "PFMUL" | "PFNACC" | "PFPNACC" | "PFRCP" | "PFRCPI2T" | "PFRCPIT1" | "PFRSQIT1" | "PFRSQRT" | "PFSUB" | "PFSUBR" | "PI2FD" | "PI2FL" | "PI2FW" | "PINSRD" | "PINSRQ" | "PINSRW" | "PMADDWL" | "PMAXSW" | "PMAXUB" | "PMINSW" | "PMINUB" | "PMOVMSKB" | "PMULHRW" | "PMULHUW" | "PMULHW" | "PMULLW" | "PMULULQ" | "POPAL" | "POPAW" | "POPFL" | "POPFQ" | "POPFW" | "POPL" | "POPQ" | "POPW" | "POR" | "PREFETCHNTA" | "PREFETCHT0" | "PREFETCHT1" | "PREFETCHT2" | "PSADBW" | "PSHUFB" | "PSHUFD" | "PSHUFHW" | "PSHUFL" | "PSHUFLW" | "PSHUFW" | "PSLLDQ" | "PSLLL" | "PSLLO" | "PSLLQ" | "PSLLW" | "PSRAL" | "PSRAW" | "PSRLDQ" | "PSRLL" | "PSRLO" | "PSRLQ" | "PSRLW" | "PSUBB" | "PSUBL" | "PSUBQ" | "PSUBSB" | "PSUBSW" | "PSUBUSB" | "PSUBUSW" | "PSUBW" | "PSWAPL" | "PUNPCKHBW" | "PUNPCKHLQ" | "PUNPCKHQDQ" | "PUNPCKHWL" | "PUNPCKLBW" | "PUNPCKLLQ" | "PUNPCKLQDQ" | "PUNPCKLWL" | "PUSHAL" | "PUSHAW" | "PUSHFL" | "PUSHFQ" | "PUSHFW" | "PUSHL" | "PUSHQ" | "PUSHW" | "PXOR" | "QUAD" | "RCLB" | "RCLL" | "RCLQ" | "RCLW" | "RCPPS" | "RCPSS" | "RCRB" | "RCRL" | "RCRQ" | "RCRW" | "RDMSR" | "RDPMC" | "RDTSC" | "REP" | "REPN" | "RETFL" | "RETFQ" | "RETFW" | "ROLB" | "ROLL" | "ROLQ" | "ROLW" | "RORB" | "RORL" | "RORQ" | "RORW" | "ROUNDPD" | "ROUNDPS" | "ROUNDSD" | "ROUNDSS" | "RSM" | "RSQRTPS" | "RSQRTSS" | "SAHF" | "SALB" | "SALL" | "SALQ" | "SALW" | "SARB" | "SARL" | "SARQ" | "SARW" | "SBBB" | "SBBL" | "SBBQ" | "SBBW" | "SCASB" | "SCASL" | "SCASQ" | "SCASW" | "SETCC" | "SETCS" | "SETEQ" | "SETGE" | "SETGT" | "SETHI" | "SETLE" | "SETLS" | "SETLT" | "SETMI" | "SETNE" | "SETOC" | "SETOS" | "SETPC" | "SETPL" | "SETPS" | "SFENCE" | "SHLB" | "SHLL" | "SHLQ" | "SHLW" | "SHRB" | "SHRL" | "SHRQ" | "SHRW" | "SHUFPD" | "SHUFPS" | "SQRTPD" | "SQRTPS" | "SQRTSD" | "SQRTSS" | "STC" | "STD" | "STI" | "STMXCSR" | "STOSB" | "STOSL" | "STOSQ" | "STOSW" | "SUBB" | "SUBL" | "SUBPD" | "SUBPS" | "SUBQ" | "SUBSD" | "SUBSS" | "SUBW" | "SWAPGS" | "SYSCALL" | "SYSRET" | "TESTB" | "TESTL" | "TESTQ" | "TESTW" | "UCOMISD" | "UCOMISS" | "UNPCKHPD" | "UNPCKHPS" | "UNPCKLPD" | "UNPCKLPS" | "VERR" | "VERW" | "VPAND" | "VPBROADCASTB" | "VPCMPEQB" | "VPMOVMSKB" | "VPTEST" | "VPXOR" | "VZEROUPPER" | "WAIT" | "WBINVD" | "WORD" | "WRMSR" | "XABORT" | "XACQUIRE" | "XADDB" | "XADDL" | "XADDQ" | "XADDW" | "XBEGIN" | "XCHGB" | "XCHGL" | "XCHGQ" | "XCHGW" | "XEND" | "XLAT" | "XORB" | "XORL" | "XORPD" | "XORPS" | "XORQ" | "XORW" | "XRELEASE" | "XTEST" PREPROCESSOR = "#include" | "#define" | "#ifdef" | "#else" | "#endif" | "#undef" FLAG = "NOPROF" | "DUPOK" | "NOSPLIT" | "RODATA" | "NOPTR" | "WRAPPER" | "NEEDCTXT" | "TLSBSS" | "NOFRAME" %% {PREPROCESSOR} { return PREPROCESSOR; } {DIRECTIVE} { return DIRECTIVE; } {FLAG} { return FLAG; } {PSEUDO_REG} { return PSEUDO_REG; } {REG} { return REGISTER; } {PSEUDO_INS} { return PSEUDO_INS; } {INS} { return INSTRUCTION; } {LINE_COMMENT} { return LINE_COMMENT; } {WS} { return TokenType.WHITE_SPACE; } {WSNL} { return TokenType.WHITE_SPACE; } {LABEL} { return LABEL; } "(" { return PAREN; } ")" { return PAREN; } "," { return COMMA; } {OPERATOR} { return OPERATOR; } "<<" | ">>" { return OPERATOR; } {NUM_HEX} { return HEX; } {NUM_INT} { return INT; } {IDENT} { return IDENTIFIER; } {STR} [^\"]* {STR} { return STRING; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Catch All /////////////////////////////////////////////////////////////////////////////////////////////////// [^] { return com.intellij.psi.TokenType.BAD_CHARACTER; } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelHighlightingLexer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.ide.highlighting; import com.intellij.lexer.FlexAdapter; import com.plan9.intel.lang.core.lexer._AsmIntelHighlightingLexer; public class AsmIntelHighlightingLexer extends FlexAdapter { public AsmIntelHighlightingLexer() { super(new _AsmIntelHighlightingLexer()); } } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelLexerTokens.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.ide.highlighting; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.plan9.intel.lang.core.lexer.AsmIntelTokenType; public class AsmIntelLexerTokens { public static final IElementType LINE_COMMENT = new AsmIntelTokenType("LINE_COMMENT"); public static final IElementType OPERATOR = new AsmIntelTokenType("operator"); public static final IElementType PAREN = new AsmIntelTokenType("PAREN"); public static final IElementType COLON = new AsmIntelTokenType(":"); public static final IElementType COMMA = new AsmIntelTokenType(","); public static final IElementType FLAG = new AsmIntelTokenType("FLAG"); public static final IElementType HEX = new AsmIntelTokenType("hex"); public static final IElementType INT = new AsmIntelTokenType("int"); public static final IElementType IDENTIFIER = new AsmIntelTokenType("identifier"); public static final IElementType PREPROCESSOR = new AsmIntelTokenType("PREPROCESSOR"); public static final IElementType PSEUDO_INS = new AsmIntelTokenType("PSEUDO_INS"); public static final IElementType INSTRUCTION = new AsmIntelTokenType("INSTRUCTION"); public static final IElementType LABEL = new AsmIntelTokenType("LABEL"); public static final IElementType PSEUDO_REG = new AsmIntelTokenType("PSEUDO_REG"); public static final IElementType REGISTER = new AsmIntelTokenType("REGISTER"); public static final IElementType STRING = new AsmIntelTokenType("STRING"); public static final IElementType DIRECTIVE = new AsmIntelTokenType("DIRECTIVE"); public static final TokenSet KEYWORDS = TokenSet.create(DIRECTIVE); public static final TokenSet NUMBERS = TokenSet.create(HEX, INT); public static final TokenSet REGISTERS = TokenSet.create(PSEUDO_REG, REGISTER); private AsmIntelLexerTokens() {} } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelSyntaxHighlighter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.ide.highlighting; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Map; import static com.plan9.intel.ide.highlighting.AsmIntelSyntaxHighlightingColors.*; public class AsmIntelSyntaxHighlighter extends SyntaxHighlighterBase { private static final Map ATTRIBUTES = ContainerUtil.newHashMap(); static { fillMap(ATTRIBUTES, LINE_COMMENT, AsmIntelLexerTokens.LINE_COMMENT); fillMap(ATTRIBUTES, INSTRUCTION, AsmIntelLexerTokens.INSTRUCTION); fillMap(ATTRIBUTES, PSEUDO_INSTRUCTION, AsmIntelLexerTokens.PSEUDO_INS); fillMap(ATTRIBUTES, STRING, AsmIntelLexerTokens.STRING); fillMap(ATTRIBUTES, LABEL, AsmIntelLexerTokens.LABEL); fillMap(ATTRIBUTES, FLAG, AsmIntelLexerTokens.FLAG); fillMap(ATTRIBUTES, OPERATOR, AsmIntelLexerTokens.OPERATOR); fillMap(ATTRIBUTES, PARENTHESIS, AsmIntelLexerTokens.PAREN); fillMap(ATTRIBUTES, IDENTIFIER, AsmIntelLexerTokens.IDENTIFIER); fillMap(ATTRIBUTES, PREPROCESSOR, AsmIntelLexerTokens.PREPROCESSOR); fillMap(ATTRIBUTES, AsmIntelLexerTokens.KEYWORDS, KEYWORD); fillMap(ATTRIBUTES, AsmIntelLexerTokens.NUMBERS, NUMBER); fillMap(ATTRIBUTES, AsmIntelLexerTokens.REGISTERS, REGISTER); } @NotNull @Override public Lexer getHighlightingLexer() { return new AsmIntelHighlightingLexer(); } @Override @NotNull public TextAttributesKey[] getTokenHighlights(IElementType tokenType) { return pack(ATTRIBUTES.get(tokenType)); } } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelSyntaxHighlighterFactory.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.ide.highlighting; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class AsmIntelSyntaxHighlighterFactory extends SyntaxHighlighterFactory { @NotNull @Override public SyntaxHighlighter getSyntaxHighlighter(@Nullable Project project, @Nullable VirtualFile file) { return new AsmIntelSyntaxHighlighter(); } } ================================================ FILE: plan9/src/com/plan9/intel/ide/highlighting/AsmIntelSyntaxHighlightingColors.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.ide.highlighting; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey; public class AsmIntelSyntaxHighlightingColors { public static final TextAttributesKey LINE_COMMENT = createTextAttributesKey("com.plan9.LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey INSTRUCTION = createTextAttributesKey("com.plan9.INSTRUCTION", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL); public static final TextAttributesKey PSEUDO_INSTRUCTION = createTextAttributesKey("com.plan9.PSEUDO_INSTRUCTION", INSTRUCTION); public static final TextAttributesKey KEYWORD = createTextAttributesKey("com.plan9.KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey STRING = createTextAttributesKey("com.plan9.STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = createTextAttributesKey("com.plan9.NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey LABEL = createTextAttributesKey("com.plan9.LABEL", DefaultLanguageHighlighterColors.LABEL); public static final TextAttributesKey FLAG = createTextAttributesKey("com.plan9.FLAG", DefaultLanguageHighlighterColors.GLOBAL_VARIABLE); public static final TextAttributesKey REGISTER = createTextAttributesKey("com.plan9.REGISTER", DefaultLanguageHighlighterColors.PARAMETER); public static final TextAttributesKey PARENTHESIS = createTextAttributesKey("com.plan9.PARENTHESIS", DefaultLanguageHighlighterColors.PARENTHESES); public static final TextAttributesKey OPERATOR = createTextAttributesKey("com.plan9.OPERATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN); public static final TextAttributesKey DIRECTIVE = createTextAttributesKey("com.plan9.DIRECTIVE", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey IDENTIFIER = createTextAttributesKey("com.plan9.IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey PREPROCESSOR = createTextAttributesKey("com.plan9.PREPROCESSOR", DefaultLanguageHighlighterColors.KEYWORD); } ================================================ FILE: plan9/src/com/plan9/intel/lang/AsmIntelLanguage.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.lang; import com.intellij.lang.Language; public class AsmIntelLanguage extends Language { public static final AsmIntelLanguage INSTANCE = new AsmIntelLanguage(); private AsmIntelLanguage() { super("plan9_x86"); } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/AsmIntelParserDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.lang.core; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import com.plan9.intel.lang.AsmIntelLanguage; import com.plan9.intel.lang.core.lexer.AsmIntelLexer; import com.plan9.intel.lang.core.lexer.AsmIntelTokenType; import com.plan9.intel.lang.core.parser.AsmIntelParser; import com.plan9.intel.lang.core.psi.AsmIntelFile; import org.jetbrains.annotations.NotNull; import static com.plan9.intel.lang.core.psi.AsmIntelTypes.*; public class AsmIntelParserDefinition implements ParserDefinition { public static final IElementType LINE_COMMENT = new AsmIntelTokenType("LINE_COMMENT"); private static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE); private static final TokenSet COMMENTS = TokenSet.create(LINE_COMMENT); public static final TokenSet KEYWORDS = TokenSet.create(TEXT); public static final TokenSet NUMBERS = TokenSet.create(HEX, INT); public static final TokenSet REGISTERS = TokenSet.create(PSEUDO_REG); public static final IFileElementType FILE = new IFileElementType(Language.findInstance(AsmIntelLanguage.class)); @NotNull @Override public Lexer createLexer(Project project) { return new AsmIntelLexer(); } @Override @NotNull public TokenSet getWhitespaceTokens() { return WHITE_SPACES; } @Override @NotNull public TokenSet getCommentTokens() { return COMMENTS; } @Override @NotNull public TokenSet getStringLiteralElements() { return TokenSet.EMPTY; } @Override @NotNull public PsiParser createParser(Project project) { return new AsmIntelParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } @Override public PsiFile createFile(FileViewProvider viewProvider) { return new AsmIntelFile(viewProvider); } @Override public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { return SpaceRequirements.MAY; } @Override @NotNull public PsiElement createElement(ASTNode node) { return Factory.createElement(node); } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/grammar/x86.bnf ================================================ { parserClass="com.plan9.intel.lang.core.parser.AsmIntelParser" extends='com.plan9.intel.lang.core.psi.impl.AsmIntelElementImpl' extends="com.intellij.extapi.psi.ASTWrapperPsiElement" psiClassPrefix="AsmIntel" psiImplClassSuffix="Impl" psiPackage="com.plan9.intel.lang.core.psi" psiImplPackage="com.plan9.intel.lang.core.psi.impl" elementTypeHolderClass="com.plan9.intel.lang.core.psi.AsmIntelTypes" elementTypeClass="com.plan9.intel.lang.core.psi.AsmIntelElementType" tokenTypeClass="com.plan9.intel.lang.core.lexer.AsmIntelTokenType" tokens = [ COLON = ':' LPAREN = '(' RPAREN = ')' COMMA = ',' COMMA = ',' BIT_OR = '|' ] } File ::= Statement* Statement ::= PreprocessorDirective | Function PreprocessorDirective ::= import STRING Function ::= FunctionHeader FunctionBody FunctionHeader ::= TEXT identifier '(' PSEUDO_REG ')' ',' FunctionFlags [',' FrameSize] FunctionFlags ::= FLAG | '(' FLAG ( '|' FLAG )* ')' FrameSize ::= '$' Literal ['-' Literal] FunctionBody ::= ( InstructionStmt | LABEL )* InstructionStmt ::= INSTRUCTION Operands Operands ::= Literal ::= int | hex ================================================ FILE: plan9/src/com/plan9/intel/lang/core/lexer/AsmIntelLexer.flex ================================================ package com.plan9.intel.lang.core.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.tree.IElementType; import com.plan9.intel.lang.core.psi.AsmIntelTypes; import com.intellij.psi.TokenType; import static com.plan9.intel.lang.core.AsmIntelParserDefinition.*; %% %public %class _AsmIntelLexer %implements FlexLexer, AsmIntelTypes %unicode %function advance %type IElementType %{ public _AsmIntelLexer() { this((java.io.Reader)null); } %} WSNL = [ \r\n\t]+ WS = [ \t\f] LINE_COMMENT = "//" [^\r\n]* STR = "\"" LETTER = [:letter:] | "_" DIGIT = [:digit:] HEX_DIGIT = [0-9A-Fa-f] INT_DIGIT = [0-9] NUM_INT = "0" | ([1-9] {INT_DIGIT}*) NUM_HEX = ("0x" | "0X") {HEX_DIGIT}+ IDENT = {LETTER} ( {LETTER} | {DIGIT} )* LABEL = {IDENT} ":" PSEUDO_REG = "FP" | "PC" | "SB" | "SP" INS = "AAA" | "AAD" | "AAM" | "AAS" | "ADCB" | "ADCL" | "ADCW" | "ADDB" | "ADDL" | "ADDW" | "ADJSP" | "ANDB" | "ANDL" | "ANDW" | "ARPL" | "BOUNDL" | "BOUNDW" | "BSFL" | "BSFW" | "BSRL" | "BSRW" | "BTL" | "BTW" | "BTCL" | "BTCW" | "BTRL" | "BTRW" | "BTSL" | "BTSW" | "BYTE" | "CLC" | "CLD" | "CLI" | "CLTS" | "CMC" | "CMPB" | "CMPL" | "CMPW" | "CMPSB" | "CMPSL" | "CMPSW" | "DAA" | "DAS" | "DECB" | "DECL" | "DECQ" | "DECW" | "DIVB" | "DIVL" | "DIVW" | "ENTER" | "HLT" | "IDIVB" | "IDIVL" | "IDIVW" | "IMULB" | "IMULL" | "IMULW" | "INB" | "INL" | "INW" | "INCB" | "INCL" | "INCQ" | "INCW" | "INSB" | "INSL" | "INSW" | "INT" | "INTO" | "IRETL" | "IRETW" | "JCC" | "JCS" | "JCXZL" | "JEQ" | "JGE" | "JGT" | "JHI" | "JLE" | "JLS" | "JLT" | "JMI" | "JNE" | "JOC" | "JOS" | "JPC" | "JPL" | "JPS" | "LAHF" | "LARL" | "LARW" | "LEAL" | "LEAW" | "LEAVEL" | "LEAVEW" | "LOCK" | "LODSB" | "LODSL" | "LODSW" | "LONG" | "LOOP" | "LOOPEQ" | "LOOPNE" | "LSLL" | "LSLW" | "MOVB" | "MOVL" | "MOVW" | "MOVBLSX" | "MOVBLZX" | "MOVBQSX" | "MOVBQZX" | "MOVBWSX" | "MOVBWZX" | "MOVWLSX" | "MOVWLZX" | "MOVWQSX" | "MOVWQZX" | "MOVSB" | "MOVSL" | "MOVSW" | "MULB" | "MULL" | "MULW" | "NEGB" | "NEGL" | "NEGW" | "NOTB" | "NOTL" | "NOTW" | "ORB" | "ORL" | "ORW" | "OUTB" | "OUTL" | "OUTW" | "OUTSB" | "OUTSL" | "OUTSW" | "PAUSE" | "POPAL" | "POPAW" | "POPFL" | "POPFW" | "POPL" | "POPW" | "PUSHAL" | "PUSHAW" | "PUSHFL" | "PUSHFW" | "PUSHL" | "PUSHW" | "RCLB" | "RCLL" | "RCLW" | "RCRB" | "RCRL" | "RCRW" | "REP" | "REPN" | "ROLB" | "ROLL" | "ROLW" | "RORB" | "RORL" | "RORW" | "SAHF" | "SALB" | "SALL" | "SALW" | "SARB" | "SARL" | "SARW" | "SBBB" | "SBBL" | "SBBW" | "SCASB" | "SCASL" | "SCASW" | "SETCC" | "SETCS" | "SETEQ" | "SETGE" | "SETGT" | "SETHI" | "SETLE" | "SETLS" | "SETLT" | "SETMI" | "SETNE" | "SETOC" | "SETOS" | "SETPC" | "SETPL" | "SETPS" | "CDQ" | "CWD" | "SHLB" | "SHLL" | "SHLW" | "SHRB" | "SHRL" | "SHRW" | "STC" | "STD" | "STI" | "STOSB" | "STOSL" | "STOSW" | "SUBB" | "SUBL" | "SUBW" | "SYSCALL" | "TESTB" | "TESTL" | "TESTW" | "VERR" | "VERW" | "WAIT" | "WORD" | "XCHGB" | "XCHGL" | "XCHGW" | "XLAT" | "XORB" | "XORL" | "XORW" | "FMOVB" | "FMOVBP" | "FMOVD" | "FMOVDP" | "FMOVF" | "FMOVFP" | "FMOVL" | "FMOVLP" | "FMOVV" | "FMOVVP" | "FMOVW" | "FMOVWP" | "FMOVX" | "FMOVXP" | "FCOMB" | "FCOMBP" | "FCOMD" | "FCOMDP" | "FCOMDPP" | "FCOMF" | "FCOMFP" | "FCOML" | "FCOMLP" | "FCOMW" | "FCOMWP" | "FUCOM" | "FUCOMP" | "FUCOMPP" | "FADDDP" | "FADDW" | "FADDL" | "FADDF" | "FADDD" | "FMULDP" | "FMULW" | "FMULL" | "FMULF" | "FMULD" | "FSUBDP" | "FSUBW" | "FSUBL" | "FSUBF" | "FSUBD" | "FSUBRDP" | "FSUBRW" | "FSUBRL" | "FSUBRF" | "FSUBRD" | "FDIVDP" | "FDIVW" | "FDIVL" | "FDIVF" | "FDIVD" | "FDIVRDP" | "FDIVRW" | "FDIVRL" | "FDIVRF" | "FDIVRD" | "FXCHD" | "FFREE" | "FLDCW" | "FLDENV" | "FRSTOR" | "FSAVE" | "FSTCW" | "FSTENV" | "FSTSW" | "F2XM1" | "FABS" | "FCHS" | "FCLEX" | "FCOS" | "FDECSTP" | "FINCSTP" | "FINIT" | "FLD1" | "FLDL2E" | "FLDL2T" | "FLDLG2" | "FLDLN2" | "FLDPI" | "FLDZ" | "FNOP" | "FPATAN" | "FPREM" | "FPREM1" | "FPTAN" | "FRNDINT" | "FSCALE" | "FSIN" | "FSINCOS" | "FSQRT" | "FTST" | "FXAM" | "FXTRACT" | "FYL2X" | "FYL2XP1" | "CMPXCHGB" | "CMPXCHGL" | "CMPXCHGW" | "CMPXCHG8B" | "CPUID" | "INVD" | "INVLPG" | "LFENCE" | "MFENCE" | "MOVNTIL" | "RDMSR" | "RDPMC" | "RDTSC" | "RSM" | "SFENCE" | "SYSRET" | "WBINVD" | "WRMSR" | "XADDB" | "XADDL" | "XADDW" | "CMOVLCC" | "CMOVLCS" | "CMOVLEQ" | "CMOVLGE" | "CMOVLGT" | "CMOVLHI" | "CMOVLLE" | "CMOVLLS" | "CMOVLLT" | "CMOVLMI" | "CMOVLNE" | "CMOVLOC" | "CMOVLOS" | "CMOVLPC" | "CMOVLPL" | "CMOVLPS" | "CMOVQCC" | "CMOVQCS" | "CMOVQEQ" | "CMOVQGE" | "CMOVQGT" | "CMOVQHI" | "CMOVQLE" | "CMOVQLS" | "CMOVQLT" | "CMOVQMI" | "CMOVQNE" | "CMOVQOC" | "CMOVQOS" | "CMOVQPC" | "CMOVQPL" | "CMOVQPS" | "CMOVWCC" | "CMOVWCS" | "CMOVWEQ" | "CMOVWGE" | "CMOVWGT" | "CMOVWHI" | "CMOVWLE" | "CMOVWLS" | "CMOVWLT" | "CMOVWMI" | "CMOVWNE" | "CMOVWOC" | "CMOVWOS" | "CMOVWPC" | "CMOVWPL" | "CMOVWPS" | "ADCQ" | "ADDQ" | "ANDQ" | "BSFQ" | "BSRQ" | "BTCQ" | "BTQ" | "BTRQ" | "BTSQ" | "CMPQ" | "CMPSQ" | "CMPXCHGQ" | "CQO" | "DIVQ" | "IDIVQ" | "IMULQ" | "IRETQ" | "JCXZQ" | "LEAQ" | "LEAVEQ" | "LODSQ" | "MOVQ" | "MOVLQSX" | "MOVLQZX" | "MOVNTIQ" | "MOVSQ" | "MULQ" | "NEGQ" | "NOTQ" | "ORQ" | "POPFQ" | "POPQ" | "PUSHFQ" | "PUSHQ" | "RCLQ" | "RCRQ" | "ROLQ" | "RORQ" | "QUAD" | "SALQ" | "SARQ" | "SBBQ" | "SCASQ" | "SHLQ" | "SHRQ" | "STOSQ" | "SUBQ" | "TESTQ" | "XADDQ" | "XCHGQ" | "XORQ" | "ADDPD" | "ADDPS" | "ADDSD" | "ADDSS" | "ANDNPD" | "ANDNPS" | "ANDPD" | "ANDPS" | "CMPPD" | "CMPPS" | "CMPSD" | "CMPSS" | "COMISD" | "COMISS" | "CVTPD2PL" | "CVTPD2PS" | "CVTPL2PD" | "CVTPL2PS" | "CVTPS2PD" | "CVTPS2PL" | "CVTSD2SL" | "CVTSD2SQ" | "CVTSD2SS" | "CVTSL2SD" | "CVTSL2SS" | "CVTSQ2SD" | "CVTSQ2SS" | "CVTSS2SD" | "CVTSS2SL" | "CVTSS2SQ" | "CVTTPD2PL" | "CVTTPS2PL" | "CVTTSD2SL" | "CVTTSD2SQ" | "CVTTSS2SL" | "CVTTSS2SQ" | "DIVPD" | "DIVPS" | "DIVSD" | "DIVSS" | "EMMS" | "FXRSTOR" | "FXRSTOR64" | "FXSAVE" | "FXSAVE64" | "LDMXCSR" | "MASKMOVOU" | "MASKMOVQ" | "MAXPD" | "MAXPS" | "MAXSD" | "MAXSS" | "MINPD" | "MINPS" | "MINSD" | "MINSS" | "MOVAPD" | "MOVAPS" | "MOVOU" | "MOVHLPS" | "MOVHPD" | "MOVHPS" | "MOVLHPS" | "MOVLPD" | "MOVLPS" | "MOVMSKPD" | "MOVMSKPS" | "MOVNTO" | "MOVNTPD" | "MOVNTPS" | "MOVNTQ" | "MOVO" | "MOVQOZX" | "MOVSD" | "MOVSS" | "MOVUPD" | "MOVUPS" | "MULPD" | "MULPS" | "MULSD" | "MULSS" | "ORPD" | "ORPS" | "PACKSSLW" | "PACKSSWB" | "PACKUSWB" | "PADDB" | "PADDL" | "PADDQ" | "PADDSB" | "PADDSW" | "PADDUSB" | "PADDUSW" | "PADDW" | "PANDB" | "PANDL" | "PANDSB" | "PANDSW" | "PANDUSB" | "PANDUSW" | "PANDW" | "PAND" | "PANDN" | "PAVGB" | "PAVGW" | "PCMPEQB" | "PCMPEQL" | "PCMPEQW" | "PCMPGTB" | "PCMPGTL" | "PCMPGTW" | "PEXTRW" | "PFACC" | "PFADD" | "PFCMPEQ" | "PFCMPGE" | "PFCMPGT" | "PFMAX" | "PFMIN" | "PFMUL" | "PFNACC" | "PFPNACC" | "PFRCP" | "PFRCPIT1" | "PFRCPI2T" | "PFRSQIT1" | "PFRSQRT" | "PFSUB" | "PFSUBR" | "PINSRW" | "PINSRD" | "PINSRQ" | "PMADDWL" | "PMAXSW" | "PMAXUB" | "PMINSW" | "PMINUB" | "PMOVMSKB" | "PMULHRW" | "PMULHUW" | "PMULHW" | "PMULLW" | "PMULULQ" | "POR" | "PSADBW" | "PSHUFHW" | "PSHUFL" | "PSHUFLW" | "PSHUFW" | "PSHUFB" | "PSLLO" | "PSLLL" | "PSLLQ" | "PSLLW" | "PSRAL" | "PSRAW" | "PSRLO" | "PSRLL" | "PSRLQ" | "PSRLW" | "PSUBB" | "PSUBL" | "PSUBQ" | "PSUBSB" | "PSUBSW" | "PSUBUSB" | "PSUBUSW" | "PSUBW" | "PSWAPL" | "PUNPCKHBW" | "PUNPCKHLQ" | "PUNPCKHQDQ" | "PUNPCKHWL" | "PUNPCKLBW" | "PUNPCKLLQ" | "PUNPCKLQDQ" | "PUNPCKLWL" | "PXOR" | "RCPPS" | "RCPSS" | "RSQRTPS" | "RSQRTSS" | "SHUFPD" | "SHUFPS" | "SQRTPD" | "SQRTPS" | "SQRTSD" | "SQRTSS" | "STMXCSR" | "SUBPD" | "SUBPS" | "SUBSD" | "SUBSS" | "UCOMISD" | "UCOMISS" | "UNPCKHPD" | "UNPCKHPS" | "UNPCKLPD" | "UNPCKLPS" | "XORPD" | "XORPS" | "PF2IW" | "PF2IL" | "PI2FW" | "PI2FL" | "RETFW" | "RETFL" | "RETFQ" | "SWAPGS" | "MODE" | "CRC32B" | "CRC32Q" | "IMUL3Q" | "PREFETCHT0" | "PREFETCHT1" | "PREFETCHT2" | "PREFETCHNTA" | "MOVQL" | "BSWAPL" | "BSWAPQ" | "AESENC" | "AESENCLAST" | "AESDEC" | "AESDECLAST" | "AESIMC" | "AESKEYGENASSIST" | "ROUNDPS" | "ROUNDSS" | "ROUNDPD" | "ROUNDSD" | "PSHUFD" | "PCLMULQDQ" | "VZEROUPPER" | "MOVHDU" | "MOVNTHD" | "MOVHDA" | "VPCMPEQB" | "VPXOR" | "VPMOVMSKB" | "VPAND" | "VPTEST" | "VPBROADCASTB" | "JCXZW" | "FCMOVCC" | "FCMOVCS" | "FCMOVEQ" | "FCMOVHI" | "FCMOVLS" | "FCMOVNE" | "FCMOVNU" | "FCMOVUN" | "FCOMI" | "FCOMIP" | "FUCOMI" | "FUCOMIP" | "XACQUIRE" | "XRELEASE" | "XBEGIN" | "XEND" | "XABORT" | "XTEST" | "LAST" FLAG = "NOPROF" | "DUPOK" | "NOSPLIT" | "RODATA" | "NOPTR" | "WRAPPER" | "NEEDCTXT" | "TLSBSS" | "NOFRAME" %% "#import" { return IMPORT; } "TEXT" { return TEXT; } {FLAG} { return FLAG; } {PSEUDO_REG} { return PSEUDO_REG; } {INS} { return INSTRUCTION; } {LINE_COMMENT} { return LINE_COMMENT; } {WS} { return TokenType.WHITE_SPACE; } {WSNL} { return TokenType.WHITE_SPACE; } {LABEL} { return LABEL; } ":" { return COLON; } "(" { return LPAREN; } ")" { return RPAREN; } "," { return COMMA; } "|" { return BIT_OR; } {NUM_HEX} { return HEX; } {NUM_INT} { return INT; } {IDENT} { return IDENTIFIER; } {STR} [^\"]* {STR} { return STRING; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Catch All /////////////////////////////////////////////////////////////////////////////////////////////////// [^] { return com.intellij.psi.TokenType.BAD_CHARACTER; } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/lexer/AsmIntelLexer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.lang.core.lexer; import com.intellij.lexer.FlexAdapter; public class AsmIntelLexer extends FlexAdapter { public AsmIntelLexer() { super(new _AsmIntelLexer()); } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/lexer/AsmIntelTokenType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.lang.core.lexer; import com.plan9.intel.lang.AsmIntelLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class AsmIntelTokenType extends IElementType { public AsmIntelTokenType(@NotNull @NonNls String debugName) { super(debugName, AsmIntelLanguage.INSTANCE); } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/psi/AsmIntelElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.lang.core.psi; import com.plan9.intel.lang.AsmIntelLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class AsmIntelElementType extends IElementType { public AsmIntelElementType(@NotNull @NonNls String debugName) { super(debugName, AsmIntelLanguage.INSTANCE); } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/psi/AsmIntelFile.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.lang.core.psi; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.plan9.intel.AsmIntelFileType; import com.plan9.intel.lang.AsmIntelLanguage; import org.jetbrains.annotations.NotNull; public class AsmIntelFile extends PsiFileBase { public AsmIntelFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, AsmIntelLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() { return AsmIntelFileType.INSTANCE; } @Override public String toString() { return "x86 File"; } } ================================================ FILE: plan9/src/com/plan9/intel/lang/core/psi/impl/AsmIntelElementImpl.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan, Stuart Carnie * * 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 com.plan9.intel.lang.core.psi.impl; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; public class AsmIntelElementImpl extends ASTWrapperPsiElement { public AsmIntelElementImpl(@NotNull ASTNode node) { super(node); } @Override public String toString() { return getNode().getElementType().toString(); } } ================================================ FILE: plan9/testData/intel/lexer/commentsAndWhitespace.s ================================================ // a comment line #import "a-file.h" // another comment line ================================================ FILE: plan9/testData/intel/lexer/commentsAndWhitespace.txt ================================================ LINE_COMMENT ('// a comment line') WHITE_SPACE ('\n\n') import ('#import') WHITE_SPACE (' ') STRING ('"a-file.h"') WHITE_SPACE ('\n\n') LINE_COMMENT ('// another comment line') ================================================ FILE: plan9/testData/intel/lexer/identifiers.s ================================================ loop: ================================================ FILE: plan9/testData/intel/lexer/identifiers.txt ================================================ LABEL ('loop:') ================================================ FILE: plan9/testData/intel/lexer/simpleFile.s ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This input was created by taking the instruction productions in // the old assembler's (6a's) grammar and hand-writing complete // instructions for each rule, to guarantee we cover the same space. #import "a-file.h" TEXT foo(SB), 0, $0 // LTYPE1 nonrem { outcode($1, &$2); } NEGQ R11 NEGQ 4(R11) NEGQ foo+4(SB) // LTYPE2 rimnon { outcode($1, &$2); } INT $4 DIVB R11 DIVB 4(R11) DIVB foo+4(SB) // LTYPE3 rimrem { outcode($1, &$2); } SUBQ $4, DI SUBQ R11, DI SUBQ 4(R11), DI SUBQ foo+4(SB), DI SUBQ $4, 8(R12) SUBQ R11, 8(R12) SUBQ R11, foo+4(SB) // LTYPE4 remrim { outcode($1, &$2); } CMPB CX, $4 // LTYPER nonrel { outcode($1, &$2); } label: JB -4(PC) JB label // LTYPEC spec3 { outcode($1, &$2); } JMP -4(PC) JMP label JMP foo+4(SB) JMP bar<>+4(SB) JMP bar<>+4(SB)(R11*4) JMP *4(SP) JMP *(R12) JMP *(R12*4) JMP *(R12)(R13*4) JMP *(AX) JMP *(SP) JMP *(AX*4) JMP *(AX)(AX*4) JMP 4(SP) JMP (R12) JMP (R12*4) JMP (R12)(R13*4) JMP (AX) JMP (SP) JMP (AX*4) JMP (AX)(AX*4) JMP R13 // LTYPEN spec4 { outcode($1, &$2); } NOP NOP AX NOP foo+4(SB) // LTYPES spec5 { outcode($1, &$2); } SHLL R11, R12 SHLL R11, foo+4(SB) SHLL R11, R11:AX // Old syntax, still accepted. // LTYPEM spec6 { outcode($1, &$2); } MOVL AX, R11 MOVL $4, R11 MOVL AX, AX:CS // LTYPEI spec7 { outcode($1, &$2); } IMULB $4 IMULB R11 IMULB $4, R11 IMULB R11, R12 IMULB R11, foo+4(SB) // LTYPEXC spec8 { outcode($1, &$2); } CMPPD R11, R12, 4 CMPPD R11, foo+4(SB), 4 // LTYPEX spec9 { outcode($1, &$2); } PINSRW $4, R11, AX PINSRW $4, foo+4(SB), AX // LTYPERT spec10 { outcode($1, &$2); } RETFL $4 // Was bug: LOOP is a branch instruction. loop: LOOP loop // LTYPE0 nonnon { outcode($1, &$2); } RET ================================================ FILE: plan9/testData/intel/lexer/simpleFile.txt ================================================ var ('var') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('ToBe') GO_WHITESPACE (' ') identifier ('bool') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('false') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('MaxInt') GO_WHITESPACE (' ') identifier ('uint64') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') int ('1') << ('<<') int ('64') GO_WHITESPACE (' ') - ('-') GO_WHITESPACE (' ') int ('1') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('z') GO_WHITESPACE (' ') identifier ('complex128') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('cmplx') . ('.') identifier ('Sqrt') ( ('(') - ('-') int ('5') GO_WHITESPACE (' ') + ('+') GO_WHITESPACE (' ') decimali ('12i') ) (')') ('') GO_WS_NEW_LINES ('\n') ) (')') ================================================ FILE: plan9/testData/intel/parser/SingleFunction.s ================================================ // foo() TEXT foo(SB),(NOSPLIT|NOPROF) loop: MOVL ================================================ FILE: plan9/testData/intel/parser/SingleFunction.txt ================================================ x86 File PsiComment(LINE_COMMENT)('// foo()') STATEMENT FUNCTION FUNCTION_HEADER PsiElement(TEXT)('TEXT') PsiElement(identifier)('foo') PsiElement(()('(') PsiElement(PSEUDO_REG)('SB') PsiElement())(')') PsiElement(,)(',') FUNCTION_FLAGS PsiElement(()('(') PsiElement(FLAG)('NOSPLIT') PsiElement(|)('|') PsiElement(FLAG)('NOPROF') PsiElement())(')') FUNCTION_BODY PsiElement(LABEL)('loop:') INSTRUCTION_STMT PsiElement(INSTRUCTION)('MOVL') OPERANDS ================================================ FILE: plan9/tests/com/plan9/intel/lang/core/lexer/AsmIntelLexerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.lang.core.lexer; import com.intellij.lexer.Lexer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.testFramework.LexerTestCase; import java.io.File; import java.io.IOException; public class AsmIntelLexerTest extends LexerTestCase { private static final String PATH = "testData/intel/lexer"; public void _testSimpleFile() { doTest(); } public void testCommentsAndWhitespace() { doTest(); } public void testIdentifiers() { doTest(); } private void doTest() { try { String text = FileUtil.loadFile(new File("./" + PATH + "/" + getTestName(true) + ".s")); String actual = printTokens(StringUtil.convertLineSeparators(text.trim()), 0); assertSameLinesWithFile(new File(PATH + "/" + getTestName(true) + ".txt").getAbsolutePath(), actual); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected Lexer createLexer() { return new AsmIntelLexer(); } @Override protected String getDirPath() { return "../" + PATH; } } ================================================ FILE: plan9/tests/com/plan9/intel/lang/core/parser/AsmIntelParserTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.plan9.intel.lang.core.parser; import com.intellij.testFramework.ParsingTestCase; import com.plan9.intel.lang.core.AsmIntelParserDefinition; import org.jetbrains.annotations.NotNull; public class AsmIntelParserTest extends ParsingTestCase { public AsmIntelParserTest() { super("parser", "s", new AsmIntelParserDefinition()); } @NotNull @Override protected String getTestDataPath() { return "testData/intel"; } @Override protected boolean skipSpaces() { return true; } @Override protected void doTest(boolean checkErrors) { super.doTest(true); if (checkErrors) { assertFalse( "PsiFile contains error elements", toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement") ); } } public void testSingleFunction() { doTest(false); } } ================================================ FILE: pluginResources/META-INF/plugin.xml ================================================ ro.redeul.google.go Go language (golang.org) support plugin 1.0 Custom Languages
  • Navigation
    • Go to inheritor structures
    • Go to super interfaces
  • Type-aware completion (aka Smart completion)
  • Extract function refactoring
  • Implement type
  • Inspections and quick-fixes
    • Introduce method
    • Introduce field
    • Delete unused parameter
    • Show symbol duplicates
    • Add/delete missing/redundant expressions in case of assignment count mismatch
    • Properly implemented Duplicated symbols inspection
    • Recursive type detection
    • Invalid const initialization
  • Tests and coverage
    • Sub-tests support (runner, navigation, gutter actions)
    • Debugging tests
  • Debugger
    • Step out
    • 100x faster performance
  • General
    • Highlighting of go:generate comments
    • Quick documentation for struct fields
    • Semantic highlighting
    • Parameter name hints
    • SQL auto-injection
    ]]>
    com.intellij.modules.lang com.intellij.modules.java com.intellij.modules.coverage com.goide.UpdateComponent
    ================================================ FILE: resources/META-INF/app-engine.xml ================================================ ================================================ FILE: resources/META-INF/coverage.xml ================================================ ================================================ FILE: resources/META-INF/gogland.xml ================================================ com.goide.project.GoModuleLibrariesInitializer com.goide.GoBundle go.intentions.category com.goide.intentions.GoAddFunctionBlockIntention com.goide.GoBundle go.intentions.category com.goide.intentions.GoMoveToStructInitializationIntention com.goide.ui.ProjectTutorialNotification org.jetbrains.plugins.yaml ================================================ FILE: resources/META-INF/google-app-engine-core-yaml.xml ================================================ ================================================ FILE: resources/META-INF/java-deps.xml ================================================ ================================================ FILE: resources/META-INF/plan9.xml ================================================ ================================================ FILE: resources/colorscheme/Darcula - dlsniper.xml ================================================ ================================================ FILE: resources/com/goide/GoBundle.properties ================================================ # # Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan # # 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. # # suppress inspection "UnusedProperty" – the property is required for showing list of links to nested configurables on root Go-configurable go.settings.description= go.intentions.category=Go ================================================ FILE: resources/fileTemplates/internal/Go Application.go.ft ================================================ package main func main() { } ================================================ FILE: resources/fileTemplates/internal/Go Application.go.html ================================================ This is Go application file template. Contains main function. ================================================ FILE: resources/fileTemplates/internal/Go File.go.ft ================================================ package ${GO_PACKAGE_NAME} ================================================ FILE: resources/fileTemplates/internal/Go File.go.html ================================================
    This is a built-in template used each time you create a new Go file, by selecting New | Go | Go File from the popup menu in one of the project views.
    The template is editable. Here you can use predefined variables (listed below) that will then be expanded like macros into the corresponding values.
    It is also possible to specify an arbitrary number of custom variables in the format ${<VARIABLE_NAME>}. In this case, before the new file is created, you will be prompted with a dialog where you can define particular values for all custom variables.
    Using the #parse directive, you can include templates from the Includes tab, by specifying the full name of the desired template as a parameter in quotation marks. For example:
    #parse("File Header.go")
    Predefined variables will take the following values:
    ${GO_PACKAGE_NAME_WITH_TEST_SUFFIX}   name of the package in which the new file is created if it's just regular file and package + '_test' suffix if the new file is a test file
    ${GO_PACKAGE_NAME}   name of the package in which the new file is created
    ${USER}   current user system login name
    ${DATE}   current system date
    ${TIME}   current system time
    ${YEAR}   current year
    ${MONTH}   current month
    ${MONTH_NAME_SHORT}   first 3 letters of the current month name. Example: Jan, Feb, etc.
    ${MONTH_NAME_FULL}   full name of the current month. Example: January, February, etc.
    ${DAY}   current day of the month
    ${HOUR}   current hour
    ${MINUTE}   current minute
    ${PROJECT_NAME}   the name of the current project
    ================================================ FILE: resources/inspectionDescriptions/GoAddTrailingComma.html ================================================ Need trailing comma before newline in composite literal. ================================================ FILE: resources/inspectionDescriptions/GoAnonymousFieldDefinitionType.html ================================================ Checks that type in pointer is type name ================================================ FILE: resources/inspectionDescriptions/GoAssignmentNilWithoutExplicitType.html ================================================ Check assignment nil without explicit type. ================================================ FILE: resources/inspectionDescriptions/GoAssignmentToConstant.html ================================================ Checks assignment to constants. ================================================ FILE: resources/inspectionDescriptions/GoAssignmentToReceiver.html ================================================ Checks for assignments to method receiver ================================================ FILE: resources/inspectionDescriptions/GoBoolExpressions.html ================================================ Checks bool expressions for redundant and suspect parts ================================================ FILE: resources/inspectionDescriptions/GoCgoInTest.html ================================================ Inspects cgo import in test files. ================================================ FILE: resources/inspectionDescriptions/GoCommentStart.html ================================================ Check if the comment starts with the correct name for exported elements. ================================================ FILE: resources/inspectionDescriptions/GoDeferGo.html ================================================ Checks defer/go statements: argument to go/defer must be function call. ================================================ FILE: resources/inspectionDescriptions/GoDeferInLoop.html ================================================ Checks if there are no calls to defer in loops. ================================================ FILE: resources/inspectionDescriptions/GoDirectAssignToStructFieldInMap.html ================================================ Check if an assignment is made directly to a struct field of a map ================================================ FILE: resources/inspectionDescriptions/GoDuplicateArgument.html ================================================ Inspects function declaration for duplicate parameters. ================================================ FILE: resources/inspectionDescriptions/GoDuplicateFieldsOrMethods.html ================================================ Checks duplicates: fields in struct types and method in interface types. ================================================ FILE: resources/inspectionDescriptions/GoDuplicateFunctionOrMethod.html ================================================ Checks function and method duplicates. ================================================ FILE: resources/inspectionDescriptions/GoDuplicateReturnArgument.html ================================================ This inspection checks function declaration for parameters redeclared in function return. ================================================ FILE: resources/inspectionDescriptions/GoEmbeddedInterfacePointer.html ================================================ This inspection checks if the embedded type is a pointer to an interface. ================================================ FILE: resources/inspectionDescriptions/GoEmptyDeclaration.html ================================================ Empty declaration inspection. ================================================ FILE: resources/inspectionDescriptions/GoExportedOwnDeclaration.html ================================================ This inspection checks whether exported var/const have its own declaration. ================================================ FILE: resources/inspectionDescriptions/GoFunctionCall.html ================================================ This inspection checks function calls. ================================================ FILE: resources/inspectionDescriptions/GoFunctionVariadicParameter.html ================================================ Inspects functions with variadic parameters for possible issues. ================================================ FILE: resources/inspectionDescriptions/GoImportUsedAsName.html ================================================ Inspects for declarations of variables, arguments or functions that overlap with the used import. If you receive this error then your code might not be as explicit as possible and might confuse other users. ================================================ FILE: resources/inspectionDescriptions/GoInfiniteFor.html ================================================ Checks empty for loops ================================================ FILE: resources/inspectionDescriptions/GoInvalidPackageImport.html ================================================ This inspection highlights invalid imports. ================================================ FILE: resources/inspectionDescriptions/GoInvalidStringOrChar.html ================================================ Checks not correctly formed string and rune literals. ================================================ FILE: resources/inspectionDescriptions/GoMissingReturn.html ================================================ Missing return at end of function. ================================================ FILE: resources/inspectionDescriptions/GoMixedNamedUnnamedParameters.html ================================================ Check if the function declares named and unnamed return parameters for ================================================ FILE: resources/inspectionDescriptions/GoMultiplePackages.html ================================================ Checks multiple packages in directory declaration. ================================================ FILE: resources/inspectionDescriptions/GoNoNewVariables.html ================================================ No new variables on left side of :=. ================================================ FILE: resources/inspectionDescriptions/GoPlaceholderCount.html ================================================ Checks the placeholders count in functions / methods.

    Known functions are (case-insensitive):
    • fmt.Printf
    • fmt.Sprintf
    • fmt.Errorf
    • fmt.Fprintf
    • fmt.Fscanf
    • fmt.Scanf
    • fmt.Sscanf
    • log.Printf
    • log.Fatalf
    • log.Panicf
    ================================================ FILE: resources/inspectionDescriptions/GoRangeIterationOnIllegalType.html ================================================ This checks if the range iteration happens on a permitted type ================================================ FILE: resources/inspectionDescriptions/GoReceiverNames.html ================================================ Inspection checks that names like me, this, self are not used in receiver names.

    See https://github.com/golang/go/wiki/CodeReviewComments#receiver-names for details

    ================================================ FILE: resources/inspectionDescriptions/GoRedeclareImportAsFunction.html ================================================ This inspection checks if a function is named in the same way as an existing import. ================================================ FILE: resources/inspectionDescriptions/GoRedundantBlankArgInRange.html ================================================ This inspection checks whether expression of range clause is redundant and can be deleted

    For example following for statements can be simplified.


    for _ = range v

    for _, _ = range v

    for a, _ = range v

    ================================================ FILE: resources/inspectionDescriptions/GoRedundantSecondIndexInSlices.html ================================================ Redundant second index in slices inspection
    Example: a[0:len(a)] ================================================ FILE: resources/inspectionDescriptions/GoRedundantTypeDeclInCompositeLit.html ================================================ Inspection checks redundant type declaration in composite literals Example: []int { int{1}, int{2}} ================================================ FILE: resources/inspectionDescriptions/GoReservedWordUsedAsName.html ================================================ Inspects for declarations of variables, arguments or functions that overlap with the built-in or reserved keyword. If you receive this error then your code might not be as explicit as possible and might confuse other users. ================================================ FILE: resources/inspectionDescriptions/GoSelfImport.html ================================================ Inspects file for own path imports. ================================================ FILE: resources/inspectionDescriptions/GoStringAndByteTypeMismatch.html ================================================ Reports comparisons of string index with a single-byte string instead of byte. ================================================ FILE: resources/inspectionDescriptions/GoStructInitialization.html ================================================ This inspection checks if the structures are initialized without specifying their field names. When initializing a structure, it's better to explicitly state the name of the fields in order to ensure that in case of changes in the order of the fields or the name of the fields they will correctly continue to be addressed. ================================================ FILE: resources/inspectionDescriptions/GoStructTag.html ================================================ Verifies that struct tags conform to Go conventions.

    According to these conventions, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

    ================================================ FILE: resources/inspectionDescriptions/GoTestSignatures.html ================================================ Checks test functions signatures. ================================================ FILE: resources/inspectionDescriptions/GoUnderscoreUsedAsValue.html ================================================ Checks if underscore is used as value. ================================================ FILE: resources/inspectionDescriptions/GoUnresolvedReference.html ================================================ Checks references. ================================================ FILE: resources/inspectionDescriptions/GoUnusedConst.html ================================================ Checks for unused constants. ================================================ FILE: resources/inspectionDescriptions/GoUnusedExportedFunction.html ================================================ Checks unused exported functions. ================================================ FILE: resources/inspectionDescriptions/GoUnusedFunction.html ================================================ Checks unused unexported functions. ================================================ FILE: resources/inspectionDescriptions/GoUnusedGlobalVariable.html ================================================ Checks for unused global variables. ================================================ FILE: resources/inspectionDescriptions/GoUnusedImport.html ================================================ Reports any import statements that are unused. ================================================ FILE: resources/inspectionDescriptions/GoUnusedLabel.html ================================================ Checks for unused label definitions. ================================================ FILE: resources/inspectionDescriptions/GoUnusedParameter.html ================================================ Check for unused function parameters ================================================ FILE: resources/inspectionDescriptions/GoUnusedVariable.html ================================================ Checks for unused variables. ================================================ FILE: resources/inspectionDescriptions/GoUsedAsValueInCondition.html ================================================ Check if assignment is used as value. ================================================ FILE: resources/inspectionDescriptions/GoVarDeclaration.html ================================================ Checks variable declarations. ================================================ FILE: resources/intentionDescriptions/GoAddFunctionBlockIntention/after.go.template ================================================ func functionName() { } ================================================ FILE: resources/intentionDescriptions/GoAddFunctionBlockIntention/before.go.template ================================================ func functionName() ================================================ FILE: resources/intentionDescriptions/GoAddFunctionBlockIntention/description.html ================================================ This intention adds braces to function or method without a block.
    ================================================ FILE: resources/intentionDescriptions/GoMoveToStructInitializationIntention/after.go.template ================================================ s := S{foo: `bar`} ================================================ FILE: resources/intentionDescriptions/GoMoveToStructInitializationIntention/before.go.template ================================================ s := S{} s.foo = `bar` ================================================ FILE: resources/intentionDescriptions/GoMoveToStructInitializationIntention/description.html ================================================ This intention moves struct field assignment to struct initialization block. ================================================ FILE: resources/liveTemplates/go.xml ================================================ ================================================ FILE: resources/liveTemplates/goHidden.xml ================================================ ================================================ FILE: resources/liveTemplates/goTags.xml ================================================ ================================================ FILE: settings.gradle ================================================ rootProject.name = 'intellij-go' include 'utils', 'google-app-engine', 'google-app-engine:google-app-engine-yaml', 'plan9' ================================================ FILE: src/com/goide/GoCommenter.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.lang.CodeDocumentationAwareCommenter; import com.intellij.psi.PsiComment; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.Nullable; public class GoCommenter implements CodeDocumentationAwareCommenter { @Nullable @Override public String getLineCommentPrefix() { return "//"; } @Nullable @Override public String getBlockCommentPrefix() { return "/*"; } @Nullable @Override public String getBlockCommentSuffix() { return "*/"; } @Nullable @Override public String getCommentedBlockCommentPrefix() { return null; } @Nullable @Override public String getCommentedBlockCommentSuffix() { return null; } @Nullable @Override public IElementType getLineCommentTokenType() { return GoParserDefinition.LINE_COMMENT; } @Nullable @Override public IElementType getBlockCommentTokenType() { return GoParserDefinition.MULTILINE_COMMENT; } @Nullable @Override public IElementType getDocumentationCommentTokenType() { return null; } @Nullable @Override public String getDocumentationCommentPrefix() { return null; } @Nullable @Override public String getDocumentationCommentLinePrefix() { return null; } @Nullable @Override public String getDocumentationCommentSuffix() { return null; } @Override public boolean isDocumentationComment(PsiComment comment) { return false; } } ================================================ FILE: src/com/goide/GoCommentsConverter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiComment; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.URLUtil; import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * See https://golang.org/src/go/doc/comment.go */ public class GoCommentsConverter { private static final Pattern LEADING_TAB = Pattern.compile("^\\t", Pattern.MULTILINE); @NotNull public String toText(@NotNull List comments) { return StringUtil.join(getStrings(comments), "\n"); } @NotNull public String toHtml(@NotNull List comments) { return textToHtml(getStrings(comments)); } @NotNull private static List getStrings(@NotNull List comments) { List strings = ContainerUtil.newArrayList(); for (PsiComment comment : comments) { IElementType type = comment.getTokenType(); if (type == GoParserDefinition.LINE_COMMENT) { strings.add(StringUtil.trimStart(StringUtil.trimStart(comment.getText(), "//"), " ")); } else if (type == GoParserDefinition.MULTILINE_COMMENT) { String text = StringUtil.trimEnd(comment.getText(), "*/"); text = StringUtil.trimStart(text, "/*"); text = LEADING_TAB.matcher(text).replaceAll(""); Collections.addAll(strings, StringUtil.splitByLines(text, false)); } } return strings; } @NotNull public String textToHtml(@NotNull List strings) { State state = new State(strings.iterator()); while (state.hasNext()) { state.next(); if (state.indented()) { state.flushBlock("p"); processIndentedBlock(state); } processSimpleBlock(state); } state.flushBlock("p"); return state.result(); } private static void processSimpleBlock(@NotNull State state) { if (state.isBlank()) { state.flushBlock("p"); } else { state.append(state.text, true); state.append("\n"); // just for prettier testdata } } private static void processIndentedBlock(@NotNull State state) { state.append(state.text); int emptyLines = 1; String text; while ((text = state.next()) != null) { if (state.isBlank()) { emptyLines++; } else if (state.indented()) { state.append(StringUtil.repeatSymbol('\n', emptyLines)).append(text); emptyLines = 1; } else { break; } } state.flushBlock("pre"); } private static class State { @NotNull private final StringBuilder currentBlock = new StringBuilder(); @NotNull private final StringBuilder result = new StringBuilder(); @NotNull private final Iterator iterator; @Nullable private String text; public State(@NotNull Iterator iterator) { this.iterator = iterator; } String next() { return text = iterator.hasNext() ? iterator.next() : null; } boolean isBlank() { return text != null && text.trim().isEmpty(); } boolean hasNext() { return iterator.hasNext(); } boolean indented() { return text != null && (StringUtil.startsWithChar(text, ' ') || StringUtil.startsWithChar(text, '\t')); } State append(@Nullable String text, boolean nice) { if (StringUtil.isNotEmpty(text)) { currentBlock.append(emphasize(text, nice)); } return this; } State append(@Nullable String text) { return append(text, false); } /** * Escape comment text for HTML. If nice is set, also turn `` into “ and '' into ”. */ private static String emphasize(@NotNull String text, boolean nice) { text = XmlStringUtil.escapeString(text); StringBuilder textWithLinks = null; Matcher matcher = URLUtil.URL_PATTERN.matcher(text); while (matcher.find()) { if (textWithLinks == null) { textWithLinks = new StringBuilder(); } textWithLinks.append(text.substring(0, matcher.start())) .append("").append(matcher.group()).append(""); } if (textWithLinks != null) { text = textWithLinks.toString(); } return nice ? StringUtil.replace(text, new String[]{"``", "''"}, new String[]{"“", "”"}) : text; } void flushBlock(@NotNull String wrapTag) { if (currentBlock.length() > 0) { result.append('<').append(wrapTag).append(">").append(currentBlock).append("\n"); currentBlock.setLength(0); } } String result() { return result.toString(); } } } ================================================ FILE: src/com/goide/GoDocumentationProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.editor.GoParameterInfoHandler; import com.goide.project.GoVendoringUtil; import com.goide.psi.*; import com.goide.psi.impl.GoCType; import com.goide.psi.impl.GoLightType; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.sdk.GoPackageUtil; import com.goide.sdk.GoSdkUtil; import com.goide.stubs.index.GoAllPrivateNamesIndex; import com.goide.stubs.index.GoAllPublicNamesIndex; import com.goide.stubs.index.GoIdFilter; import com.goide.util.GoUtil; import com.intellij.codeInsight.documentation.DocumentationManagerProtocol; import com.intellij.lang.ASTNode; import com.intellij.lang.documentation.AbstractDocumentationProvider; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IdFilter; import com.intellij.xml.util.XmlStringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoDocumentationProvider extends AbstractDocumentationProvider { private static final Logger LOG = Logger.getInstance(GoDocumentationProvider.class); private static final GoCommentsConverter COMMENTS_CONVERTER = new GoCommentsConverter(); @NotNull public static String getCommentText(@NotNull List comments, boolean withHtml) { return withHtml ? COMMENTS_CONVERTER.toHtml(comments) : COMMENTS_CONVERTER.toText(comments); } @NotNull public static List getCommentsForElement(@Nullable PsiElement element) { List comments = getCommentsInner(element); if (comments.isEmpty()) { if (element instanceof GoVarDefinition || element instanceof GoConstDefinition) { PsiElement parent = element.getParent(); // spec comments = getCommentsInner(parent); if (comments.isEmpty() && parent != null) { return getCommentsInner(parent.getParent()); // declaration } } else if (element instanceof GoTypeSpec) { return getCommentsInner(element.getParent()); // type declaration } } return comments; } @NotNull private static List getCommentsInner(@Nullable PsiElement element) { if (element == null) { return ContainerUtil.emptyList(); } List result = ContainerUtil.newArrayList(); PsiElement e; for (e = element.getPrevSibling(); e != null; e = e.getPrevSibling()) { if (e instanceof PsiWhiteSpace) { if (e.getText().contains("\n\n")) return result; continue; } if (e instanceof PsiComment) { result.add(0, (PsiComment)e); } else { return result; } } return result; } @Nullable private static GoFile findDocFileForDirectory(@NotNull PsiDirectory directory) { PsiFile file = directory.findFile("doc.go"); if (file instanceof GoFile) { return (GoFile)file; } PsiFile directoryFile = directory.findFile(GoUtil.suggestPackageForDirectory(directory) + ".go"); return directoryFile instanceof GoFile ? (GoFile)directoryFile : null; } @Nullable private static String getPackageComment(@Nullable GoFile file) { if (file != null) { boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(ModuleUtilCore.findModuleForPsiElement(file)); // todo: remove after correct stubbing (comments needed in stubs) GoPackageClause pack = PsiTreeUtil.findChildOfType(file, GoPackageClause.class); String title = "Package " + GoUtil.suggestPackageForDirectory(file.getParent()) + "\n"; String importPath = "

    import \"" + StringUtil.notNullize(file.getImportPath(vendoringEnabled)) + "\"

    \n"; return title + importPath + getCommentText(getCommentsForElement(pack), true); } return null; } @Nullable private static PsiElement adjustDocElement(@Nullable PsiElement element) { return element instanceof GoImportSpec ? ((GoImportSpec)element).getImportString().resolve() : element; } @NotNull private static String getSignature(PsiElement element, PsiElement context) { if (element instanceof GoTypeSpec) { String name = ((GoTypeSpec)element).getName(); return StringUtil.isNotEmpty(name) ? "type " + name : ""; } GoDocumentationPresentationFunction presentationFunction = new GoDocumentationPresentationFunction(getImportPathForElement(element)); if (element instanceof GoConstDefinition) { String name = ((GoConstDefinition)element).getName(); if (StringUtil.isNotEmpty(name)) { String type = getTypePresentation(((GoConstDefinition)element).getGoType(null), presentationFunction); GoExpression value = ((GoConstDefinition)element).getValue(); return "const " + name + (!type.isEmpty() ? " " + type : "") + (value != null ? " = " + value.getText() : ""); } } if (element instanceof GoVarDefinition) { String name = ((GoVarDefinition)element).getName(); if (StringUtil.isNotEmpty(name)) { String type = getTypePresentation(((GoVarDefinition)element).getGoType(GoPsiImplUtil.createContextOnElement(context)), presentationFunction); GoExpression value = ((GoVarDefinition)element).getValue(); return "var " + name + (!type.isEmpty() ? " " + type : "") + (value != null ? " = " + value.getText() : ""); } } if (element instanceof GoParamDefinition) { String name = ((GoParamDefinition)element).getName(); if (StringUtil.isNotEmpty(name)) { String type = getTypePresentation(((GoParamDefinition)element).getGoType(GoPsiImplUtil.createContextOnElement(context)), presentationFunction); return "var " + name + (!type.isEmpty() ? " " + type : ""); } } if (element instanceof GoReceiver) { String name = ((GoReceiver)element).getName(); if (StringUtil.isNotEmpty(name)) { String type = getTypePresentation(((GoReceiver)element).getGoType(GoPsiImplUtil.createContextOnElement(context)), presentationFunction); return "var " + name + (!type.isEmpty() ? " " + type : ""); } } return element instanceof GoSignatureOwner ? getSignatureOwnerTypePresentation((GoSignatureOwner)element, presentationFunction) : ""; } @NotNull private static String getSignatureOwnerTypePresentation(@NotNull GoSignatureOwner signatureOwner, @NotNull Function presentationFunction) { PsiElement identifier = null; if (signatureOwner instanceof GoNamedSignatureOwner) { identifier = ((GoNamedSignatureOwner)signatureOwner).getIdentifier(); } GoSignature signature = signatureOwner.getSignature(); if (identifier == null && signature == null) { return ""; } StringBuilder builder = new StringBuilder("func ").append(identifier != null ? identifier.getText() : "").append('('); if (signature != null) { builder.append(getParametersAsString(signature.getParameters())); } builder.append(')'); GoResult result = signature != null ? signature.getResult() : null; GoParameters parameters = result != null ? result.getParameters() : null; GoType type = result != null ? result.getType() : null; if (parameters != null) { String signatureParameters = getParametersAsString(parameters); if (!signatureParameters.isEmpty()) { builder.append(" (").append(signatureParameters).append(')'); } } else if (type != null) { builder.append(' ').append(getTypePresentation(type, presentationFunction)); } return builder.toString(); } @NotNull private static String getParametersAsString(@NotNull GoParameters parameters) { String contextImportPath = getImportPathForElement(parameters); return StringUtil.join(GoParameterInfoHandler.getParameterPresentations(parameters, element -> getTypePresentation(element, new GoDocumentationPresentationFunction(contextImportPath))), ", "); } @Nullable private static String getImportPathForElement(@Nullable PsiElement element) { PsiFile file = element != null ? element.getContainingFile() : null; return file instanceof GoFile ? ((GoFile)file).getImportPath(false) : null; } @NotNull public static String getTypePresentation(@Nullable PsiElement element, @NotNull Function presentationFunction) { if (element instanceof GoType) { GoType type = (GoType)element; if (type instanceof GoMapType) { GoType keyType = ((GoMapType)type).getKeyType(); GoType valueType = ((GoMapType)type).getValueType(); return "map[" + getTypePresentation(keyType, presentationFunction) + "]" + getTypePresentation(valueType, presentationFunction); } if (type instanceof GoChannelType) { ASTNode typeNode = type.getNode(); GoType innerType = ((GoChannelType)type).getType(); ASTNode innerTypeNode = innerType != null ? innerType.getNode() : null; if (typeNode != null && innerTypeNode != null) { StringBuilder result = new StringBuilder(); for (ASTNode node : typeNode.getChildren(null)) { if (node.equals(innerTypeNode)) { break; } if (node.getElementType() != TokenType.WHITE_SPACE) { result.append(XmlStringUtil.escapeString(node.getText())); } } result.append(" ").append(getTypePresentation(innerType, presentationFunction)); return result.toString(); } } if (type instanceof GoParType) { return "(" + getTypePresentation(((GoParType)type).getActualType(), presentationFunction) + ")"; } if (type instanceof GoArrayOrSliceType) { return "[]" + getTypePresentation(((GoArrayOrSliceType)type).getType(), presentationFunction); } if (type instanceof GoPointerType) { GoType inner = ((GoPointerType)type).getType(); return inner instanceof GoSpecType ? getTypePresentation(inner, presentationFunction) : "*" + getTypePresentation(inner, presentationFunction); } if (type instanceof GoTypeList) { return "(" + StringUtil.join(((GoTypeList)type).getTypeList(), element1 -> getTypePresentation(element1, presentationFunction), ", ") + ")"; } if (type instanceof GoFunctionType) { return getSignatureOwnerTypePresentation((GoFunctionType)type, presentationFunction); } if (type instanceof GoSpecType) { return getTypePresentation(GoPsiImplUtil.getTypeSpecSafe(type), presentationFunction); } if (type instanceof GoCType) { return "C"; } if (type instanceof GoLightType) { LOG.error("Cannot build presentable text for type: " + type.getClass().getSimpleName() + " - " + type.getText()); return ""; } if (type instanceof GoStructType) { StringBuilder result = new StringBuilder("struct {"); result.append(StringUtil.join(((GoStructType)type).getFieldDeclarationList(), declaration -> { GoAnonymousFieldDefinition anon = declaration.getAnonymousFieldDefinition(); String fieldString = anon != null ? getTypePresentation(anon.getGoTypeInner(null), presentationFunction) : StringUtil.join(declaration.getFieldDefinitionList(), PsiElement::getText, ", ") + " " + getTypePresentation(declaration.getType(), presentationFunction); GoTag tag = declaration.getTag(); return fieldString + (tag != null ? tag.getText() : ""); }, "; ")); return result.append("}").toString(); } GoTypeReferenceExpression typeRef = GoPsiImplUtil.getTypeReference(type); if (typeRef != null) { PsiElement resolve = typeRef.resolve(); if (resolve != null) { return getTypePresentation(resolve, presentationFunction); } } } return presentationFunction.fun(element); } @Nullable public static String getLocalUrlToElement(@NotNull PsiElement element) { if (element instanceof GoTypeSpec || element instanceof PsiDirectory) { return getReferenceText(element, true); } return null; } @Nullable private static String getReferenceText(@Nullable PsiElement element, boolean includePackageName) { if (element instanceof GoNamedElement) { PsiFile file = element.getContainingFile(); if (file instanceof GoFile) { String importPath = ((GoFile)file).getImportPath(false); if (element instanceof GoFunctionDeclaration || element instanceof GoTypeSpec) { String name = ((GoNamedElement)element).getName(); if (StringUtil.isNotEmpty(name)) { String fqn = getElementFqn((GoNamedElement)element, name, includePackageName); return String.format("%s#%s", StringUtil.notNullize(importPath), fqn); } } else if (element instanceof GoMethodDeclaration) { GoType receiverType = ((GoMethodDeclaration)element).getReceiverType(); String receiver = getReceiverTypeText(receiverType); String name = ((GoMethodDeclaration)element).getName(); if (StringUtil.isNotEmpty(receiver) && StringUtil.isNotEmpty(name)) { String fqn = getElementFqn((GoNamedElement)element, name, includePackageName); return String.format("%s#%s.%s", StringUtil.notNullize(importPath), receiver, fqn); } } } } else if (element instanceof PsiDirectory && findDocFileForDirectory((PsiDirectory)element) != null) { return GoSdkUtil.getImportPath((PsiDirectory)element, false); } return null; } private static String getReceiverTypeText(@Nullable GoType type) { if (type == null) return null; if (type instanceof GoPointerType) { GoType inner = ((GoPointerType)type).getType(); if (inner != null) return inner.getText(); } return type.getText(); } @NotNull private static String getElementFqn(@NotNull GoNamedElement element, @NotNull String name, boolean includePackageName) { if (includePackageName) { String packageName = element.getContainingFile().getPackageName(); if (!StringUtil.isEmpty(packageName)) { return packageName + "." + name; } } return name; } @Override public String generateDoc(PsiElement element, PsiElement originalElement) { element = adjustDocElement(element); if (element instanceof GoNamedElement) { String signature = getSignature(element, originalElement); signature = StringUtil.isNotEmpty(signature) ? "" + signature + "\n" : signature; return StringUtil.nullize(signature + getCommentText(getCommentsForElement(element), true)); } if (element instanceof PsiDirectory) { return getPackageComment(findDocFileForDirectory((PsiDirectory)element)); } return null; } @Override public List getUrlFor(PsiElement element, PsiElement originalElement) { String referenceText = getReferenceText(adjustDocElement(element), false); if (StringUtil.isNotEmpty(referenceText)) { return Collections.singletonList("https://godoc.org/" + referenceText); } return super.getUrlFor(element, originalElement); } @Nullable @Override public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { if (element instanceof GoNamedElement) { String result = getSignature(element, originalElement); if (StringUtil.isNotEmpty(result)) return result; } return super.getQuickNavigateInfo(element, originalElement); } @Override public PsiElement getDocumentationElementForLink(PsiManager psiManager, String link, PsiElement context) { if (context != null && !DumbService.isDumb(psiManager.getProject())) { // it's important to ask module on file, otherwise module won't be found for elements in libraries files [zolotov] Module module = ModuleUtilCore.findModuleForPsiElement(context.getContainingFile()); int hash = link.indexOf('#'); String importPath = hash >= 0 ? link.substring(0, hash) : link; Project project = psiManager.getProject(); VirtualFile directory = GoPackageUtil.findByImportPath(importPath, project, module); PsiDirectory psiDirectory = directory != null ? psiManager.findDirectory(directory) : null; String anchor = hash >= 0 ? link.substring(Math.min(hash + 1, link.length())) : null; if (StringUtil.isNotEmpty(anchor)) { GlobalSearchScope scope = psiDirectory != null ? GoPackageUtil.packageScope(psiDirectory, null) : GlobalSearchScope.projectScope(project); IdFilter idFilter = GoIdFilter.getFilesFilter(scope); GoNamedElement element = ContainerUtil.getFirstItem(StubIndex.getElements(GoAllPublicNamesIndex.ALL_PUBLIC_NAMES, anchor, project, scope, idFilter, GoNamedElement.class)); if (element != null) { return element; } return ContainerUtil.getFirstItem(StubIndex.getElements(GoAllPrivateNamesIndex.ALL_PRIVATE_NAMES, anchor, project, scope, idFilter, GoNamedElement.class)); } else { return psiDirectory; } } return super.getDocumentationElementForLink(psiManager, link, context); } private static class GoDocumentationPresentationFunction implements Function { private final String myContextImportPath; public GoDocumentationPresentationFunction(@Nullable String contextImportPath) { myContextImportPath = contextImportPath; } @Override public String fun(PsiElement element) { if (element instanceof GoTypeSpec) { String localUrl = getLocalUrlToElement(element); String name = ((GoTypeSpec)element).getName(); if (StringUtil.isNotEmpty(name)) { String importPath = getImportPathForElement(element); GoFile file = ((GoTypeSpec)element).getContainingFile(); String packageName = file.getPackageName(); if (StringUtil.isNotEmpty(packageName) && !GoPsiImplUtil.isBuiltinFile(file) && !Comparing.equal(importPath, myContextImportPath)) { return String.format("%s.%s", DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL, StringUtil.notNullize(importPath), packageName, DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL, localUrl, name); } return String.format("%s", DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL, localUrl, name); } } return element != null ? element.getText() : ""; } } } ================================================ FILE: src/com/goide/GoFileElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.psi.GoFile; import com.goide.stubs.GoFileStub; import com.goide.stubs.index.GoPackagesIndex; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.StubBuilder; import com.intellij.psi.stubs.*; import com.intellij.psi.tree.IStubFileElementType; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoFileElementType extends IStubFileElementType { public static final IStubFileElementType INSTANCE = new GoFileElementType(); public static final int VERSION = 21; private GoFileElementType() { super("GO_FILE", GoLanguage.INSTANCE); } @Override public int getStubVersion() { return VERSION; } @NotNull @Override public StubBuilder getBuilder() { return new DefaultStubBuilder() { @NotNull @Override protected StubElement createStubForFile(@NotNull PsiFile file) { if (file instanceof GoFile) { return new GoFileStub((GoFile)file); } return super.createStubForFile(file); } }; } @Override public void indexStub(@NotNull GoFileStub stub, @NotNull IndexSink sink) { super.indexStub(stub, sink); String packageName = stub.getPackageName(); if (StringUtil.isNotEmpty(packageName)) { sink.occurrence(GoPackagesIndex.KEY, packageName); } } @Override public void serialize(@NotNull GoFileStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeUTF(StringUtil.notNullize(stub.getBuildFlags())); } @NotNull @Override public GoFileStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoFileStub(null, StringRef.fromNullableString(StringUtil.nullize(dataStream.readUTF()))); } @NotNull @Override public String getExternalId() { return "go.FILE"; } } ================================================ FILE: src/com/goide/GoFileType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.nio.charset.Charset; public class GoFileType extends LanguageFileType { public static final LanguageFileType INSTANCE = new GoFileType(); protected GoFileType() { super(GoLanguage.INSTANCE); } @NotNull @Override public String getName() { return GoConstants.GO; } @NotNull @Override public String getDescription() { return "Go files"; } @NotNull @Override public String getDefaultExtension() { return "go"; } @Nullable @Override public Icon getIcon() { return GoIcons.ICON; } @Override public String getCharset(@NotNull VirtualFile file, @NotNull byte[] content) { return CharsetToolkit.UTF8; } @Override public Charset extractCharsetFromFileContent(@Nullable Project project, @Nullable VirtualFile file, @NotNull CharSequence content) { return CharsetToolkit.UTF8_CHARSET; } } ================================================ FILE: src/com/goide/GoFileTypeFactory.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class GoFileTypeFactory extends FileTypeFactory { @Override public void createFileTypes(@NotNull FileTypeConsumer consumer) { consumer.consume(GoFileType.INSTANCE, GoFileType.INSTANCE.getDefaultExtension()); } } ================================================ FILE: src/com/goide/GoIconProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.psi.GoFile; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.ide.IconProvider; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoIconProvider extends IconProvider implements DumbAware { @Nullable @Override public Icon getIcon(@NotNull PsiElement e, @Iconable.IconFlags int flags) { return e instanceof GoFile && e.isValid() && GoTestFinder.isTestFile((GoFile)e) ? GoIcons.TEST_RUN : null; } } ================================================ FILE: src/com/goide/GoIcons.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.icons.AllIcons; import com.intellij.openapi.util.IconLoader; import com.intellij.ui.LayeredIcon; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import javax.swing.*; @SuppressWarnings("ConstantConditions") public interface GoIcons { Icon ICON = IconLoader.findIcon("/icons/go.png"); Icon TYPE = IconLoader.findIcon("/icons/type.png"); Icon APPLICATION_RUN = Helper.createIconWithShift(ICON, AllIcons.Nodes.RunnableMark); Icon TEST_RUN = Helper.createIconWithShift(ICON, AllIcons.Nodes.JunitTestMark); Icon METHOD = AllIcons.Nodes.Method; Icon FUNCTION = AllIcons.Nodes.Function; Icon VARIABLE = AllIcons.Nodes.Variable; Icon CONSTANT = IconLoader.findIcon("/icons/constant.png"); Icon PARAMETER = AllIcons.Nodes.Parameter; Icon FIELD = AllIcons.Nodes.Field; Icon LABEL = null; // todo: we need an icon here! Icon RECEIVER = AllIcons.Nodes.Parameter; Icon PACKAGE = AllIcons.Nodes.Package; Icon MODULE_ICON = IconLoader.findIcon("/icons/goModule.png"); Icon DEBUG = ICON; Icon DIRECTORY = PlatformIcons.DIRECTORY_CLOSED_ICON; class Helper { private Helper() {} @NotNull public static LayeredIcon createIconWithShift(@NotNull Icon base, Icon mark) { LayeredIcon icon = new LayeredIcon(2) { @Override public int getIconHeight() { return base.getIconHeight(); } }; icon.setIcon(base, 0); icon.setIcon(mark, 1, 0, base.getIconWidth() / 2); return icon; } } } ================================================ FILE: src/com/goide/GoIndexPatternBuilder.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.psi.GoFile; import com.intellij.lexer.Lexer; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.search.IndexPatternBuilder; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoIndexPatternBuilder implements IndexPatternBuilder { @Nullable @Override public Lexer getIndexingLexer(@NotNull PsiFile file) { return file instanceof GoFile ? ((GoFile)file).getParserDefinition().createLexer(file.getProject()) : null; } @Nullable @Override public TokenSet getCommentTokenSet(@NotNull PsiFile file) { return GoParserDefinition.COMMENTS; } @Override public int getCommentStartDelta(IElementType tokenType) { return 0; } @Override public int getCommentEndDelta(IElementType tokenType) { return tokenType == GoParserDefinition.MULTILINE_COMMENT ? 2 : 0; } } ================================================ FILE: src/com/goide/GoLanguage.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoLanguage extends Language { public static final Language INSTANCE = new GoLanguage(); private GoLanguage() { super("go", "text/go", "text/x-go", "application/x-go"); } @NotNull @Override public String getDisplayName() { return GoConstants.GO; } @Nullable @Override public LanguageFileType getAssociatedFileType() { return GoFileType.INSTANCE; } @Override public boolean isCaseSensitive() { return true; } } ================================================ FILE: src/com/goide/GoModuleBuilder.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.sdk.GoSdkType; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.ide.util.projectWizard.JavaModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleBuilderListener; import com.intellij.ide.util.projectWizard.SourcePathsBuilder; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.projectRoots.SdkTypeId; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.util.Pair; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoModuleBuilder extends JavaModuleBuilder implements SourcePathsBuilder, ModuleBuilderListener { @Override public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException { addListener(this); super.setupRootModel(modifiableRootModel); } @Override public List> getSourcePaths() { return ContainerUtil.emptyList(); } @NotNull @Override public ModuleType getModuleType() { return GoModuleType.getInstance(); } @Override public boolean isSuitableSdkType(SdkTypeId sdkType) { return sdkType == GoSdkType.getInstance(); } @Override public void moduleCreated(@NotNull Module module) { CompilerWorkspaceConfiguration.getInstance(module.getProject()).CLEAR_OUTPUT_DIRECTORY = false; } } ================================================ FILE: src/com/goide/GoModuleType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.sdk.GoSdkType; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.ProjectJdkForModuleStep; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoModuleType extends ModuleType { public GoModuleType() { super(GoConstants.MODULE_TYPE_ID); } @NotNull public static GoModuleType getInstance() { return (GoModuleType)ModuleTypeManager.getInstance().findByID(GoConstants.MODULE_TYPE_ID); } @NotNull @Override public GoModuleBuilder createModuleBuilder() { return new GoModuleBuilder(); } @NotNull @Override public String getName() { return "Go Module"; } @NotNull @Override public String getDescription() { return "Go modules are used for developing Go applications."; } @Nullable @Override public Icon getBigIcon() { return GoIcons.MODULE_ICON; } @Nullable @Override public Icon getNodeIcon(boolean isOpened) { return GoIcons.ICON; } @NotNull @Override public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull GoModuleBuilder moduleBuilder, @NotNull ModulesProvider modulesProvider) { return new ModuleWizardStep[]{new ProjectJdkForModuleStep(wizardContext, GoSdkType.getInstance()) { @Override public void updateDataModel() { super.updateDataModel(); moduleBuilder.setModuleJdk(getJdk()); } }}; } } ================================================ FILE: src/com/goide/GoNamesValidator.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.lexer.GoLexer; import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.project.Project; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoNamesValidator implements NamesValidator { @Override public boolean isKeyword(@NotNull String name, Project project) { return GoParserDefinition.KEYWORDS.contains(getLexerType(name)); } @Override public boolean isIdentifier(@NotNull String name, Project project) { return getLexerType(name) == GoTypes.IDENTIFIER; } @Nullable private static IElementType getLexerType(@NotNull String text) { GoLexer lexer = new GoLexer(); lexer.start(text); return lexer.getTokenEnd() == text.length() ? lexer.getTokenType() : null; } } ================================================ FILE: src/com/goide/GoParserDefinition.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.lexer.GoLexer; import com.goide.parser.GoParser; import com.goide.psi.GoFile; import com.goide.psi.GoTokenType; import com.intellij.lang.ASTNode; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import static com.goide.GoTypes.*; public class GoParserDefinition implements ParserDefinition { public static final IElementType LINE_COMMENT = new GoTokenType("GO_LINE_COMMENT"); public static final IElementType MULTILINE_COMMENT = new GoTokenType("GO_MULTILINE_COMMENT"); public static final IElementType WS = new GoTokenType("GO_WHITESPACE"); public static final IElementType NLS = new GoTokenType("GO_WS_NEW_LINES"); public static final TokenSet WHITESPACES = TokenSet.create(WS, NLS); public static final TokenSet COMMENTS = TokenSet.create(LINE_COMMENT, MULTILINE_COMMENT); public static final TokenSet STRING_LITERALS = TokenSet.create(STRING, RAW_STRING, CHAR); public static final TokenSet NUMBERS = TokenSet.create(INT, FLOAT, FLOATI, DECIMALI, FLOATI); // todo: HEX, OCT, public static final TokenSet KEYWORDS = TokenSet.create( BREAK, CASE, CHAN, CONST, CONTINUE, DEFAULT, DEFER, ELSE, FALLTHROUGH, FOR, FUNC, GO, GOTO, IF, IMPORT, INTERFACE, MAP, PACKAGE, RANGE, RETURN, SELECT, STRUCT, SWITCH, TYPE_, VAR); public static final TokenSet OPERATORS = TokenSet.create( EQ, ASSIGN, NOT_EQ, NOT, PLUS_PLUS, PLUS_ASSIGN, PLUS, MINUS_MINUS, MINUS_ASSIGN, MINUS, COND_OR, BIT_OR_ASSIGN, BIT_OR, BIT_CLEAR_ASSIGN, BIT_CLEAR, COND_AND, BIT_AND_ASSIGN, BIT_AND, SHIFT_LEFT_ASSIGN, SHIFT_LEFT, SEND_CHANNEL, LESS_OR_EQUAL, LESS, BIT_XOR_ASSIGN, BIT_XOR, MUL_ASSIGN, MUL, QUOTIENT_ASSIGN, QUOTIENT, REMAINDER_ASSIGN, REMAINDER, SHIFT_RIGHT_ASSIGN, SHIFT_RIGHT, GREATER_OR_EQUAL, GREATER, VAR_ASSIGN); @NotNull @Override public Lexer createLexer(Project project) { return new GoLexer(); } @NotNull @Override public PsiParser createParser(Project project) { return new GoParser(); } @NotNull @Override public IFileElementType getFileNodeType() { return GoFileElementType.INSTANCE; } @NotNull @Override public TokenSet getWhitespaceTokens() { return WHITESPACES; } @NotNull @Override public TokenSet getCommentTokens() { return COMMENTS; } @NotNull @Override public TokenSet getStringLiteralElements() { return STRING_LITERALS; } @NotNull @Override public PsiElement createElement(ASTNode node) { return Factory.createElement(node); } @NotNull @Override public PsiFile createFile(@NotNull FileViewProvider viewProvider) { return new GoFile(viewProvider); } @NotNull @Override public SpaceRequirements spaceExistanceTypeBetweenTokens(ASTNode left, ASTNode right) { return SpaceRequirements.MAY; } } ================================================ FILE: src/com/goide/GoProjectGenerator.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.facet.ui.ValidationResult; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.platform.DirectoryProjectGenerator; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoProjectGenerator implements DirectoryProjectGenerator { @Nls @NotNull @Override public String getName() { return GoConstants.GO; } @Nullable @Override public Object showGenerationSettings(VirtualFile baseDir) throws ProcessCanceledException { return null; } @Nullable @Override public Icon getLogo() { return GoIcons.ICON; } @Override public void generateProject(@NotNull Project project, @NotNull VirtualFile baseDir, @Nullable Object settings, @NotNull Module module) { } @NotNull @Override public ValidationResult validate(@NotNull String baseDirPath) { return ValidationResult.OK; } } ================================================ FILE: src/com/goide/UpdateComponent.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PermanentInstallationID; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.EditorFactoryAdapter; import com.intellij.openapi.editor.event.EditorFactoryEvent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.io.HttpRequests; import org.jdom.JDOMException; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.concurrent.TimeUnit; import static com.goide.util.GoUtil.getPlugin; public class UpdateComponent implements ApplicationComponent, Disposable { private static final Logger LOG = Logger.getInstance(UpdateComponent.class); private static final String KEY = "go.last.update.timestamp"; private final EditorFactoryAdapter myListener = new EditorFactoryAdapter() { @Override public void editorCreated(@NotNull EditorFactoryEvent event) { Document document = event.getEditor().getDocument(); VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null && file.getFileType() == GoFileType.INSTANCE) { checkForUpdates(); } } }; @Override public void initComponent() { if (!ApplicationManager.getApplication().isUnitTestMode()) { EditorFactory.getInstance().addEditorFactoryListener(myListener, this); } } private static void checkForUpdates() { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); long lastUpdate = propertiesComponent.getOrInitLong(KEY, 0); if (lastUpdate == 0 || System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)) { ApplicationManager.getApplication().executeOnPooledThread(() -> { try { String buildNumber = ApplicationInfo.getInstance().getBuild().asString(); IdeaPluginDescriptor plugin = getPlugin(); String pluginVersion = plugin.getVersion(); String pluginId = plugin.getPluginId().getIdString(); String os = URLEncoder.encode(SystemInfo.OS_NAME + " " + SystemInfo.OS_VERSION, CharsetToolkit.UTF8); String uid = PermanentInstallationID.get(); String url = "https://plugins.jetbrains.com/plugins/list" + "?pluginId=" + pluginId + "&build=" + buildNumber + "&pluginVersion=" + pluginVersion + "&os=" + os + "&uuid=" + uid; PropertiesComponent.getInstance().setValue(KEY, String.valueOf(System.currentTimeMillis())); HttpRequests.request(url).connect( request -> { try { JDOMUtil.load(request.getReader()); LOG.info((request.isSuccessful() ? "Successful" : "Unsuccessful") + " update: " + url); } catch (JDOMException e) { LOG.warn(e); } return null; } ); } catch (UnknownHostException ignored) { } catch (IOException e) { LOG.warn(e); } }); } } @Override public void disposeComponent() { } @NotNull @Override public String getComponentName() { return getClass().getName(); } @Override public void dispose() { disposeComponent(); } } ================================================ FILE: src/com/goide/actions/file/GoCreateFileAction.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.file; import com.goide.GoIcons; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.ide.actions.CreateFileFromTemplateDialog; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; public class GoCreateFileAction extends CreateFileFromTemplateAction implements DumbAware { public static final String FILE_TEMPLATE = "Go File"; public static final String APPLICATION_TEMPLATE = "Go Application"; private static final String NEW_GO_FILE = "New Go File"; private static final String DEFAULT_GO_TEMPLATE_PROPERTY = "DefaultGoTemplateProperty"; public GoCreateFileAction() { super(NEW_GO_FILE, "", GoIcons.ICON); } @Override protected void buildDialog(Project project, PsiDirectory directory, @NotNull CreateFileFromTemplateDialog.Builder builder) { builder.setTitle(NEW_GO_FILE) .addKind("Empty file", GoIcons.ICON, FILE_TEMPLATE) .addKind("Simple Application", GoIcons.ICON, APPLICATION_TEMPLATE); } @Nullable @Override protected String getDefaultTemplateProperty() { return DEFAULT_GO_TEMPLATE_PROPERTY; } @NotNull @Override protected String getActionName(PsiDirectory directory, String newName, String templateName) { return NEW_GO_FILE; } @Override protected void postProcess(PsiFile createdElement, String templateName, Map customProperties) { if (createdElement instanceof GoFile) { GoPackageClause packageClause = ((GoFile)createdElement).getPackage(); if (packageClause == null) { return; } Project project = createdElement.getProject(); Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor == null) { return; } VirtualFile virtualFile = createdElement.getContainingFile().getVirtualFile(); if (virtualFile == null) { return; } if (FileDocumentManager.getInstance().getDocument(virtualFile) == editor.getDocument()) { editor.getCaretModel().moveToOffset(packageClause.getTextRange().getEndOffset()); } } } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof GoCreateFileAction; } } ================================================ FILE: src/com/goide/actions/file/GoCreateFromTemplateHandler.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.file; import com.goide.GoConstants; import com.goide.GoFileType; import com.intellij.ide.fileTemplates.DefaultCreateFromTemplateHandler; import com.intellij.ide.fileTemplates.FileTemplate; import java.util.Map; public class GoCreateFromTemplateHandler extends DefaultCreateFromTemplateHandler { @Override public boolean handlesTemplate(FileTemplate template) { return template.isTemplateOfType(GoFileType.INSTANCE); } @Override public void prepareProperties(Map props) { Object name = props.get(FileTemplate.ATTRIBUTE_NAME); Object packageName = props.get(GoTemplatePropertiesProvider.GO_PACKAGE_NAME); if (name instanceof String && packageName instanceof String) { if (((String)name).endsWith(GoConstants.TEST_SUFFIX) || ((String)name).endsWith(GoConstants.TEST_SUFFIX_WITH_EXTENSION)) { props.put(GoTemplatePropertiesProvider.GO_PACKAGE_NAME_WITH_TEST_SUFFIX, packageName + GoConstants.TEST_SUFFIX); } } } } ================================================ FILE: src/com/goide/actions/file/GoTemplatePropertiesProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.file; import com.goide.util.GoUtil; import com.intellij.ide.fileTemplates.DefaultTemplatePropertiesProvider; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.psi.PsiDirectory; import java.util.Properties; public class GoTemplatePropertiesProvider implements DefaultTemplatePropertiesProvider { public static final String GO_PACKAGE_NAME = "GO_" + FileTemplate.ATTRIBUTE_PACKAGE_NAME; public static final String GO_PACKAGE_NAME_WITH_TEST_SUFFIX = GO_PACKAGE_NAME + "_WITH_TEST_SUFFIX"; @Override public void fillProperties(PsiDirectory directory, Properties props) { String packageForDirectory = GoUtil.suggestPackageForDirectory(directory); props.setProperty(GO_PACKAGE_NAME, packageForDirectory); props.setProperty(GO_PACKAGE_NAME_WITH_TEST_SUFFIX, packageForDirectory); } } ================================================ FILE: src/com/goide/actions/tool/GoDownloadableFileAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.GoConstants; import com.goide.codeInsight.imports.GoGetPackageFix; import com.goide.sdk.GoSdkUtil; import com.intellij.execution.ExecutionException; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; public abstract class GoDownloadableFileAction extends GoExternalToolsAction { private static final String GO_GET_LINK = "goGetLink"; @NotNull private final String myGoGetImportPath; @NotNull private final String myExecutableName; public GoDownloadableFileAction(@NotNull String executableName, @NotNull String goGetImportPath) { myExecutableName = executableName; myGoGetImportPath = goGetImportPath; } @Override protected boolean doSomething(@NotNull VirtualFile virtualFile, @Nullable Module module, @NotNull Project project, @NotNull String title) throws ExecutionException { VirtualFile executable = getExecutable(project, module); if (executable == null) { String message = "Can't find `" + myExecutableName + "` in GOPATH. Try to invoke go get " + myExecutableName + ""; NotificationListener listener = new MyNotificationListener(project, module); Notifications.Bus.notify(GoConstants.GO_NOTIFICATION_GROUP.createNotification(title, message, NotificationType.WARNING, listener), project); return false; } return super.doSomething(virtualFile, module, project, title); } @Nullable protected VirtualFile getExecutable(@NotNull Project project, @Nullable Module module) { return GoSdkUtil.findExecutableInGoPath(myExecutableName, project, module); } private class MyNotificationListener implements NotificationListener { private final Project myProject; private final Module myModule; private MyNotificationListener(@NotNull Project project, @Nullable Module module) { myProject = project; myModule = module; } @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String description = event.getDescription(); if (GO_GET_LINK.equals(description)) { GoGetPackageFix.applyFix(myProject, myModule, myGoGetImportPath, false); notification.expire(); } } } } } ================================================ FILE: src/com/goide/actions/tool/GoExternalToolsAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.GoConstants; import com.goide.GoFileType; import com.goide.sdk.GoSdkService; import com.goide.util.GoExecutor; import com.intellij.execution.ExecutionException; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.ExceptionUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoExternalToolsAction extends DumbAwareAction { private static final Logger LOG = Logger.getInstance(GoExternalToolsAction.class); private static void error(@NotNull String title, @NotNull Project project, @Nullable Exception ex) { String message = ex == null ? "" : ExceptionUtil.getUserStackTrace(ex, LOG); NotificationType type = NotificationType.ERROR; Notifications.Bus.notify(GoConstants.GO_EXECUTION_NOTIFICATION_GROUP.createNotification(title, message, type, null), project); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); Project project = e.getProject(); VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE); if (project == null || file == null || !file.isInLocalFileSystem() || !isAvailableOnFile(file)) { e.getPresentation().setEnabled(false); return; } Module module = ModuleUtilCore.findModuleForFile(file, project); e.getPresentation().setEnabled(GoSdkService.getInstance(project).isGoModule(module)); } protected boolean isAvailableOnFile(VirtualFile file) { return file.getFileType() == GoFileType.INSTANCE; } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); VirtualFile file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE); assert project != null; String title = StringUtil.notNullize(e.getPresentation().getText()); Module module = ModuleUtilCore.findModuleForFile(file, project); try { doSomething(file, module, project, title); } catch (ExecutionException ex) { error(title, project, ex); LOG.error(ex); } } protected boolean doSomething(@NotNull VirtualFile virtualFile, @Nullable Module module, @NotNull Project project, @NotNull String title) throws ExecutionException { return doSomething(virtualFile, module, project, title, false); } private boolean doSomething(@NotNull VirtualFile virtualFile, @Nullable Module module, @NotNull Project project, @NotNull String title, boolean withProgress) { //noinspection unchecked return doSomething(virtualFile, module, project, title, withProgress, Consumer.EMPTY_CONSUMER); } protected boolean doSomething(@NotNull VirtualFile virtualFile, @Nullable Module module, @NotNull Project project, @NotNull String title, boolean withProgress, @NotNull Consumer consumer) { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if (document != null) { FileDocumentManager.getInstance().saveDocument(document); } else { FileDocumentManager.getInstance().saveAllDocuments(); } createExecutor(project, module, title, virtualFile).executeWithProgress(withProgress, result -> { consumer.consume(result); VfsUtil.markDirtyAndRefresh(true, true, true, virtualFile); }); return true; } protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull VirtualFile virtualFile) { String filePath = virtualFile.getCanonicalPath(); assert filePath != null; return createExecutor(project, module, title, filePath); } @NotNull protected abstract GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull String filePath); } ================================================ FILE: src/com/goide/actions/tool/GoFmtCheckinFactory.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.psi.GoFile; import com.intellij.CommonBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.changes.CommitContext; import com.intellij.openapi.vcs.changes.CommitExecutor; import com.intellij.openapi.vcs.checkin.CheckinHandler; import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory; import com.intellij.openapi.vcs.ui.RefreshableOnComponent; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.PairConsumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.List; public class GoFmtCheckinFactory extends CheckinHandlerFactory { private static final String GO_FMT = "GO_FMT"; @Override @NotNull public CheckinHandler createHandler(@NotNull CheckinProjectPanel panel, @NotNull CommitContext commitContext) { return new CheckinHandler() { @Override public RefreshableOnComponent getBeforeCheckinConfigurationPanel() { JCheckBox checkBox = new JCheckBox("Go fmt"); return new RefreshableOnComponent() { @Override @NotNull public JComponent getComponent() { JPanel panel = new JPanel(new BorderLayout()); panel.add(checkBox, BorderLayout.WEST); return panel; } @Override public void refresh() { } @Override public void saveState() { PropertiesComponent.getInstance(panel.getProject()).setValue(GO_FMT, Boolean.toString(checkBox.isSelected())); } @Override public void restoreState() { checkBox.setSelected(enabled(panel)); } }; } @Override public ReturnResult beforeCheckin(@Nullable CommitExecutor executor, PairConsumer additionalDataConsumer) { if (enabled(panel)) { Ref success = Ref.create(true); FileDocumentManager.getInstance().saveAllDocuments(); for (PsiFile file : getPsiFiles()) { VirtualFile virtualFile = file.getVirtualFile(); new GoFmtFileAction().doSomething(virtualFile, ModuleUtilCore.findModuleForPsiElement(file), file.getProject(), "Go fmt", true, result -> { if (!result) success.set(false); }); } if (!success.get()) { return showErrorMessage(executor); } } return super.beforeCheckin(); } @NotNull private ReturnResult showErrorMessage(@Nullable CommitExecutor executor) { String[] buttons = new String[]{"&Details...", commitButtonMessage(executor, panel), CommonBundle.getCancelButtonText()}; int answer = Messages.showDialog(panel.getProject(), "GoFmt returned non-zero code on some of the files.
    " + "Would you like to commit anyway?\n", "Go Fmt", null, buttons, 0, 1, UIUtil.getWarningIcon()); if (answer == Messages.OK) { return ReturnResult.CLOSE_WINDOW; } if (answer == Messages.NO) { return ReturnResult.COMMIT; } return ReturnResult.CANCEL; } @NotNull private List getPsiFiles() { Collection files = panel.getVirtualFiles(); List psiFiles = ContainerUtil.newArrayList(); PsiManager manager = PsiManager.getInstance(panel.getProject()); for (VirtualFile file : files) { PsiFile psiFile = manager.findFile(file); if (psiFile instanceof GoFile) { psiFiles.add(psiFile); } } return psiFiles; } }; } @NotNull private static String commitButtonMessage(@Nullable CommitExecutor executor, @NotNull CheckinProjectPanel panel) { return StringUtil.trimEnd(executor != null ? executor.getActionText() : panel.getCommitActionName(), "..."); } private static boolean enabled(@NotNull CheckinProjectPanel panel) { return PropertiesComponent.getInstance(panel.getProject()).getBoolean(GO_FMT, false); } } ================================================ FILE: src/com/goide/actions/tool/GoFmtFileAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.util.GoExecutor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFmtFileAction extends GoExternalToolsAction { @Override @NotNull protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull String filePath) { return GoExecutor.in(project, module).withPresentableName(title).withParameters("fmt", filePath).showOutputOnError(); } } ================================================ FILE: src/com/goide/actions/tool/GoFmtProjectAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.goide.util.GoExecutor; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFmtProjectAction extends DumbAwareAction { @Override public void update(@NotNull AnActionEvent e) { Project project = e.getProject(); e.getPresentation().setEnabled(project != null && GoSdkService.getInstance(project).getSdkHomePath(null) != null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getProject(); assert project != null; FileDocumentManager.getInstance().saveAllDocuments(); for (Module module : GoSdkUtil.getGoModules(project)) { for (VirtualFile file : ModuleRootManager.getInstance(module).getContentRoots()) { fmt(project, module, "go fmt " + file.getPath(), file); } } } private static void fmt(@NotNull Project project, @Nullable Module module, @NotNull String presentation, @NotNull VirtualFile dir) { GoExecutor.in(project, module).withPresentableName(presentation).withWorkDirectory(dir.getPath()) .withParameters("fmt", "./...").showOutputOnError().executeWithProgress(false, result -> VfsUtil.markDirtyAndRefresh(true, true, true, dir)); } } ================================================ FILE: src/com/goide/actions/tool/GoImportsFileAction.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.util.GoExecutor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoImportsFileAction extends GoDownloadableFileAction { public GoImportsFileAction() { super("goimports", "golang.org/x/tools/cmd/goimports"); } @NotNull @Override protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull String filePath) { VirtualFile executable = getExecutable(project, module); assert executable != null; return GoExecutor.in(project, module).withExePath(executable.getPath()).withParameters("-w", filePath).showOutputOnError(); } } ================================================ FILE: src/com/goide/actions/tool/GoTypeFileAction.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.util.GoExecutor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoTypeFileAction extends GoDownloadableFileAction { public GoTypeFileAction() { super("gotype", "golang.org/x/tools/cmd/gotype"); } @Override protected boolean isAvailableOnFile(VirtualFile file) { return super.isAvailableOnFile(file) || file.isDirectory(); } @NotNull @Override protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull VirtualFile file) { return super.createExecutor(project, module, title, file.isDirectory() ? file : file.getParent()); } @NotNull @Override protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull String filePath) { VirtualFile executable = getExecutable(project, module); assert executable != null; return GoExecutor.in(project, module).withExePath(executable.getPath()).withParameters("-e", "-a", "-v", filePath ) .showNotifications(false, true).showOutputOnError(); } } ================================================ FILE: src/com/goide/actions/tool/GoVetFileAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions.tool; import com.goide.util.GoExecutor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoVetFileAction extends GoExternalToolsAction { @Override protected boolean isAvailableOnFile(VirtualFile file) { return super.isAvailableOnFile(file) || file.isDirectory(); } @Override @NotNull protected GoExecutor createExecutor(@NotNull Project project, @Nullable Module module, @NotNull String title, @NotNull String filePath) { return GoExecutor.in(project, module).withPresentableName(title).withParameters("tool", "vet", filePath) .showNotifications(false, true).showOutputOnError(); } } ================================================ FILE: src/com/goide/appengine/GoAppEngineExtension.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine; import com.goide.sdk.GoSdkService; import com.intellij.appengine.AppEngineExtension; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nullable; public class GoAppEngineExtension extends AppEngineExtension { @Override public boolean isAppEngineEnabled(@Nullable PsiElement context) { if (context != null) { // it's important to ask module on file, otherwise module won't be found for elements in libraries files [zolotov] Module module = ModuleUtilCore.findModuleForPsiElement(context.getContainingFile()); if (GoSdkService.getInstance(context.getProject()).isAppEngineSdk(module)) { return true; } } return false; } } ================================================ FILE: src/com/goide/appengine/GoAppEngineIcons.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine; import com.goide.GoIcons; import com.intellij.appengine.GoogleAppEngineIcons; import com.intellij.ui.LayeredIcon; import javax.swing.*; public interface GoAppEngineIcons { Icon ICON = new LayeredIcon(GoIcons.ICON, GoogleAppEngineIcons.AppEngineMark); } ================================================ FILE: src/com/goide/appengine/GoAppEngineLibraryPresentationProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSmallIDEsSdkService; import com.intellij.openapi.roots.libraries.DummyLibraryProperties; import com.intellij.openapi.roots.libraries.LibraryKind; import com.intellij.openapi.roots.libraries.LibraryPresentationProvider; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public class GoAppEngineLibraryPresentationProvider extends LibraryPresentationProvider { private static final LibraryKind KIND = LibraryKind.create("go_gae"); public GoAppEngineLibraryPresentationProvider() { super(KIND); } @Nullable @Override public Icon getIcon() { return GoAppEngineIcons.ICON; } @Nullable @Override public DummyLibraryProperties detect(@NotNull List classesRoots) { for (VirtualFile root : classesRoots) { if (GoSmallIDEsSdkService.isGoSdkLibRoot(root) && GoSdkService.isAppEngineSdkPath(GoSdkService.libraryRootToSdkPath(root))) { return DummyLibraryProperties.INSTANCE; } } return null; } } ================================================ FILE: src/com/goide/appengine/YamlFilesModificationTracker.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine; import com.goide.util.GoUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.vfs.*; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ObjectUtils; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class YamlFilesModificationTracker extends SimpleModificationTracker { public YamlFilesModificationTracker(@NotNull Project project) { VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override public void fileCreated(@NotNull VirtualFileEvent event) { handleEvent(event); } @Override public void fileDeleted(@NotNull VirtualFileEvent event) { handleEvent(event); } @Override public void fileMoved(@NotNull VirtualFileMoveEvent event) { handleEvent(event); } @Override public void fileCopied(@NotNull VirtualFileCopyEvent event) { handleEvent(event); } private void handleEvent(@NotNull VirtualFileEvent event) { if ("yaml".equals(PathUtil.getFileExtension(event.getFileName()))) { incModificationCount(); } } }, project); } public static YamlFilesModificationTracker getInstance(@NotNull Project project) { return ServiceManager.getService(project, YamlFilesModificationTracker.class); } @NotNull public static Collection getYamlFiles(@NotNull Project project, @Nullable Module module) { UserDataHolder dataHolder = ObjectUtils.notNull(module, project); return CachedValuesManager.getManager(project).getCachedValue(dataHolder, () -> { Collection yamlFiles = ApplicationManager.getApplication().runReadAction(new Computable>() { @Override public Collection compute() { return FilenameIndex.getAllFilesByExt(project, "yaml", GoUtil.moduleScopeWithoutLibraries(project, module)); } }); return CachedValueProvider.Result.create(yamlFiles, getInstance(project)); }); } } ================================================ FILE: src/com/goide/appengine/run/GoAppEngineRunConfiguration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine.run; import com.goide.runconfig.GoModuleBasedConfiguration; import com.goide.runconfig.GoRunConfigurationBase; import com.goide.sdk.GoSdkService; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.PathUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoAppEngineRunConfiguration extends GoRunConfigurationBase { private static final String HOST_NAME = "HOST"; private static final String PORT_NAME = "PORT"; private static final String ADMIN_PORT_NAME = "ADMIN_PORT"; private static final String CONFIG_FILE = "CONFIG"; @Nullable private String myHost; @Nullable private String myPort; @Nullable private String myAdminPort; @Nullable private String myConfigFile; public GoAppEngineRunConfiguration(@NotNull Project project, String name, @NotNull ConfigurationType configurationType) { super(name, new GoModuleBasedConfiguration(project), configurationType.getConfigurationFactories()[0]); } @Nullable public String getHost() { return myHost; } public void setHost(@Nullable String host) { myHost = host; } @Nullable public String getPort() { return myPort; } public void setPort(@Nullable String port) { myPort = port; } @Nullable public String getAdminPort() { return myAdminPort; } public void setAdminPort(@Nullable String adminPort) { myAdminPort = adminPort; } @Nullable public String getConfigFile() { return myConfigFile; } public void setConfigFile(@Nullable String configFile) { myConfigFile = configFile; } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); myHost = JDOMExternalizerUtil.getFirstChildValueAttribute(element, HOST_NAME); myPort = JDOMExternalizerUtil.getFirstChildValueAttribute(element, PORT_NAME); myAdminPort = JDOMExternalizerUtil.getFirstChildValueAttribute(element, ADMIN_PORT_NAME); myConfigFile = JDOMExternalizerUtil.getFirstChildValueAttribute(element, CONFIG_FILE); } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); addNonEmptyElement(element, HOST_NAME, myHost); addNonEmptyElement(element, PORT_NAME, myPort); addNonEmptyElement(element, ADMIN_PORT_NAME, myAdminPort); addNonEmptyElement(element, CONFIG_FILE, myConfigFile); } @Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); Module module = getConfigurationModule().getModule(); if (module != null) { if (!GoSdkService.getInstance(module.getProject()).isAppEngineSdk(module)) { throw new RuntimeConfigurationWarning("Go SDK is not specified for module '" + module.getName() + "'"); } } checkPortValue(myPort, "Invalid port"); checkPortValue(myAdminPort, "Invalid admin port"); if (myConfigFile != null && !"yaml".equals(PathUtil.getFileExtension(myConfigFile))) { throw new RuntimeConfigurationException("Config file is not YAML"); } } private static void checkPortValue(@Nullable String port, @NotNull String errorMessage) throws RuntimeConfigurationError { if (StringUtil.isNotEmpty(port)) { int intPort = StringUtil.parseInt(port, -1); if (intPort < 0 || intPort > Short.MAX_VALUE * 2) { throw new RuntimeConfigurationError(errorMessage); } } } @NotNull @Override public SettingsEditor getConfigurationEditor() { return new GoAppEngineRunConfigurationEditor(getProject()); } @NotNull @Override protected GoAppEngineRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module) { return new GoAppEngineRunningState(env, module, this); } } ================================================ FILE: src/com/goide/appengine/run/GoAppEngineRunConfigurationEditor.form ================================================
    ================================================ FILE: src/com/goide/appengine/run/GoAppEngineRunConfigurationEditor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine.run; import com.goide.appengine.YamlFilesModificationTracker; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.ui.GoCommonSettingsPanel; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.TextFieldWithHistoryWithBrowseButton; import com.intellij.ui.components.JBTextField; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class GoAppEngineRunConfigurationEditor extends SettingsEditor { private JPanel myComponent; private JBTextField myHostField; private JBTextField myPortField; private GoCommonSettingsPanel myCommonSettingsPanel; private JBTextField myAdminPortField; private TextFieldWithHistoryWithBrowseButton myConfigFileField; public GoAppEngineRunConfigurationEditor(@NotNull Project project) { super(null); initConfigFileField(project); myCommonSettingsPanel.init(project); } @Override protected void resetEditorFrom(@NotNull GoAppEngineRunConfiguration configuration) { myHostField.setText(StringUtil.notNullize(configuration.getHost())); myPortField.setText(StringUtil.notNullize(configuration.getPort())); myAdminPortField.setText(StringUtil.notNullize(configuration.getAdminPort())); myConfigFileField.getChildComponent().setText(StringUtil.notNullize(configuration.getConfigFile())); myCommonSettingsPanel.resetEditorFrom(configuration); } @Override protected void applyEditorTo(@NotNull GoAppEngineRunConfiguration configuration) throws ConfigurationException { configuration.setHost(StringUtil.nullize(myHostField.getText().trim())); configuration.setPort(StringUtil.nullize(myPortField.getText().trim())); configuration.setAdminPort(StringUtil.nullize(myAdminPortField.getText().trim())); configuration.setConfigFile(StringUtil.nullize(myConfigFileField.getText().trim())); myCommonSettingsPanel.applyEditorTo(configuration); } @NotNull @Override protected JComponent createEditor() { return myComponent; } @Override protected void disposeEditor() { myComponent.setVisible(false); } private void initConfigFileField(@NotNull Project project) { GoRunUtil.installFileChooser(project, myConfigFileField, false, false, file -> "yaml".equals(file.getExtension())); myConfigFileField.getChildComponent().setHistory(ContainerUtil.map2List( YamlFilesModificationTracker.getYamlFiles(project, null), VirtualFile::getPath)); } } ================================================ FILE: src/com/goide/appengine/run/GoAppEngineRunConfigurationType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine.run; import com.goide.appengine.GoAppEngineIcons; import com.goide.runconfig.GoConfigurationFactoryBase; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class GoAppEngineRunConfigurationType extends ConfigurationTypeBase { public GoAppEngineRunConfigurationType() { super("GoAppEngineRunConfiguration", "Go App Engine", "Go app engine web server runner", GoAppEngineIcons.ICON); addFactory(new GoConfigurationFactoryBase(this) { @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new GoAppEngineRunConfiguration(project, "Go App Engine", getInstance()); } }); } @NotNull public static GoAppEngineRunConfigurationType getInstance() { return Extensions.findExtension(CONFIGURATION_TYPE_EP, GoAppEngineRunConfigurationType.class); } } ================================================ FILE: src/com/goide/appengine/run/GoAppEngineRunningState.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.appengine.run; import com.goide.runconfig.GoRunningState; import com.goide.util.GoExecutor; import com.intellij.execution.ExecutionException; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; public class GoAppEngineRunningState extends GoRunningState { public GoAppEngineRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoAppEngineRunConfiguration configuration) { super(env, module, configuration); } @Override protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { executor.withParameters("serve"); executor.withParameterString(myConfiguration.getGoToolParams()); String host = myConfiguration.getHost(); String port = myConfiguration.getPort(); String adminPort = myConfiguration.getAdminPort(); if (StringUtil.isNotEmpty(host)) { executor.withParameters("-host", host); } if (StringUtil.isNotEmpty(port)) { executor.withParameters("-port", port); } if (StringUtil.isNotEmpty(adminPort)) { executor.withParameters("-admin_port", adminPort); } executor.withParameters(StringUtil.notNullize(myConfiguration.getConfigFile(), ".")); return executor; } } ================================================ FILE: src/com/goide/codeInsight/GoExpressionTypeProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight; import com.goide.psi.GoTopLevelDeclaration; import com.goide.psi.GoType; import com.goide.psi.GoTypeOwner; import com.intellij.lang.ExpressionTypeProvider; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.SyntaxTraverser; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoExpressionTypeProvider extends ExpressionTypeProvider { @NotNull @Override public String getInformationHint(@NotNull GoTypeOwner element) { GoType type = element.getGoType(null); return StringUtil.escapeXml(StringUtil.notNullize(type != null ? type.getText() : null, "")); } @NotNull @Override public String getErrorHint() { return "Selection doesn't contain a Go expression"; } @NotNull @Override public List getExpressionsAt(@NotNull PsiElement at) { if (at instanceof PsiWhiteSpace && at.textMatches("\n")) { at = PsiTreeUtil.prevLeaf(at); } return SyntaxTraverser.psiApi().parents(at).takeWhile(Conditions.notInstanceOf(GoTopLevelDeclaration.class)) .filter(GoTypeOwner.class).toList(); } } ================================================ FILE: src/com/goide/codeInsight/imports/GoAutoImportConfigurable.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.project.GoExcludedPathsSettings; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.*; import com.intellij.ui.components.JBList; import com.intellij.util.ui.FormBuilder; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Arrays; public class GoAutoImportConfigurable implements SearchableConfigurable { private JCheckBox myCbShowImportPopup; private JCheckBox myCbAddUnambiguousImports; private JBList myExcludePackagesList; private DefaultListModel myExcludePackagesModel; @NotNull private final GoCodeInsightSettings myCodeInsightSettings; @NotNull private final GoExcludedPathsSettings myExcludedSettings; private final boolean myIsDefaultProject; private final boolean myIsDialog; public GoAutoImportConfigurable(@NotNull Project project, boolean dialogMode) { myCodeInsightSettings = GoCodeInsightSettings.getInstance(); myExcludedSettings = GoExcludedPathsSettings.getInstance(project); myIsDefaultProject = project.isDefault(); myIsDialog = dialogMode; } @Nullable @Override public JComponent createComponent() { FormBuilder builder = FormBuilder.createFormBuilder(); myCbShowImportPopup = new JCheckBox(ApplicationBundle.message("checkbox.show.import.popup")); myCbAddUnambiguousImports = new JCheckBox(ApplicationBundle.message("checkbox.add.unambiguous.imports.on.the.fly")); builder.addComponent(myCbShowImportPopup); builder.addComponent(myCbAddUnambiguousImports); myExcludePackagesList = new JBList(); JComponent excludedPanel = new JPanel(new BorderLayout()); excludedPanel.add(ToolbarDecorator.createDecorator(myExcludePackagesList) .setAddAction(new AddImportExclusionAction()).disableUpDownActions().createPanel(), BorderLayout.CENTER); excludedPanel.setBorder(IdeBorderFactory.createTitledBorder(ApplicationBundle.message("exclude.from.completion.group"), true)); if (!myIsDefaultProject) { builder.addComponent(excludedPanel); } JPanel result = new JPanel(new BorderLayout()); result.add(builder.getPanel(), BorderLayout.NORTH); if (myIsDialog) result.setPreferredSize(new Dimension(300, -1)); return result; } public void focusList() { myExcludePackagesList.setSelectedIndex(0); myExcludePackagesList.requestFocus(); } private String[] getExcludedPackages() { String[] excludedPackages = new String[myExcludePackagesModel.size()]; for (int i = 0; i < myExcludePackagesModel.size(); i++) { excludedPackages[i] = (String)myExcludePackagesModel.elementAt(i); } Arrays.sort(excludedPackages); return excludedPackages; } @Override public boolean isModified() { return myCodeInsightSettings.isShowImportPopup() != myCbShowImportPopup.isSelected() || myCodeInsightSettings.isAddUnambiguousImportsOnTheFly() != myCbAddUnambiguousImports.isSelected() || !Arrays.equals(getExcludedPackages(), myExcludedSettings.getExcludedPackages()); } @Override public void apply() throws ConfigurationException { myCodeInsightSettings.setShowImportPopup(myCbShowImportPopup.isSelected()); myCodeInsightSettings.setAddUnambiguousImportsOnTheFly(myCbAddUnambiguousImports.isSelected()); myExcludedSettings.setExcludedPackages(getExcludedPackages()); } @Override public void reset() { myCbShowImportPopup.setSelected(myCodeInsightSettings.isShowImportPopup()); myCbAddUnambiguousImports.setSelected(myCodeInsightSettings.isAddUnambiguousImportsOnTheFly()); myExcludePackagesModel = new DefaultListModel(); for (String name : myExcludedSettings.getExcludedPackages()) { myExcludePackagesModel.add(myExcludePackagesModel.size(), name); } myExcludePackagesList.setModel(myExcludePackagesModel); } @NotNull @Override public String getId() { return "go.autoimport"; } @Nullable @Override public Runnable enableSearch(String option) { return null; } @Nls @Override public String getDisplayName() { return "Auto Import"; } @Nullable @Override public String getHelpTopic() { return null; } @Override public void disposeUIResources() { UIUtil.dispose(myCbShowImportPopup); UIUtil.dispose(myCbAddUnambiguousImports); UIUtil.dispose(myExcludePackagesList); myCbShowImportPopup = null; myCbAddUnambiguousImports = null; myExcludePackagesList = null; myExcludePackagesModel.removeAllElements(); myExcludePackagesModel = null; } private class AddImportExclusionAction implements AnActionButtonRunnable { @Override public void run(AnActionButton button) { String packageName = Messages.showInputDialog("Enter the import path to exclude from auto-import and completion:", "Exclude Import Path", Messages.getWarningIcon()); addExcludedPackage(packageName); } private void addExcludedPackage(@Nullable String packageName) { if (StringUtil.isEmpty(packageName)) return; int index = -Arrays.binarySearch(myExcludePackagesModel.toArray(), packageName) - 1; if (index >= 0) { myExcludePackagesModel.add(index, packageName); ScrollingUtil.ensureIndexIsVisible(myExcludePackagesList, index, 0); } myExcludePackagesList.clearSelection(); myExcludePackagesList.setSelectedValue(packageName, true); myExcludePackagesList.requestFocus(); } } } ================================================ FILE: src/com/goide/codeInsight/imports/GoCodeInsightSettings.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.GoConstants; import com.intellij.openapi.components.*; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.Nullable; @State( name = GoConstants.GO, storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/editor.codeinsight.xml") ) public class GoCodeInsightSettings implements PersistentStateComponent { private boolean myShowImportPopup = true; private boolean myAddUnambiguousImportsOnTheFly = true; public static GoCodeInsightSettings getInstance() { return ServiceManager.getService(GoCodeInsightSettings.class); } @Nullable @Override public GoCodeInsightSettings getState() { return this; } @Override public void loadState(GoCodeInsightSettings state) { XmlSerializerUtil.copyBean(state, this); } public boolean isShowImportPopup() { return myShowImportPopup; } public void setShowImportPopup(boolean showImportPopup) { myShowImportPopup = showImportPopup; } public boolean isAddUnambiguousImportsOnTheFly() { return myAddUnambiguousImportsOnTheFly; } public void setAddUnambiguousImportsOnTheFly(boolean addUnambiguousImportsOnTheFly) { myAddUnambiguousImportsOnTheFly = addUnambiguousImportsOnTheFly; } } ================================================ FILE: src/com/goide/codeInsight/imports/GoExcludePathLookupActionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.project.GoExcludedPathsSettings; import com.goide.psi.GoFile; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupActionProvider; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementAction; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoExcludePathLookupActionProvider implements LookupActionProvider { @Override public void fillActions(LookupElement element, Lookup lookup, Consumer consumer) { PsiElement psiElement = element.getPsiElement(); PsiFile file = psiElement != null && psiElement.isValid() ? psiElement.getContainingFile() : null; String importPath = file instanceof GoFile ? ((GoFile)file).getImportPath(false) : null; if (importPath != null) { Project project = psiElement.getProject(); for (String path : getPaths(importPath)) { consumer.consume(new ExcludePathAction(project, path)); } consumer.consume(new EditExcludedAction(project)); } } private static List getPaths(String importPath) { List result = ContainerUtil.newArrayList(importPath); int i; while ((i = importPath.lastIndexOf('/')) > 0) { importPath = importPath.substring(0, i); result.add(importPath); } return result; } private static class EditExcludedAction extends LookupElementAction { @NotNull Project myProject; protected EditExcludedAction(@NotNull Project project) { super(AllIcons.Actions.Edit, "Edit auto import settings"); myProject = project; } @Override public Result performLookupAction() { ApplicationManager.getApplication().invokeLater(() -> { GoAutoImportConfigurable configurable = new GoAutoImportConfigurable(myProject, true); ShowSettingsUtil.getInstance().editConfigurable(myProject, configurable, configurable::focusList); }); return Result.HIDE_LOOKUP; } } private static class ExcludePathAction extends LookupElementAction { private Project myProject; private String myImportPath; protected ExcludePathAction(@NotNull Project project, @NotNull String importPath) { super(AllIcons.Actions.Exclude, "Exclude '" + importPath + "'"); myProject = project; myImportPath = importPath; } @Override public Result performLookupAction() { GoExcludedPathsSettings.getInstance(myProject).excludePath(myImportPath); return Result.HIDE_LOOKUP; } } } ================================================ FILE: src/com/goide/codeInsight/imports/GoGetPackageFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.sdk.GoSdkService; import com.goide.util.GoExecutor; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiElement; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoGetPackageFix extends LocalQuickFixBase implements HighPriorityAction { @NotNull private final String myPackage; public GoGetPackageFix(@NotNull String packageName) { super("go get -t " + packageName + "/...", "go get"); myPackage = packageName; } public static void applyFix(@NotNull Project project, @Nullable Module module, @NotNull String packageName, boolean startInBackground) { String sdkPath = GoSdkService.getInstance(project).getSdkHomePath(module); if (StringUtil.isEmpty(sdkPath)) return; CommandProcessor.getInstance().runUndoTransparentAction(() -> { Consumer consumer = aBoolean -> VirtualFileManager.getInstance().asyncRefresh(null); GoExecutor.in(project, module).withPresentableName("go get -t " + packageName + "/...") .withParameters("get", "-t", packageName+"/...").showNotifications(false, true).showOutputOnError() .executeWithProgress(!startInBackground, consumer); }); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element != null) { applyFix(project, ModuleUtilCore.findModuleForPsiElement(element.getContainingFile()), myPackage, true); } } } ================================================ FILE: src/com/goide/codeInsight/imports/GoImportOptimizer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.psi.impl.GoReferenceBase; import com.intellij.lang.ImportOptimizer; import com.intellij.openapi.editor.Document; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class GoImportOptimizer implements ImportOptimizer { @Override public boolean supports(PsiFile file) { return file instanceof GoFile; } @NotNull @Override public Runnable processFile(@NotNull PsiFile file) { if (!(file instanceof GoFile)) { return EmptyRunnable.getInstance(); } MultiMap importMap = ((GoFile)file).getImportMap(); Set importEntriesToDelete = ContainerUtil.newLinkedHashSet(); Set importIdentifiersToDelete = findRedundantImportIdentifiers(importMap); importEntriesToDelete.addAll(findDuplicatedEntries(importMap)); importEntriesToDelete.addAll(filterUnusedImports(file, importMap).values()); if (importEntriesToDelete.isEmpty() && importIdentifiersToDelete.isEmpty()) { return EmptyRunnable.getInstance(); } return new CollectingInfoRunnable() { @Nullable @Override public String getUserNotificationInfo() { int entriesToDelete = importEntriesToDelete.size(); int identifiersToDelete = importIdentifiersToDelete.size(); String result = ""; if (entriesToDelete > 0) { result = "Removed " + entriesToDelete + " import" + (entriesToDelete > 1 ? "s" : ""); } if (identifiersToDelete > 0) { result += result.isEmpty() ? "Removed " : " and "; result += identifiersToDelete + " alias" + (identifiersToDelete > 1 ? "es" : ""); } return StringUtil.nullize(result); } @Override public void run() { if (!importEntriesToDelete.isEmpty() || !importIdentifiersToDelete.isEmpty()) { PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject()); Document document = manager.getDocument(file); if (document != null) { manager.commitDocument(document); } } for (PsiElement importEntry : importEntriesToDelete) { if (importEntry != null && importEntry.isValid()) { deleteImportSpec(getImportSpec(importEntry)); } } for (PsiElement identifier : importIdentifiersToDelete) { if (identifier != null && identifier.isValid()) { identifier.delete(); } } } }; } @NotNull public static Set findRedundantImportIdentifiers(@NotNull MultiMap importMap) { Set importIdentifiersToDelete = ContainerUtil.newLinkedHashSet(); for (PsiElement importEntry : importMap.values()) { GoImportSpec importSpec = getImportSpec(importEntry); if (importSpec != null) { String localPackageName = importSpec.getLocalPackageName(); if (!StringUtil.isEmpty(localPackageName)) { if (Comparing.equal(importSpec.getAlias(), localPackageName)) { importIdentifiersToDelete.add(importSpec.getIdentifier()); } } } } return importIdentifiersToDelete; } public static MultiMap filterUnusedImports(@NotNull PsiFile file, @NotNull MultiMap importMap) { MultiMap result = MultiMap.create(); result.putAllValues(importMap); result.remove("_"); // imports for side effects are always used Collection implicitImports = ContainerUtil.newArrayList(result.get(".")); for (GoImportSpec importEntry : implicitImports) { GoImportSpec spec = getImportSpec(importEntry); if (spec != null && spec.isDot() && hasImportUsers(spec)) { result.remove(".", importEntry); } } file.accept(new GoRecursiveVisitor() { @Override public void visitTypeReferenceExpression(@NotNull GoTypeReferenceExpression o) { GoTypeReferenceExpression lastQualifier = o.getQualifier(); if (lastQualifier != null) { GoTypeReferenceExpression previousQualifier; while ((previousQualifier = lastQualifier.getQualifier()) != null) { lastQualifier = previousQualifier; } markAsUsed(lastQualifier.getIdentifier(), lastQualifier.getReference()); } } @Override public void visitReferenceExpression(@NotNull GoReferenceExpression o) { GoReferenceExpression lastQualifier = o.getQualifier(); if (lastQualifier != null) { GoReferenceExpression previousQualifier; while ((previousQualifier = lastQualifier.getQualifier()) != null) { lastQualifier = previousQualifier; } markAsUsed(lastQualifier.getIdentifier(), lastQualifier.getReference()); } } private void markAsUsed(@NotNull PsiElement qualifier, @NotNull PsiReference reference) { String qualifierText = qualifier.getText(); if (!result.containsKey(qualifierText)) { // already marked return; } PsiElement resolve = reference.resolve(); if (!(resolve instanceof PsiDirectory || resolve instanceof GoImportSpec || resolve instanceof PsiDirectoryContainer)) { return; } Collection qualifiersToDelete = ContainerUtil.newHashSet(); for (GoImportSpec spec : result.get(qualifierText)) { for (Map.Entry> entry : result.entrySet()) { for (GoImportSpec importSpec : entry.getValue()) { if (importSpec == spec) { qualifiersToDelete.add(entry.getKey()); } } } } for (String qualifierToDelete : qualifiersToDelete) { result.remove(qualifierToDelete); } } }); return result; } private static boolean hasImportUsers(@NotNull GoImportSpec spec) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (spec) { List list = spec.getUserData(GoReferenceBase.IMPORT_USERS); if (list != null) { for (PsiElement e : list) { if (e.isValid()) { return true; } ProgressManager.checkCanceled(); } } } return false; } @NotNull public static Set findDuplicatedEntries(@NotNull MultiMap importMap) { Set duplicatedEntries = ContainerUtil.newLinkedHashSet(); for (Map.Entry> imports : importMap.entrySet()) { Collection importsWithSameName = imports.getValue(); if (importsWithSameName.size() > 1) { MultiMap importsWithSameString = collectImportsWithSameString(importsWithSameName); for (Map.Entry> importWithSameString : importsWithSameString.entrySet()) { List duplicates = ContainerUtil.newArrayList(importWithSameString.getValue()); if (duplicates.size() > 1) { duplicatedEntries.addAll(duplicates.subList(1, duplicates.size())); } } } } return duplicatedEntries; } private static void deleteImportSpec(@Nullable GoImportSpec importSpec) { GoImportDeclaration importDeclaration = PsiTreeUtil.getParentOfType(importSpec, GoImportDeclaration.class); if (importSpec != null && importDeclaration != null) { PsiElement startElementToDelete = importSpec; PsiElement endElementToDelete = importSpec; if (importDeclaration.getImportSpecList().size() == 1) { startElementToDelete = importDeclaration; endElementToDelete = importDeclaration; PsiElement nextSibling = endElementToDelete.getNextSibling(); if (nextSibling != null && nextSibling.getNode().getElementType() == GoTypes.SEMICOLON) { endElementToDelete = nextSibling; } } // todo: delete after proper formatter implementation PsiElement nextSibling = endElementToDelete.getNextSibling(); if (nextSibling instanceof PsiWhiteSpace && nextSibling.textContains('\n')) { endElementToDelete = nextSibling; } startElementToDelete.getParent().deleteChildRange(startElementToDelete, endElementToDelete); } } @NotNull private static MultiMap collectImportsWithSameString(@NotNull Collection importsWithSameName) { MultiMap importsWithSameString = MultiMap.create(); for (PsiElement duplicateCandidate : importsWithSameName) { GoImportSpec importSpec = getImportSpec(duplicateCandidate); if (importSpec != null) { importsWithSameString.putValue(importSpec.getPath(), importSpec); } } return importsWithSameString; } @Nullable public static GoImportSpec getImportSpec(@NotNull PsiElement importEntry) { return PsiTreeUtil.getNonStrictParentOfType(importEntry, GoImportSpec.class); } } ================================================ FILE: src/com/goide/codeInsight/imports/GoImportPackageQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.GoIcons; import com.goide.completion.GoCompletionUtil; import com.goide.project.GoVendoringUtil; import com.goide.psi.GoFile; import com.goide.psi.GoReferenceExpression; import com.goide.psi.GoTypeReferenceExpression; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoReference; import com.goide.psi.impl.GoTypeReference; import com.goide.runconfig.testing.GoTestFinder; import com.goide.stubs.index.GoPackagesIndex; import com.goide.util.GoUtil; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.daemon.impl.DaemonListeners; import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.HintAction; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBList; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import static com.intellij.util.containers.ContainerUtil.*; public class GoImportPackageQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement implements HintAction, HighPriorityAction { @NotNull private final String myPackageName; @Nullable private List myPackagesToImport; public GoImportPackageQuickFix(@NotNull PsiElement element, @NotNull String importPath) { super(element); myPackageName = ""; myPackagesToImport = Collections.singletonList(importPath); } public GoImportPackageQuickFix(@NotNull PsiReference reference) { super(reference.getElement()); myPackageName = reference.getCanonicalText(); } @Nullable public PsiReference getReference(PsiElement element) { if (element != null && element.isValid()) { for (PsiReference reference : element.getReferences()) { if (isSupportedReference(reference)) { return reference; } } } return null; } private static boolean isSupportedReference(@Nullable PsiReference reference) { return reference instanceof GoReference || reference instanceof GoTypeReference; } @Override public boolean showHint(@NotNull Editor editor) { return doAutoImportOrShowHint(editor, true); } @NotNull @Override public String getText() { PsiElement element = getStartElement(); if (element != null) { return "Import " + getText(getImportPathVariantsToImport(element)); } return "Import package"; } @NotNull private static String getText(@NotNull Collection packagesToImport) { return getFirstItem(packagesToImport, "") + "? " + (packagesToImport.size() > 1 ? "(multiple choices...) " : ""); } @NotNull @Override public String getFamilyName() { return "Import package"; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; perform(getImportPathVariantsToImport(startElement), file, editor); } @Override public boolean isAvailable(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { PsiReference reference = getReference(startElement); return file instanceof GoFile && file.getManager().isInProject(file) && reference != null && reference.resolve() == null && !getImportPathVariantsToImport(startElement).isEmpty() && notQualified(startElement); } private static boolean notQualified(@Nullable PsiElement startElement) { return startElement instanceof GoReferenceExpression && ((GoReferenceExpression)startElement).getQualifier() == null || startElement instanceof GoTypeReferenceExpression && ((GoTypeReferenceExpression)startElement).getQualifier() == null; } @NotNull private List getImportPathVariantsToImport(@NotNull PsiElement element) { if (myPackagesToImport == null) { myPackagesToImport = getImportPathVariantsToImport(myPackageName, element); } return myPackagesToImport; } @NotNull public static List getImportPathVariantsToImport(@NotNull String packageName, @NotNull PsiElement context) { PsiFile contextFile = context.getContainingFile(); Set imported = contextFile instanceof GoFile ? ((GoFile)contextFile).getImportedPackagesMap().keySet() : Collections.emptySet(); Project project = context.getProject(); PsiDirectory parentDirectory = contextFile != null ? contextFile.getParent() : null; String testTargetPackage = GoTestFinder.getTestTargetPackage(contextFile); Module module = contextFile != null ? ModuleUtilCore.findModuleForPsiElement(contextFile) : null; boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module); GlobalSearchScope scope = GoUtil.goPathResolveScope(context); Collection packages = StubIndex.getElements(GoPackagesIndex.KEY, packageName, project, scope, GoFile.class); return sorted(skipNulls(map2Set( packages, file -> { if (parentDirectory != null && parentDirectory.isEquivalentTo(file.getParent())) { if (testTargetPackage == null || !testTargetPackage.equals(file.getPackageName())) { return null; } } if (!GoPsiImplUtil.canBeAutoImported(file, false, module)) { return null; } String importPath = file.getImportPath(vendoringEnabled); return !imported.contains(importPath) ? importPath : null; } )), new MyImportsComparator(context, vendoringEnabled)); } public boolean doAutoImportOrShowHint(@NotNull Editor editor, boolean showHint) { PsiElement element = getStartElement(); if (element == null || !element.isValid()) return false; PsiReference reference = getReference(element); if (reference == null || reference.resolve() != null) return false; List packagesToImport = getImportPathVariantsToImport(element); if (packagesToImport.isEmpty()) { return false; } PsiFile file = element.getContainingFile(); String firstPackageToImport = getFirstItem(packagesToImport); // autoimport on trying to fix if (packagesToImport.size() == 1) { if (GoCodeInsightSettings.getInstance().isAddUnambiguousImportsOnTheFly() && !LaterInvocator.isInModalContext() && (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(file))) { CommandProcessor.getInstance().runUndoTransparentAction(() -> perform(file, firstPackageToImport)); return true; } } // show hint on failed autoimport if (showHint) { if (ApplicationManager.getApplication().isUnitTestMode()) return false; if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false; if (!GoCodeInsightSettings.getInstance().isShowImportPopup()) return false; TextRange referenceRange = reference.getRangeInElement().shiftRight(element.getTextRange().getStartOffset()); HintManager.getInstance().showQuestionHint( editor, ShowAutoImportPass.getMessage(packagesToImport.size() > 1, getFirstItem(packagesToImport)), referenceRange.getStartOffset(), referenceRange.getEndOffset(), () -> { if (file.isValid() && !editor.isDisposed()) { perform(packagesToImport, file, editor); } return true; } ); return true; } return false; } private void perform(@NotNull List packagesToImport, @NotNull PsiFile file, @Nullable Editor editor) { LOG.assertTrue(editor != null || packagesToImport.size() == 1, "Cannot invoke fix with ambiguous imports on null editor"); if (packagesToImport.size() > 1 && editor != null) { JBList list = new JBList(packagesToImport); list.installCellRenderer(o -> { JBLabel label = new JBLabel(o.toString(), GoIcons.PACKAGE, SwingConstants.LEFT); label.setBorder(IdeBorderFactory.createEmptyBorder(2, 4, 2, 4)); return label; }); PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list).setRequestFocus(true) .setTitle("Package to import") .setItemChoosenCallback( () -> { int i = list.getSelectedIndex(); if (i < 0) return; perform(file, packagesToImport.get(i)); }) .setFilteringEnabled(o -> o instanceof String ? (String)o : o.toString()); JBPopup popup = builder.createPopup(); builder.getScrollPane().setBorder(null); builder.getScrollPane().setViewportBorder(null); popup.showInBestPositionFor(editor); } else if (packagesToImport.size() == 1) { perform(file, getFirstItem(packagesToImport)); } else { String packages = StringUtil.join(packagesToImport, ","); throw new IncorrectOperationException("Cannot invoke fix with ambiguous imports on editor ()" + editor + ". Packages: " + packages); } } private void perform(@NotNull PsiFile file, @Nullable String pathToImport) { if (file instanceof GoFile && pathToImport != null) { Project project = file.getProject(); CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> { if (!isAvailable()) return; if (((GoFile)file).getImportedPackagesMap().containsKey(pathToImport)) return; ((GoFile)file).addImport(pathToImport, null); }), "Add import", null); } } private static class MyImportsComparator implements Comparator { @Nullable private final String myContextImportPath; public MyImportsComparator(@Nullable PsiElement context, boolean vendoringEnabled) { myContextImportPath = GoCompletionUtil.getContextImportPath(context, vendoringEnabled); } @Override public int compare(@NotNull String s1, @NotNull String s2) { int result = Comparing.compare(GoCompletionUtil.calculatePackagePriority(s2, myContextImportPath), GoCompletionUtil.calculatePackagePriority(s1, myContextImportPath)); return result != 0 ? result : Comparing.compare(s1, s2); } } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoBracesUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoStatement; import com.goide.psi.impl.GoStatementImpl; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; public class GoBracesUnwrapper extends GoUnwrapper { public GoBracesUnwrapper() { super("Unwrap braces"); } @Override public boolean isApplicableTo(PsiElement e) { return e.getClass().equals(GoStatementImpl.class) && ((GoStatement)e).getBlock() != null; } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { context.extractFromBlock(((GoStatement)element).getBlock(), element); context.delete(element); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoElseRemover.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; public class GoElseRemover extends GoElseUnwrapperBase { public GoElseRemover() { super("Remove else"); } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { context.delete(element); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoElseUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoElseStatement; import com.goide.psi.GoIfStatement; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; public class GoElseUnwrapper extends GoElseUnwrapperBase { public GoElseUnwrapper() { super("Unwrap else"); } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { GoElseStatement elseStatement = (GoElseStatement)element; GoIfStatement elseIf = elseStatement.getIfStatement(); context.extractNewLine(elseStatement); if (elseIf != null) { context.extractElement(elseIf, elseStatement); } context.extractFromBlock(elseStatement.getBlock(), elseStatement); context.delete(elseStatement); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoElseUnwrapperBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoElseStatement; import com.goide.psi.GoIfStatement; import com.intellij.psi.PsiElement; import java.util.Set; public abstract class GoElseUnwrapperBase extends GoUnwrapper { public GoElseUnwrapperBase(String description) { super(description); } @Override public void collectElementsToIgnore(PsiElement element, Set result) { PsiElement parent = element.getParent(); if (parent instanceof GoIfStatement) { result.add(parent); } } @Override public boolean isApplicableTo(PsiElement e) { return e instanceof GoElseStatement; } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoForUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoForClause; import com.goide.psi.GoForStatement; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; public class GoForUnwrapper extends GoUnwrapper { public GoForUnwrapper() { super("Unwrap for"); } @Override public boolean isApplicableTo(PsiElement e) { return e instanceof GoForStatement; } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { GoForStatement forStatement = (GoForStatement)element; GoForClause forClause = forStatement.getForClause(); if (forClause != null) { context.extractElement(ContainerUtil.getFirstItem(forClause.getStatementList()), forStatement); } context.extractFromBlock(forStatement.getBlock(), forStatement); context.delete(forStatement); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoFunctionArgumentUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoArgumentList; import com.goide.psi.GoCallExpr; import com.goide.psi.GoExpression; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import java.util.List; public class GoFunctionArgumentUnwrapper extends GoUnwrapper { public GoFunctionArgumentUnwrapper() { super("Unwrap argument"); } @Override public boolean isApplicableTo(PsiElement e) { return e instanceof GoExpression && e.getParent() instanceof GoArgumentList && e.getParent().getParent() instanceof GoCallExpr; } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { PsiElement parent = element.getParent(); GoCallExpr call = parent != null ? ObjectUtils.tryCast(parent.getParent(), GoCallExpr.class) : null; if (call != null) { context.extractElement(element, call); context.delete(call); } } @Override public String getDescription(PsiElement e) { String text = e.getText(); if (text.length() > 20) text = text.substring(0, 17) + "..."; return "Unwrap " + text; } @Override public PsiElement collectAffectedElements(PsiElement e, List toExtract) { super.collectAffectedElements(e, toExtract); return e.getParent().getParent(); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoIfUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoElseStatement; import com.goide.psi.GoIfStatement; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; public class GoIfUnwrapper extends GoUnwrapper { public GoIfUnwrapper() { super("Unwrap if"); } @Override public boolean isApplicableTo(PsiElement e) { return e instanceof GoIfStatement && !(e.getParent() instanceof GoElseStatement); } @Override protected void doUnwrap(PsiElement element, Context context) throws IncorrectOperationException { GoIfStatement ifStatement = (GoIfStatement)element; context.extractFromBlock(ifStatement.getBlock(), ifStatement); context.delete(ifStatement); } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoUnwrapDescriptor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.intellij.codeInsight.unwrap.UnwrapDescriptorBase; import com.intellij.codeInsight.unwrap.Unwrapper; public class GoUnwrapDescriptor extends UnwrapDescriptorBase { @Override protected Unwrapper[] createUnwrappers() { return new Unwrapper[]{ new GoElseRemover(), new GoElseUnwrapper(), new GoIfUnwrapper(), new GoForUnwrapper(), new GoBracesUnwrapper(), new GoFunctionArgumentUnwrapper() }; } } ================================================ FILE: src/com/goide/codeInsight/unwrap/GoUnwrapper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.psi.GoBlock; import com.goide.psi.GoStatement; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInsight.unwrap.AbstractUnwrapper; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoUnwrapper extends AbstractUnwrapper { protected GoUnwrapper(String description) { super(description); } @Override protected Context createContext() { return new Context(); } protected static class Context extends AbstractUnwrapper.AbstractContext { public void extractNewLine(PsiElement from) { PsiElement newLine = GoElementFactory.createNewLine(from.getProject()); if (myIsEffective) { newLine = from.getParent().addBefore(newLine, from); } if (newLine != null) { addElementToExtract(newLine); } } public void extractFromBlock(@Nullable GoBlock block, @NotNull PsiElement from) { if (block != null) { for (GoStatement statement : block.getStatementList()) { extractElement(statement, from); } } } @Override public void addElementToExtract(PsiElement e) { super.addElementToExtract(e); CodeEditUtil.markToReformat(e.getNode(), true); } @Override protected boolean isWhiteSpace(PsiElement element) { return element instanceof PsiWhiteSpace; } } } ================================================ FILE: src/com/goide/completion/AddBracketsInsertHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class AddBracketsInsertHandler extends ParenthesesInsertHandler { @Override protected boolean placeCaretInsideParentheses(InsertionContext context, LookupElement element) { return true; } @Override public void handleInsert(@NotNull InsertionContext context, LookupElement item) { Editor editor = context.getEditor(); Document document = editor.getDocument(); context.commitDocument(); PsiElement element = findNextToken(context); char completionChar = context.getCompletionChar(); boolean putCaretInside = completionChar == '[' || placeCaretInsideParentheses(context, item); if (completionChar == '[') { context.setAddCompletionChar(false); } int tail; if (isToken(element, "[")) { tail = element.getTextRange().getStartOffset(); if (completionChar != '[' && completionChar != '\t') { editor.getCaretModel().moveToOffset(context.getTailOffset()); } else { editor.getCaretModel().moveToOffset(tail + 1); } context.setTailOffset(tail + 1); PsiElement list = element.getParent(); PsiElement last = list.getLastChild(); if (isToken(last, "]")) { int rparenthOffset = last.getTextRange().getStartOffset(); context.setTailOffset(rparenthOffset + 1); if (!putCaretInside) { for (int i = tail + 1; i < rparenthOffset; ++i) { if (!Character.isWhitespace(document.getCharsSequence().charAt(i))) { return; } } editor.getCaretModel().moveToOffset(context.getTailOffset()); } else { editor.getCaretModel().moveToOffset(tail + 1); } return; } } else { document.insertString(context.getTailOffset(), "["); editor.getCaretModel().moveToOffset(context.getTailOffset()); } if (context.getCompletionChar() == '[') { tail = context.getTailOffset(); if (tail < document.getTextLength() && StringUtil.isJavaIdentifierPart(document.getCharsSequence().charAt(tail))) { return; } } document.insertString(context.getTailOffset(), "]"); if (!putCaretInside) { editor.getCaretModel().moveToOffset(context.getTailOffset()); } } private static boolean isToken(@Nullable PsiElement element, @NotNull String text) { return element != null && element.textMatches(text); } } ================================================ FILE: src/com/goide/completion/BracesInsertHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; public class BracesInsertHandler implements InsertHandler { public static final BracesInsertHandler ONE_LINER = new BracesInsertHandler(true); public static final BracesInsertHandler INSTANCE = new BracesInsertHandler(false); private final boolean myOneLine; private BracesInsertHandler(boolean oneLine) { myOneLine = oneLine; } @Override public void handleInsert(@NotNull InsertionContext context, LookupElement item) { Editor editor = context.getEditor(); CharSequence documentText = context.getDocument().getImmutableCharSequence(); int offset = skipWhiteSpaces(editor.getCaretModel().getOffset(), documentText); if (documentText.charAt(offset) != '{') { Project project = context.getProject(); Template template = TemplateManager.getInstance(project).createTemplate("braces", "go", myOneLine ? "{$END$}" : " {\n$END$\n}"); template.setToReformat(true); TemplateManager.getInstance(project).startTemplate(editor, template); } else { editor.getCaretModel().moveToOffset(offset); ApplicationManager.getApplication().runWriteAction(() -> { EditorActionHandler enterAction = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_START_NEW_LINE); enterAction.execute(editor, editor.getCaretModel().getCurrentCaret(), ((EditorEx)editor).getDataContext()); }); } } private static int skipWhiteSpaces(int offset, @NotNull CharSequence documentText) { while (offset < documentText.length() && StringUtil.isWhiteSpace(documentText.charAt(offset))) { offset += 1; } return Math.min(documentText.length() - 1, offset); } } ================================================ FILE: src/com/goide/completion/CancellableCollectProcessor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.openapi.progress.ProgressManager; import com.intellij.util.CommonProcessors; import java.util.Collection; public class CancellableCollectProcessor extends CommonProcessors.CollectProcessor { public CancellableCollectProcessor(Collection collection) { super(collection); } @Override public boolean process(T s) { ProgressManager.checkCanceled(); return super.process(s); } } ================================================ FILE: src/com/goide/completion/GoAutoImportCompletionContributor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.project.GoVendoringUtil; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeReference; import com.goide.runconfig.testing.GoTestFinder; import com.goide.stubs.index.GoIdFilter; import com.goide.util.GoUtil; import com.intellij.codeInsight.completion.*; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.patterns.PsiElementPattern; import com.intellij.patterns.StandardPatterns; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.util.ProcessingContext; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static com.goide.completion.GoCompletionUtil.createPrefixMatcher; import static com.goide.psi.impl.GoPsiImplUtil.prevDot; import static com.goide.stubs.index.GoAllPublicNamesIndex.ALL_PUBLIC_NAMES; import static com.intellij.patterns.PlatformPatterns.psiElement; public class GoAutoImportCompletionContributor extends CompletionContributor { public GoAutoImportCompletionContributor() { extend(CompletionType.BASIC, inGoFile(), new CompletionProvider() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { PsiElement position = parameters.getPosition(); PsiElement parent = position.getParent(); if (prevDot(parent)) return; PsiFile psiFile = parameters.getOriginalFile(); if (!(psiFile instanceof GoFile && parent instanceof GoReferenceExpressionBase)) return; GoFile file = (GoFile)psiFile; result = adjustMatcher(parameters, result, parent); PrefixMatcher matcher = result.getPrefixMatcher(); if (parameters.getInvocationCount() < 2 && matcher.getPrefix().isEmpty()) { result.restartCompletionOnPrefixChange(StandardPatterns.string().longerThan(0)); return; } GoReferenceExpressionBase qualifier = ((GoReferenceExpressionBase)parent).getQualifier(); if (qualifier != null && qualifier.getReference() != null && qualifier.getReference().resolve() != null) return; ArrayList processors = ContainerUtil.newArrayList(); if (parent instanceof GoReferenceExpression && !GoPsiImplUtil.isUnaryBitAndExpression(parent)) { processors.add(new FunctionsProcessor()); processors.add(new VariablesAndConstantsProcessor()); } if (parent instanceof GoReferenceExpression || parent instanceof GoTypeReferenceExpression) { processors.add(new TypesProcessor(parent)); } if (processors.isEmpty()) return; Module module = ModuleUtilCore.findModuleForPsiElement(psiFile); NamedElementProcessor processor = new NamedElementProcessor(processors, file, result, module); Project project = position.getProject(); GlobalSearchScope scope = new GoUtil.ExceptTestsScope(GoUtil.goPathResolveScope(file)); VirtualFile containingDirectory = file.getVirtualFile().getParent(); if (containingDirectory != null) { scope = new GoUtil.ExceptChildOfDirectory(containingDirectory, scope, GoTestFinder.getTestTargetPackage(file)); } IdFilter idFilter = GoIdFilter.getProductionFilter(project); Set sortedKeys = collectAndSortAllPublicProductionNames(matcher, scope, idFilter, file); for (String name : sortedKeys) { processor.setName(name); for (GoNamedElement element : StubIndex.getElements(ALL_PUBLIC_NAMES, name, project, scope, idFilter, GoNamedElement.class)) { if (!processor.process(element)) { break; } } } } private CompletionResultSet adjustMatcher(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result, @NotNull PsiElement parent) { int startOffset = parent.getTextRange().getStartOffset(); String newPrefix = parameters.getEditor().getDocument().getText(TextRange.create(startOffset, parameters.getOffset())); return result.withPrefixMatcher(createPrefixMatcher(newPrefix)); } }); } @NotNull private static Set collectAndSortAllPublicProductionNames(@NotNull PrefixMatcher matcher, @NotNull GlobalSearchScope scope, @Nullable IdFilter idFilter, @NotNull GoFile file) { String prefix = matcher.getPrefix(); boolean emptyPrefix = prefix.isEmpty(); Set packagesWithAliases = ContainerUtil.newHashSet(); if (!emptyPrefix) { for (Map.Entry> entry : file.getImportMap().entrySet()) { for (GoImportSpec spec : entry.getValue()) { String alias = spec.getAlias(); if (spec.isDot() || alias != null) { packagesWithAliases.add(entry.getKey()); break; } } } } Set allNames = ContainerUtil.newTroveSet(); StubIndex.getInstance().processAllKeys(ALL_PUBLIC_NAMES, new CancellableCollectProcessor(allNames) { @Override protected boolean accept(String s) { return emptyPrefix || matcher.prefixMatches(s) || packagesWithAliases.contains(substringBefore(s, '.')); } }, scope, idFilter); if (emptyPrefix) { return allNames; } List sorted = ContainerUtil.sorted(allNames, String.CASE_INSENSITIVE_ORDER); ProgressManager.checkCanceled(); LinkedHashSet result = ContainerUtil.newLinkedHashSet(); for (String name : sorted) { ProgressManager.checkCanceled(); if (matcher.isStartMatch(name)) { result.add(name); } } result.addAll(sorted); return result; } private static PsiElementPattern.Capture inGoFile() { return psiElement().inFile(psiElement(GoFile.class)); } @NotNull private static String substringBefore(@NotNull String s, char c) { int i = s.indexOf(c); if (i == -1) return s; return s.substring(0, i); } private static String substringAfter(@NotNull String s, char c) { int i = s.indexOf(c); if (i == -1) return ""; return s.substring(i + 1); } @NotNull private static String replacePackageWithAlias(@NotNull String qualifiedName, @Nullable String alias) { return alias != null ? alias + "." + substringAfter(qualifiedName, '.') : qualifiedName; } private interface ElementProcessor { boolean process(@NotNull String name, @NotNull GoNamedElement element, @NotNull ExistingImportData importData, @NotNull CompletionResultSet result); boolean isMine(@NotNull String name, @NotNull GoNamedElement element); } private static class VariablesAndConstantsProcessor implements ElementProcessor { @Override public boolean process(@NotNull String name, @NotNull GoNamedElement element, @NotNull ExistingImportData importData, @NotNull CompletionResultSet result) { double priority = importData.exists ? GoCompletionUtil.VAR_PRIORITY : GoCompletionUtil.NOT_IMPORTED_VAR_PRIORITY; result.addElement(GoCompletionUtil.createVariableLikeLookupElement(element, replacePackageWithAlias(name, importData.alias), GoAutoImportInsertHandler.SIMPLE_INSERT_HANDLER, priority)); return true; } @Override public boolean isMine(@NotNull String name, @NotNull GoNamedElement element) { return element instanceof GoVarDefinition || element instanceof GoConstDefinition; } } private static class FunctionsProcessor implements ElementProcessor { @Override public boolean process(@NotNull String name, @NotNull GoNamedElement element, @NotNull ExistingImportData importData, @NotNull CompletionResultSet result) { GoFunctionDeclaration function = (GoFunctionDeclaration)element; double priority = importData.exists ? GoCompletionUtil.FUNCTION_PRIORITY : GoCompletionUtil.NOT_IMPORTED_FUNCTION_PRIORITY; result.addElement(GoCompletionUtil.createFunctionOrMethodLookupElement(function, replacePackageWithAlias(name, importData.alias), GoAutoImportInsertHandler.FUNCTION_INSERT_HANDLER, priority)); return true; } @Override public boolean isMine(@NotNull String name, @NotNull GoNamedElement element) { return element instanceof GoFunctionDeclaration; } } private static class TypesProcessor implements ElementProcessor { @Nullable private final PsiElement myParent; public TypesProcessor(@Nullable PsiElement parent) { myParent = parent; } @Override public boolean process(@NotNull String name, @NotNull GoNamedElement element, @NotNull ExistingImportData importData, @NotNull CompletionResultSet result) { GoTypeSpec spec = (GoTypeSpec)element; boolean forTypes = myParent instanceof GoTypeReferenceExpression; double priority; if (importData.exists) { priority = forTypes ? GoCompletionUtil.TYPE_PRIORITY : GoCompletionUtil.TYPE_CONVERSION; } else { priority = forTypes ? GoCompletionUtil.NOT_IMPORTED_TYPE_PRIORITY : GoCompletionUtil.NOT_IMPORTED_TYPE_CONVERSION; } String lookupString = replacePackageWithAlias(name, importData.alias); if (forTypes) { result.addElement(GoCompletionUtil.createTypeLookupElement(spec, lookupString, GoAutoImportInsertHandler.SIMPLE_INSERT_HANDLER, importData.importPath, priority)); } else { result.addElement(GoCompletionUtil.createTypeConversionLookupElement(spec, lookupString, GoAutoImportInsertHandler.TYPE_CONVERSION_INSERT_HANDLER, importData.importPath, priority)); } return true; } @Override public boolean isMine(@NotNull String name, @NotNull GoNamedElement element) { if (myParent != null && element instanceof GoTypeSpec) { PsiReference reference = myParent.getReference(); return !(reference instanceof GoTypeReference) || ((GoTypeReference)reference).allowed((GoTypeSpec)element); } return false; } } private static class NamedElementProcessor implements Processor { @NotNull private final Collection myProcessors; @NotNull private final CompletionResultSet myResult; @NotNull private String myName = ""; @NotNull private final Map myImportedPackages; @Nullable private final Module myModule; private final boolean myVendoringEnabled; public NamedElementProcessor(@NotNull Collection processors, @NotNull GoFile contextFile, @NotNull CompletionResultSet result, @Nullable Module module) { myProcessors = processors; myVendoringEnabled = GoVendoringUtil.isVendoringEnabled(module); myImportedPackages = contextFile.getImportedPackagesMap(); myModule = module; myResult = result; } public void setName(@NotNull String name) { myName = name; } @Override public boolean process(@NotNull GoNamedElement element) { ProgressManager.checkCanceled(); Boolean allowed = null; ExistingImportData importData = null; for (ElementProcessor processor : myProcessors) { if (processor.isMine(myName, element)) { importData = cachedImportData(element, importData); allowed = cachedAllowed(element, allowed); if (allowed == Boolean.FALSE || importData.isDot) break; if (!processor.process(myName, element, importData, myResult)) { return false; } } } return true; } @NotNull private Boolean cachedAllowed(@NotNull GoNamedElement element, @Nullable Boolean existingValue) { if (existingValue != null) return existingValue; return GoPsiImplUtil.canBeAutoImported(element.getContainingFile(), false, myModule); } @NotNull private ExistingImportData cachedImportData(@NotNull GoNamedElement element, @Nullable ExistingImportData existingValue) { if (existingValue != null) return existingValue; GoFile declarationFile = element.getContainingFile(); String importPath = declarationFile.getImportPath(myVendoringEnabled); GoImportSpec existingImport = myImportedPackages.get(importPath); boolean exists = existingImport != null; boolean isDot = exists && existingImport.isDot(); String alias = existingImport != null ? existingImport.getAlias() : null; return new ExistingImportData(exists, isDot, alias, importPath); } } private static class ExistingImportData { public final boolean exists; public final boolean isDot; public final String alias; public final String importPath; private ExistingImportData(boolean exists, boolean isDot, String packageName, String importPath) { this.exists = exists; this.isDot = isDot; alias = packageName; this.importPath = importPath; } } } ================================================ FILE: src/com/goide/completion/GoAutoImportInsertHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.codeInsight.imports.GoImportPackageQuickFix; import com.goide.project.GoVendoringUtil; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoNamedElement; import com.goide.psi.GoTypeSpec; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoAutoImportInsertHandler implements InsertHandler { public static final InsertHandler SIMPLE_INSERT_HANDLER = new GoAutoImportInsertHandler<>(); public static final InsertHandler TYPE_CONVERSION_INSERT_HANDLER = new GoAutoImportInsertHandler<>( GoCompletionUtil.Lazy.TYPE_CONVERSION_INSERT_HANDLER, GoTypeSpec.class); public static final InsertHandler FUNCTION_INSERT_HANDLER = new GoAutoImportInsertHandler<>( GoCompletionUtil.Lazy.VARIABLE_OR_FUNCTION_INSERT_HANDLER, GoFunctionDeclaration.class); @Nullable private final InsertHandler myDelegate; @Nullable private final Class myClass; private GoAutoImportInsertHandler() { this(null, null); } private GoAutoImportInsertHandler(@Nullable InsertHandler delegate, @Nullable Class clazz) { myDelegate = delegate; myClass = clazz; } @Override public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) { PsiElement element = item.getPsiElement(); if (element instanceof GoNamedElement) { if (myClass != null && myDelegate != null && myClass.isInstance(element)) { myDelegate.handleInsert(context, item); } autoImport(context, (GoNamedElement)element); } } private static void autoImport(@NotNull InsertionContext context, @NotNull GoNamedElement element) { PsiFile file = context.getFile(); boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(ModuleUtilCore.findModuleForPsiElement(file)); String importPath = element.getContainingFile().getImportPath(vendoringEnabled); if (StringUtil.isEmpty(importPath)) return; PsiDocumentManager.getInstance(context.getProject()).commitDocument(context.getEditor().getDocument()); PsiReference reference = file.findReferenceAt(context.getStartOffset()); if (reference != null) { PsiElement referenceElement = reference.getElement(); GoImportPackageQuickFix fix = new GoImportPackageQuickFix(referenceElement, importPath); fix.invoke(context.getProject(), file, context.getEditor(), referenceElement, referenceElement); } } } ================================================ FILE: src/com/goide/completion/GoCharFilter.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.psi.GoImportString; import com.intellij.codeInsight.lookup.CharFilter; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoCharFilter extends CharFilter { @Nullable @Override public Result acceptChar(char c, int prefixLength, @NotNull Lookup lookup) { if (lookup.isCompletion() && '/' == c && PsiTreeUtil.getParentOfType(lookup.getPsiElement(), GoImportString.class) != null) { return Result.ADD_TO_PREFIX; } return null; } } ================================================ FILE: src/com/goide/completion/GoCompletionConfidence.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.psi.GoNamedElement; import com.intellij.codeInsight.completion.CompletionConfidence; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; public class GoCompletionConfidence extends CompletionConfidence { @NotNull @Override public ThreeState shouldSkipAutopopup(@NotNull PsiElement context, @NotNull PsiFile psiFile, int offset) { return context instanceof GoNamedElement && ((GoNamedElement)context).isBlank() ? ThreeState.YES : ThreeState.UNSURE; } } ================================================ FILE: src/com/goide/completion/GoCompletionContributor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoConstants; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.psi.impl.GoCachedReference; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoPackageUtil; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Conditions; import com.intellij.patterns.PatternCondition; import com.intellij.patterns.PsiElementPattern; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ProcessingContext; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; import static com.intellij.codeInsight.completion.PrioritizedLookupElement.withPriority; import static com.intellij.patterns.PlatformPatterns.psiElement; public class GoCompletionContributor extends CompletionContributor { public GoCompletionContributor() { extend(CompletionType.BASIC, importString(), new GoImportPathsCompletionProvider()); extend(CompletionType.BASIC, referenceExpression(), new GoReferenceCompletionProvider()); extend(CompletionType.BASIC, goReference(), new GoReferenceCompletionProvider()); extend(CompletionType.BASIC, testFunctionSignature(), new GoTestFunctionCompletionProvider()); } private static PsiElementPattern.Capture testFunctionSignature() { return psiElement(GoTypes.IDENTIFIER).with(new GoTestFilePattern()).withParent(GoFunctionDeclaration.class) .afterLeaf(psiElement().withElementType(GoTypes.FUNC)); } private static PsiElementPattern.Capture goReference() { return psiElement().withParent(psiElement().withReference(GoCachedReference.class)); } @Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { PsiElement position = parameters.getPosition(); PsiFile file = parameters.getOriginalFile(); ASTNode node = position.getNode(); if (file instanceof GoFile && position.getParent() instanceof GoPackageClause && node.getElementType() == GoTypes.IDENTIFIER) { boolean isTestFile = GoTestFinder.isTestFile(file); PsiDirectory directory = file.getParent(); String currentPackageName = ((GoFile)file).getPackageName(); Collection packagesInDirectory = GoPackageUtil.getAllPackagesInDirectory(directory, null, true); for (String packageName : packagesInDirectory) { if (!packageName.equals(currentPackageName)) { result.addElement(packageLookup(packageName, GoCompletionUtil.PACKAGE_PRIORITY - 1)); } if (isTestFile) { result.addElement(packageLookup(packageName + GoConstants.TEST_SUFFIX, GoCompletionUtil.PACKAGE_PRIORITY)); } } if (directory != null && ContainerUtil.filter(directory.getFiles(), Conditions.instanceOf(GoFile.class)).size() == 1) { String packageFromDirectory = GoPsiImplUtil.getLocalPackageName(directory.getName()); if (!packageFromDirectory.isEmpty()) { result.addElement(packageLookup(packageFromDirectory, GoCompletionUtil.PACKAGE_PRIORITY - 1)); } } result.addElement(packageLookup(GoConstants.MAIN, GoCompletionUtil.PACKAGE_PRIORITY - 2)); } super.fillCompletionVariants(parameters, result); } @NotNull private static LookupElement packageLookup(@NotNull String packageName, int priority) { LookupElement element = withPriority(LookupElementBuilder.create(packageName), priority); return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(element); } private static PsiElementPattern.Capture importString() { return psiElement().withElementType(GoParserDefinition.STRING_LITERALS).withParent(GoStringLiteral.class) .withSuperParent(2, GoImportString.class); } private static PsiElementPattern.Capture referenceExpression() { return psiElement().withParent(GoReferenceExpressionBase.class); } private static class GoTestFilePattern extends PatternCondition { public GoTestFilePattern() { super("in go test file"); } @Override public boolean accepts(@NotNull PsiElement element, ProcessingContext context) { return GoTestFinder.isTestFile(element.getContainingFile()); } } } ================================================ FILE: src/com/goide/completion/GoCompletionUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoIcons; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.sdk.GoSdkUtil; import com.goide.stubs.GoFieldDefinitionStub; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.completion.PrefixMatcher; import com.intellij.codeInsight.completion.PrioritizedLookupElement; import com.intellij.codeInsight.completion.impl.CamelHumpMatcher; import com.intellij.codeInsight.completion.util.ParenthesesInsertHandler; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.lookup.LookupElementPresentation; import com.intellij.codeInsight.lookup.LookupElementRenderer; import com.intellij.openapi.Disposable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; public class GoCompletionUtil { public static final int KEYWORD_PRIORITY = 20; public static final int CONTEXT_KEYWORD_PRIORITY = 25; public static final int NOT_IMPORTED_FUNCTION_PRIORITY = 3; public static final int FUNCTION_PRIORITY = NOT_IMPORTED_FUNCTION_PRIORITY + 10; public static final int NOT_IMPORTED_TYPE_PRIORITY = 5; public static final int TYPE_PRIORITY = NOT_IMPORTED_TYPE_PRIORITY + 10; public static final int NOT_IMPORTED_TYPE_CONVERSION = 1; public static final int TYPE_CONVERSION = NOT_IMPORTED_TYPE_CONVERSION + 10; public static final int NOT_IMPORTED_VAR_PRIORITY = 5; public static final int VAR_PRIORITY = NOT_IMPORTED_VAR_PRIORITY + 10; private static final int FIELD_PRIORITY = CONTEXT_KEYWORD_PRIORITY + 1; private static final int LABEL_PRIORITY = 15; public static final int PACKAGE_PRIORITY = 5; public static class Lazy { private static final SingleCharInsertHandler DIR_INSERT_HANDLER = new SingleCharInsertHandler('/'); private static final SingleCharInsertHandler PACKAGE_INSERT_HANDLER = new SingleCharInsertHandler('.'); public static final InsertHandler VARIABLE_OR_FUNCTION_INSERT_HANDLER = new InsertHandler() { @Override public void handleInsert(InsertionContext context, @NotNull LookupElement item) { PsiElement e = item.getPsiElement(); if (e instanceof GoSignatureOwner) { doInsert(context, item, ((GoSignatureOwner)e).getSignature()); } else if (e instanceof GoNamedElement) { GoType type = ((GoNamedElement)e).getGoType(null); if (type instanceof GoFunctionType) { doInsert(context, item, ((GoFunctionType)type).getSignature()); } } } private void doInsert(InsertionContext context, @NotNull LookupElement item, @Nullable GoSignature signature) { int paramsCount = signature != null ? signature.getParameters().getParameterDeclarationList().size() : 0; InsertHandler handler = paramsCount == 0 ? ParenthesesInsertHandler.NO_PARAMETERS : ParenthesesInsertHandler.WITH_PARAMETERS; handler.handleInsert(context, item); if (signature != null) { AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), null); } } }; public static final InsertHandler TYPE_CONVERSION_INSERT_HANDLER = (context, item) -> { PsiElement element = item.getPsiElement(); if (element instanceof GoTypeSpec) { GoType type = ((GoTypeSpec)element).getSpecType().getType(); if (type instanceof GoStructType || type instanceof GoArrayOrSliceType || type instanceof GoMapType) { BracesInsertHandler.ONE_LINER.handleInsert(context, item); } else { ParenthesesInsertHandler.WITH_PARAMETERS.handleInsert(context, item); } } }; private static final SingleCharInsertHandler FIELD_DEFINITION_INSERT_HANDLER = new SingleCharInsertHandler(':') { @Override public void handleInsert(@NotNull InsertionContext context, LookupElement item) { PsiFile file = context.getFile(); if (!(file instanceof GoFile)) return; context.commitDocument(); int offset = context.getStartOffset(); PsiElement at = file.findElementAt(offset); GoCompositeElement ref = PsiTreeUtil.getParentOfType(at, GoValue.class, GoReferenceExpression.class); if (ref instanceof GoReferenceExpression && (((GoReferenceExpression)ref).getQualifier() != null || GoPsiImplUtil.prevDot(ref))) { return; } GoValue value = PsiTreeUtil.getParentOfType(at, GoValue.class); if (value == null || PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class) != null) return; super.handleInsert(context, item); } }; private static final LookupElementRenderer FUNCTION_RENDERER = new LookupElementRenderer() { @Override public void renderElement(@NotNull LookupElement element, @NotNull LookupElementPresentation p) { PsiElement o = element.getPsiElement(); if (!(o instanceof GoNamedSignatureOwner)) return; GoNamedSignatureOwner f = (GoNamedSignatureOwner)o; Icon icon = f instanceof GoMethodDeclaration || f instanceof GoMethodSpec ? GoIcons.METHOD : GoIcons.FUNCTION; String typeText = ""; GoSignature signature = f.getSignature(); String paramText = ""; if (signature != null) { GoResult result = signature.getResult(); paramText = signature.getParameters().getText(); if (result != null) typeText = result.getText(); } p.setIcon(icon); p.setTypeText(typeText); p.setTypeGrayed(true); p.setTailText(calcTailText(f), true); p.setItemText(element.getLookupString() + paramText); } }; private static final LookupElementRenderer VARIABLE_RENDERER = new LookupElementRenderer() { @Override public void renderElement(@NotNull LookupElement element, @NotNull LookupElementPresentation p) { PsiElement o = element.getPsiElement(); if (!(o instanceof GoNamedElement)) return; GoNamedElement v = (GoNamedElement)o; GoType type = typesDisabled ? null : v.getGoType(null); String text = GoPsiImplUtil.getText(type); Icon icon = v instanceof GoVarDefinition ? GoIcons.VARIABLE : v instanceof GoParamDefinition ? GoIcons.PARAMETER : v instanceof GoFieldDefinition ? GoIcons.FIELD : v instanceof GoReceiver ? GoIcons.RECEIVER : v instanceof GoConstDefinition ? GoIcons.CONSTANT : v instanceof GoAnonymousFieldDefinition ? GoIcons.FIELD : null; p.setIcon(icon); p.setTailText(calcTailTextForFields(v), true); p.setTypeText(text); p.setTypeGrayed(true); p.setItemText(element.getLookupString()); } }; } private static boolean typesDisabled; @TestOnly public static void disableTypeInfoInLookup(@NotNull Disposable disposable) { typesDisabled = true; Disposer.register(disposable, () -> { //noinspection AssignmentToStaticFieldFromInstanceMethod typesDisabled = false; }); } private GoCompletionUtil() { } @NotNull public static CamelHumpMatcher createPrefixMatcher(@NotNull PrefixMatcher original) { return createPrefixMatcher(original.getPrefix()); } @NotNull public static CamelHumpMatcher createPrefixMatcher(@NotNull String prefix) { return new CamelHumpMatcher(prefix, false); } @NotNull public static LookupElement createFunctionOrMethodLookupElement(@NotNull GoNamedSignatureOwner f, @NotNull String lookupString, @Nullable InsertHandler h, double priority) { return PrioritizedLookupElement.withPriority(LookupElementBuilder .createWithSmartPointer(lookupString, f) .withRenderer(Lazy.FUNCTION_RENDERER) .withInsertHandler(h != null ? h : Lazy.VARIABLE_OR_FUNCTION_INSERT_HANDLER), priority); } @Nullable private static String calcTailText(GoSignatureOwner m) { if (typesDisabled) { return null; } String text = ""; if (m instanceof GoMethodDeclaration) { text = GoPsiImplUtil.getText(((GoMethodDeclaration)m).getReceiverType()); } else if (m instanceof GoMethodSpec) { PsiElement parent = m.getParent(); if (parent instanceof GoInterfaceType) { text = GoPsiImplUtil.getText((GoInterfaceType)parent); } } return StringUtil.isNotEmpty(text) ? " " + UIUtil.rightArrow() + " " + text : null; } @NotNull public static LookupElement createTypeLookupElement(@NotNull GoTypeSpec t) { return createTypeLookupElement(t, StringUtil.notNullize(t.getName()), null, null, TYPE_PRIORITY); } @NotNull public static LookupElement createTypeLookupElement(@NotNull GoTypeSpec t, @NotNull String lookupString, @Nullable InsertHandler handler, @Nullable String importPath, double priority) { LookupElementBuilder builder = LookupElementBuilder.createWithSmartPointer(lookupString, t) .withInsertHandler(handler).withIcon(GoIcons.TYPE); if (importPath != null) builder = builder.withTailText(" " + importPath, true); return PrioritizedLookupElement.withPriority(builder, priority); } @NotNull public static LookupElement createLabelLookupElement(@NotNull GoLabelDefinition l, @NotNull String lookupString) { return PrioritizedLookupElement.withPriority(LookupElementBuilder.createWithSmartPointer(lookupString, l).withIcon(GoIcons.LABEL), LABEL_PRIORITY); } @NotNull public static LookupElement createTypeConversionLookupElement(@NotNull GoTypeSpec t) { return createTypeConversionLookupElement(t, StringUtil.notNullize(t.getName()), null, null, TYPE_CONVERSION); } @NotNull public static LookupElement createTypeConversionLookupElement(@NotNull GoTypeSpec t, @NotNull String lookupString, @Nullable InsertHandler insertHandler, @Nullable String importPath, double priority) { // todo: check context and place caret in or outside {} InsertHandler handler = ObjectUtils.notNull(insertHandler, Lazy.TYPE_CONVERSION_INSERT_HANDLER); return createTypeLookupElement(t, lookupString, handler, importPath, priority); } @Nullable public static LookupElement createFieldLookupElement(@NotNull GoFieldDefinition v) { String name = v.getName(); if (StringUtil.isEmpty(name)) return null; return createVariableLikeLookupElement(v, name, Lazy.FIELD_DEFINITION_INSERT_HANDLER, FIELD_PRIORITY); } @Nullable public static LookupElement createVariableLikeLookupElement(@NotNull GoNamedElement v) { String name = v.getName(); if (StringUtil.isEmpty(name)) return null; return createVariableLikeLookupElement(v, name, Lazy.VARIABLE_OR_FUNCTION_INSERT_HANDLER, VAR_PRIORITY); } @NotNull public static LookupElement createVariableLikeLookupElement(@NotNull GoNamedElement v, @NotNull String lookupString, @Nullable InsertHandler insertHandler, double priority) { return PrioritizedLookupElement.withPriority(LookupElementBuilder.createWithSmartPointer(lookupString, v) .withRenderer(Lazy.VARIABLE_RENDERER) .withInsertHandler(insertHandler), priority); } @Nullable private static String calcTailTextForFields(@NotNull GoNamedElement v) { String name = null; if (v instanceof GoFieldDefinition) { GoFieldDefinitionStub stub = ((GoFieldDefinition)v).getStub(); GoTypeSpec spec = stub != null ? stub.getParentStubOfType(GoTypeSpec.class) : PsiTreeUtil.getParentOfType(v, GoTypeSpec.class); name = spec != null ? spec.getName() : null; } return StringUtil.isNotEmpty(name) ? " " + UIUtil.rightArrow() + " " + name : null; } @Nullable public static LookupElement createPackageLookupElement(@NotNull GoImportSpec spec, @Nullable String name, boolean vendoringEnabled) { name = name != null ? name : ObjectUtils.notNull(spec.getAlias(), spec.getLocalPackageName()); return createPackageLookupElement(name, spec.getImportString().resolve(), spec, vendoringEnabled, true); } @NotNull public static LookupElement createPackageLookupElement(@NotNull String importPath, @Nullable PsiDirectory directory, @Nullable PsiElement context, boolean vendoringEnabled, boolean forType) { return createPackageLookupElement(importPath, getContextImportPath(context, vendoringEnabled), directory, forType); } @NotNull public static LookupElement createPackageLookupElement(@NotNull String importPath, @Nullable String contextImportPath, @Nullable PsiDirectory directory, boolean forType) { LookupElementBuilder builder = directory != null ? LookupElementBuilder.create(directory, importPath) : LookupElementBuilder.create(importPath); return PrioritizedLookupElement.withPriority(builder.withLookupString(importPath.substring(Math.max(0, importPath.lastIndexOf('/')))) .withIcon(GoIcons.PACKAGE) .withInsertHandler(forType ? Lazy.PACKAGE_INSERT_HANDLER : null), calculatePackagePriority(importPath, contextImportPath)); } public static int calculatePackagePriority(@NotNull String importPath, @Nullable String currentPath) { int priority = PACKAGE_PRIORITY; if (StringUtil.isNotEmpty(currentPath)) { String[] givenSplit = importPath.split("/"); String[] contextSplit = currentPath.split("/"); for (int i = 0; i < contextSplit.length && i < givenSplit.length; i++) { if (contextSplit[i].equals(givenSplit[i])) { priority++; } else { break; } } } return priority - StringUtil.countChars(importPath, '/') - StringUtil.countChars(importPath, '.'); } @Nullable public static String getContextImportPath(@Nullable PsiElement context, boolean vendoringEnabled) { if (context == null) return null; String currentPath = null; if (context instanceof PsiDirectory) { currentPath = GoSdkUtil.getImportPath((PsiDirectory)context, vendoringEnabled); } else { PsiFile file = context.getContainingFile(); if (file instanceof GoFile) { currentPath = ((GoFile)file).getImportPath(vendoringEnabled); } } return currentPath; } @NotNull public static LookupElementBuilder createDirectoryLookupElement(@NotNull PsiDirectory dir) { return LookupElementBuilder.createWithSmartPointer(dir.getName(), dir).withIcon(GoIcons.DIRECTORY) .withInsertHandler(dir.getFiles().length == 0 ? Lazy.DIR_INSERT_HANDLER : null); } } ================================================ FILE: src/com/goide/completion/GoImportPathsCompletionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoFileType; import com.goide.project.GoExcludedPathsSettings; import com.goide.project.GoVendoringUtil; import com.goide.psi.GoFile; import com.goide.psi.GoImportString; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.util.GoUtil; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoImportPathsCompletionProvider extends CompletionProvider { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { GoImportString importString = PsiTreeUtil.getParentOfType(parameters.getPosition(), GoImportString.class); if (importString == null) return; String path = importString.getPath(); if (path.startsWith("./") || path.startsWith("../")) return; TextRange pathRange = importString.getPathTextRange().shiftRight(importString.getTextRange().getStartOffset()); String newPrefix = parameters.getEditor().getDocument().getText(TextRange.create(pathRange.getStartOffset(), parameters.getOffset())); result = result.withPrefixMatcher(result.getPrefixMatcher().cloneWithPrefix(newPrefix)); Module module = ModuleUtilCore.findModuleForPsiElement(parameters.getOriginalFile()); if (module != null) { addCompletions(result, module, parameters.getOriginalFile(), GoUtil.goPathResolveScope(module, parameters.getOriginalFile()), false); } } public static void addCompletions(@NotNull CompletionResultSet result, @NotNull Module module, @Nullable PsiElement context, @NotNull GlobalSearchScope scope, boolean allowMain) { Project project = module.getProject(); boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module); String contextImportPath = GoCompletionUtil.getContextImportPath(context, vendoringEnabled); GoExcludedPathsSettings excludedSettings = GoExcludedPathsSettings.getInstance(project); PsiFile contextFile = context != null ? context.getContainingFile() : null; boolean testFileWithTestPackage = GoTestFinder.isTestFileWithTestPackage(contextFile); for (VirtualFile file : FileTypeIndex.getFiles(GoFileType.INSTANCE, scope)) { ProgressManager.checkCanceled(); PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (!(psiFile instanceof GoFile)) continue; PsiDirectory directory = psiFile.getContainingDirectory(); if (directory == null) continue; GoFile goFile = (GoFile)psiFile; if (!GoPsiImplUtil.canBeAutoImported(goFile, allowMain, module)) continue; String importPath = goFile.getImportPath(vendoringEnabled); if (StringUtil.isNotEmpty(importPath) && !excludedSettings.isExcluded(importPath) && (testFileWithTestPackage || !importPath.equals(contextImportPath))) { result.addElement(GoCompletionUtil.createPackageLookupElement(importPath, contextImportPath, directory, false)); } } } } ================================================ FILE: src/com/goide/completion/GoKeywordCompletionContributor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.template.GoLiveTemplateContextType; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.project.DumbAware; import com.intellij.patterns.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import java.util.Collection; import static com.goide.completion.GoCompletionUtil.CONTEXT_KEYWORD_PRIORITY; import static com.goide.completion.GoCompletionUtil.KEYWORD_PRIORITY; import static com.goide.completion.GoKeywordCompletionProvider.EMPTY_INSERT_HANDLER; import static com.intellij.patterns.PlatformPatterns.psiElement; import static com.intellij.patterns.PlatformPatterns.psiFile; import static com.intellij.patterns.StandardPatterns.*; public class GoKeywordCompletionContributor extends CompletionContributor implements DumbAware { private static final InsertHandler ADD_BRACKETS_INSERT_HANDLER = new AddBracketsInsertHandler(); public GoKeywordCompletionContributor() { extend(CompletionType.BASIC, packagePattern(), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE, "package")); extend(CompletionType.BASIC, importPattern(), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, "import")); extend(CompletionType.BASIC, topLevelPattern(), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, "const", "var", "func", "type")); extend(CompletionType.BASIC, insideBlockPattern(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, "type", "for", "const", "var", "return", "if", "switch", "go", "defer", "goto")); extend(CompletionType.BASIC, insideBlockPattern(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, EMPTY_INSERT_HANDLER, "fallthrough")); extend(CompletionType.BASIC, insideBlockPattern(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, BracesInsertHandler.INSTANCE, "select")); extend(CompletionType.BASIC, typeDeclaration(), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, BracesInsertHandler.INSTANCE, "interface", "struct")); extend(CompletionType.BASIC, typeExpression(), new GoKeywordCompletionProvider(KEYWORD_PRIORITY, BracesInsertHandler.ONE_LINER, "interface", "struct")); extend(CompletionType.BASIC, insideForStatement(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, EMPTY_INSERT_HANDLER, "continue")); extend(CompletionType.BASIC, insideBreakStatementOwner(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, EMPTY_INSERT_HANDLER, "break")); extend(CompletionType.BASIC, typeExpression(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, "chan")); extend(CompletionType.BASIC, typeExpression(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, ADD_BRACKETS_INSERT_HANDLER, "map")); extend(CompletionType.BASIC, referenceExpression(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, ADD_BRACKETS_INSERT_HANDLER, "map")); extend(CompletionType.BASIC, afterIfBlock(GoTypes.IDENTIFIER), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, "else")); extend(CompletionType.BASIC, afterElseKeyword(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, "if")); extend(CompletionType.BASIC, insideSwitchStatement(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, "case", "default")); extend(CompletionType.BASIC, rangeClause(), new GoKeywordCompletionProvider(CONTEXT_KEYWORD_PRIORITY, AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP, "range")); } @Override public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) { super.fillCompletionVariants(parameters, result); PsiElement position = parameters.getPosition(); if (insideGoOrDeferStatements().accepts(position) || anonymousFunction().accepts(position)) { InsertHandler insertHandler = GoKeywordCompletionProvider.createTemplateBasedInsertHandler("go_lang_anonymous_func"); result.addElement(GoKeywordCompletionProvider.createKeywordLookupElement("func", CONTEXT_KEYWORD_PRIORITY, insertHandler)); } if (referenceExpression().accepts(position)) { InsertHandler insertHandler = GoKeywordCompletionProvider.createTemplateBasedInsertHandler("go_lang_anonymous_struct"); result.addElement(GoKeywordCompletionProvider.createKeywordLookupElement("struct", CONTEXT_KEYWORD_PRIORITY, insertHandler)); } } private static ElementPattern afterIfBlock(@NotNull IElementType tokenType) { PsiElementPattern.Capture statement = psiElement(GoStatement.class).afterSiblingSkipping(psiElement().whitespaceCommentEmptyOrError(), psiElement(GoIfStatement.class)); PsiElementPattern.Capture lh = psiElement(GoLeftHandExprList.class).withParent(statement); return psiElement(tokenType).withParent(psiElement(GoReferenceExpressionBase.class).with(new GoNonQualifiedReference()).withParent(lh)) .andNot(afterElseKeyword()).afterLeaf(psiElement(GoTypes.RBRACE)); } private static ElementPattern rangeClause() { return psiElement(GoTypes.IDENTIFIER).andOr( // for a := ran | for a = ran psiElement().withParent(psiElement(GoReferenceExpression.class).withParent(GoRangeClause.class).afterLeaf("=", ":=")), // for ran psiElement().afterLeaf(psiElement(GoTypes.FOR)) ); } private static ElementPattern afterElseKeyword() { return psiElement(GoTypes.IDENTIFIER).afterLeafSkipping(psiElement().whitespaceCommentEmptyOrError(), psiElement(GoTypes.ELSE)); } private static ElementPattern insideForStatement(@NotNull IElementType tokenType) { return insideBlockPattern(tokenType).inside(false, psiElement(GoForStatement.class), psiElement(GoFunctionLit.class)); } private static ElementPattern insideBreakStatementOwner(@NotNull IElementType tokenType) { return insideBlockPattern(tokenType).with(new InsideBreakStatementOwner()); } private static ElementPattern insideConstSpec() { return psiElement().inside(false, psiElement(GoConstSpec.class), psiElement(GoStatement.class)); } private static PsiElementPattern.Capture insideSelectorExpression() { return psiElement().inside(true, psiElement(GoSelectorExpr.class), psiElement(GoStatement.class)); } private static ElementPattern typeExpression() { return psiElement(GoTypes.IDENTIFIER).withParent( psiElement(GoTypeReferenceExpression.class) .with(new GoNonQualifiedReference()) .with(new GoNotInsideReceiver())); } private static ElementPattern referenceExpression() { return psiElement(GoTypes.IDENTIFIER).withParent( psiElement(GoReferenceExpression.class) .andNot(insideConstSpec()) .andNot(insideSelectorExpression()) .without(new FieldNameInStructLiteral()) .withParent(not(psiElement(GoSelectorExpr.class))).with(new GoNonQualifiedReference())); } private static ElementPattern insideSwitchStatement() { return onStatementBeginning(GoTypes.IDENTIFIER, GoTypes.CASE, GoTypes.DEFAULT) .inside(false, psiElement(GoCaseClause.class), psiElement(GoFunctionLit.class)); } private static ElementPattern typeDeclaration() { return psiElement(GoTypes.IDENTIFIER) .withParent(psiElement(GoTypeReferenceExpression.class).withParent(psiElement(GoType.class).withParent(GoSpecType.class))); } private static PsiElementPattern.Capture insideGoOrDeferStatements() { return psiElement(GoTypes.IDENTIFIER) .withParent(psiElement(GoExpression.class).withParent(or(psiElement(GoDeferStatement.class), psiElement(GoGoStatement.class)))); } private static ElementPattern anonymousFunction() { return and(referenceExpression(), psiElement().withParent(psiElement(GoReferenceExpression.class) .withParent(or(psiElement(GoArgumentList.class), not(psiElement(GoLeftHandExprList.class)))))); } private static PsiElementPattern.Capture insideBlockPattern(@NotNull IElementType tokenType) { return onStatementBeginning(tokenType) .withParent(psiElement(GoExpression.class).withParent(psiElement(GoLeftHandExprList.class).withParent( psiElement(GoStatement.class).inside(GoBlock.class)))); } private static PsiElementPattern.Capture topLevelPattern() { return onStatementBeginning(GoTypes.IDENTIFIER).withParent( or(psiElement(PsiErrorElement.class).withParent(goFileWithPackage()), psiElement(GoFile.class))); } private static PsiElementPattern.Capture importPattern() { return onStatementBeginning(GoTypes.IDENTIFIER).withParent(psiElement(GoFile.class)) .afterSiblingSkipping(psiElement().whitespaceCommentOrError(), psiElement(GoImportList.class)); } private static PsiElementPattern.Capture packagePattern() { return psiElement(GoTypes.IDENTIFIER) .withParent(psiElement(PsiErrorElement.class).withParent(goFileWithoutPackage()).isFirstAcceptedChild(psiElement())); } private static PsiElementPattern.Capture onStatementBeginning(@NotNull IElementType... tokenTypes) { return psiElement().withElementType(TokenSet.create(tokenTypes)).with(new OnStatementBeginning()); } private static PsiFilePattern.Capture goFileWithPackage() { CollectionPattern collection = collection(PsiElement.class); CollectionPattern packageIsFirst = collection.first(psiElement(GoTypes.PACKAGE_CLAUSE)); return psiFile(GoFile.class).withChildren(collection.filter(not(psiElement().whitespaceCommentEmptyOrError()), packageIsFirst)); } private static PsiFilePattern.Capture goFileWithoutPackage() { CollectionPattern collection = collection(PsiElement.class); ElementPattern> emptyOrPackageIsNotFirst = or(collection.empty(), collection.first(not(psiElement(GoTypes.PACKAGE_CLAUSE)))); return psiFile(GoFile.class).withChildren(collection.filter(not(psiElement().whitespaceCommentEmptyOrError()), emptyOrPackageIsNotFirst)); } private static class GoNonQualifiedReference extends PatternCondition { public GoNonQualifiedReference() { super("non qualified type"); } @Override public boolean accepts(@NotNull GoReferenceExpressionBase element, ProcessingContext context) { return element.getQualifier() == null; } } private static class GoNotInsideReceiver extends PatternCondition { public GoNotInsideReceiver() { super("noi inside receiver"); } @Override public boolean accepts(@NotNull GoReferenceExpressionBase element, ProcessingContext context) { return PsiTreeUtil.getParentOfType(element, GoReceiver.class) == null; } } private static class FieldNameInStructLiteral extends PatternCondition { public FieldNameInStructLiteral() { super("field name in struct literal"); } @Override public boolean accepts(@NotNull GoReferenceExpression expression, ProcessingContext context) { GoStructLiteralCompletion.Variants variants = GoStructLiteralCompletion.allowedVariants(expression); return variants == GoStructLiteralCompletion.Variants.FIELD_NAME_ONLY; } } private static class OnStatementBeginning extends PatternCondition { public OnStatementBeginning() { super("on statement beginning"); } @Override public boolean accepts(@NotNull PsiElement psiElement, ProcessingContext context) { return GoLiveTemplateContextType.Statement.onStatementBeginning(psiElement); } } private static class InsideBreakStatementOwner extends PatternCondition { public InsideBreakStatementOwner() {super("inside break statement owner");} @Override public boolean accepts(@NotNull PsiElement element, ProcessingContext context) { return GoPsiImplUtil.getBreakStatementOwner(element) != null; } } } ================================================ FILE: src/com/goide/completion/GoKeywordCompletionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.AutoCompletionPolicy; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoKeywordCompletionProvider extends CompletionProvider { public static final InsertHandler EMPTY_INSERT_HANDLER = (context, element) -> { }; private final int myPriority; @Nullable private final InsertHandler myInsertHandler; @Nullable private final AutoCompletionPolicy myCompletionPolicy; @NotNull private final String[] myKeywords; public GoKeywordCompletionProvider(int priority, String... keywords) { this(priority, null, null, keywords); } public GoKeywordCompletionProvider(int priority, @Nullable AutoCompletionPolicy completionPolicy, @NotNull String... keywords) { this(priority, null, completionPolicy, keywords); } public GoKeywordCompletionProvider(int priority, @Nullable InsertHandler insertHandler, @NotNull String... keywords) { this(priority, insertHandler, null, keywords); } private GoKeywordCompletionProvider(int priority, @Nullable InsertHandler insertHandler, @Nullable AutoCompletionPolicy completionPolicy, @NotNull String... keywords) { myPriority = priority; myInsertHandler = insertHandler; myCompletionPolicy = completionPolicy; myKeywords = keywords; } @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { for (String keyword : myKeywords) { result.addElement(createKeywordLookupElement(keyword)); } } @NotNull private LookupElement createKeywordLookupElement(@NotNull String keyword) { InsertHandler insertHandler = ObjectUtils.chooseNotNull(myInsertHandler, createTemplateBasedInsertHandler("go_lang_" + keyword)); LookupElement result = createKeywordLookupElement(keyword, myPriority, insertHandler); return myCompletionPolicy != null ? myCompletionPolicy.applyPolicy(result) : result; } public static LookupElement createKeywordLookupElement(@NotNull String keyword, int priority, @Nullable InsertHandler insertHandler) { LookupElementBuilder builder = LookupElementBuilder.create(keyword).withBoldness(true).withInsertHandler(insertHandler); return PrioritizedLookupElement.withPriority(builder, priority); } @Nullable public static InsertHandler createTemplateBasedInsertHandler(@NotNull String templateId) { return (context, item) -> { Template template = TemplateSettings.getInstance().getTemplateById(templateId); Editor editor = context.getEditor(); if (template != null) { editor.getDocument().deleteString(context.getStartOffset(), context.getTailOffset()); TemplateManager.getInstance(context.getProject()).startTemplate(editor, template); } else { int currentOffset = editor.getCaretModel().getOffset(); CharSequence documentText = editor.getDocument().getImmutableCharSequence(); if (documentText.length() <= currentOffset || documentText.charAt(currentOffset) != ' ') { EditorModificationUtil.insertStringAtCaret(editor, " "); } else { EditorModificationUtil.moveCaretRelatively(editor, 1); } } }; } } ================================================ FILE: src/com/goide/completion/GoReferenceCompletionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.project.GoVendoringUtil; import com.goide.psi.*; import com.goide.psi.impl.*; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ProcessingContext; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; import static com.goide.completion.GoCompletionUtil.createPrefixMatcher; public class GoReferenceCompletionProvider extends CompletionProvider { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet set) { GoReferenceExpressionBase expression = PsiTreeUtil.getParentOfType(parameters.getPosition(), GoReferenceExpressionBase.class); PsiFile originalFile = parameters.getOriginalFile(); if (expression != null) { fillVariantsByReference(expression.getReference(), originalFile, set.withPrefixMatcher(createPrefixMatcher(set.getPrefixMatcher()))); } PsiElement parent = parameters.getPosition().getParent(); if (parent != null) { fillVariantsByReference(parent.getReference(), originalFile, set.withPrefixMatcher(createPrefixMatcher(set.getPrefixMatcher()))); } } private static void fillVariantsByReference(@Nullable PsiReference reference, @NotNull PsiFile file, @NotNull CompletionResultSet result) { if (reference == null) return; if (reference instanceof PsiMultiReference) { PsiReference[] references = ((PsiMultiReference)reference).getReferences(); ContainerUtil.sort(references, PsiMultiReference.COMPARATOR); fillVariantsByReference(ArrayUtil.getFirstElement(references), file, result); } else if (reference instanceof GoReference) { GoReferenceExpression refExpression = ObjectUtils.tryCast(reference.getElement(), GoReferenceExpression.class); GoStructLiteralCompletion.Variants variants = GoStructLiteralCompletion.allowedVariants(refExpression); fillStructFieldNameVariants(file, result, variants, refExpression); if (variants != GoStructLiteralCompletion.Variants.FIELD_NAME_ONLY) { ((GoReference)reference).processResolveVariants(new MyGoScopeProcessor(result, file, false)); } } else if (reference instanceof GoTypeReference) { PsiElement element = reference.getElement(); PsiElement spec = PsiTreeUtil.getParentOfType(element, GoFieldDeclaration.class, GoTypeSpec.class); boolean insideParameter = PsiTreeUtil.getParentOfType(element, GoParameterDeclaration.class) != null; ((GoTypeReference)reference).processResolveVariants(new MyGoScopeProcessor(result, file, true) { @Override protected boolean accept(@NotNull PsiElement e) { return e != spec && !(insideParameter && (e instanceof GoNamedSignatureOwner || e instanceof GoVarDefinition || e instanceof GoConstDefinition)); } }); } else if (reference instanceof GoCachedReference) { ((GoCachedReference)reference).processResolveVariants(new MyGoScopeProcessor(result, file, false)); } } private static void fillStructFieldNameVariants(@NotNull PsiFile file, @NotNull CompletionResultSet result, @NotNull GoStructLiteralCompletion.Variants variants, @Nullable GoReferenceExpression refExpression) { if (refExpression == null || variants != GoStructLiteralCompletion.Variants.FIELD_NAME_ONLY && variants != GoStructLiteralCompletion.Variants.BOTH) { return; } GoLiteralValue literal = PsiTreeUtil.getParentOfType(refExpression, GoLiteralValue.class); new GoFieldNameReference(refExpression).processResolveVariants(new MyGoScopeProcessor(result, file, false) { final Set alreadyAssignedFields = GoStructLiteralCompletion.alreadyAssignedFields(literal); @Override public boolean execute(@NotNull PsiElement o, @NotNull ResolveState state) { String structFieldName = o instanceof GoFieldDefinition ? ((GoFieldDefinition)o).getName() : o instanceof GoAnonymousFieldDefinition ? ((GoAnonymousFieldDefinition)o).getName() : null; if (structFieldName != null && alreadyAssignedFields.contains(structFieldName)) { return true; } return super.execute(o, state); } }); } private static void addElement(@NotNull PsiElement o, @NotNull ResolveState state, boolean forTypes, boolean vendoringEnabled, @NotNull Set processedNames, @NotNull CompletionResultSet set) { LookupElement lookup = createLookupElement(o, state, forTypes, vendoringEnabled); if (lookup != null) { String lookupString = lookup.getLookupString(); if (!processedNames.contains(lookupString)) { set.addElement(lookup); processedNames.add(lookupString); } } } @Nullable private static LookupElement createLookupElement(@NotNull PsiElement o, @NotNull ResolveState state, boolean forTypes, boolean vendoringEnabled) { if (o instanceof GoNamedElement && !((GoNamedElement)o).isBlank() || o instanceof GoImportSpec && !((GoImportSpec)o).isDot()) { if (o instanceof GoImportSpec) { return GoCompletionUtil.createPackageLookupElement((GoImportSpec)o, state.get(GoReferenceBase.ACTUAL_NAME), vendoringEnabled); } else if (o instanceof GoNamedSignatureOwner && ((GoNamedSignatureOwner)o).getName() != null) { String name = ((GoNamedSignatureOwner)o).getName(); if (name != null) { return GoCompletionUtil.createFunctionOrMethodLookupElement((GoNamedSignatureOwner)o, name, null, GoCompletionUtil.FUNCTION_PRIORITY); } } else if (o instanceof GoTypeSpec) { return forTypes ? GoCompletionUtil.createTypeLookupElement((GoTypeSpec)o) : GoCompletionUtil.createTypeConversionLookupElement((GoTypeSpec)o); } else if (o instanceof PsiDirectory) { return GoCompletionUtil.createPackageLookupElement(((PsiDirectory)o).getName(), (PsiDirectory)o, o, vendoringEnabled, true); } else if (o instanceof GoLabelDefinition) { String name = ((GoLabelDefinition)o).getName(); if (name != null) return GoCompletionUtil.createLabelLookupElement((GoLabelDefinition)o, name); } else if (o instanceof GoFieldDefinition) { return GoCompletionUtil.createFieldLookupElement((GoFieldDefinition)o); } else { return GoCompletionUtil.createVariableLikeLookupElement((GoNamedElement)o); } } return null; } private static class MyGoScopeProcessor extends GoScopeProcessor { @NotNull private final CompletionResultSet myResult; private final boolean myForTypes; private final boolean myVendoringEnabled; private final Set myProcessedNames = ContainerUtil.newHashSet(); public MyGoScopeProcessor(@NotNull CompletionResultSet result, @NotNull PsiFile originalFile, boolean forTypes) { myResult = result; myForTypes = forTypes; myVendoringEnabled = GoVendoringUtil.isVendoringEnabled(ModuleUtilCore.findModuleForPsiElement(originalFile)); } @Override public boolean execute(@NotNull PsiElement o, @NotNull ResolveState state) { if (accept(o)) { addElement(o, state, myForTypes, myVendoringEnabled, myProcessedNames, myResult); } return true; } protected boolean accept(@NotNull PsiElement e) { return true; } @Override public boolean isCompletion() { return true; } } } ================================================ FILE: src/com/goide/completion/GoStructLiteralCompletion.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.psi.PsiElement; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Set; class GoStructLiteralCompletion { /** * Describes struct literal completion variants that should be suggested. */ enum Variants { /** * Only struct field names should be suggested. * Indicates that field:value initializers are used in this struct literal. * For example, {@code Struct{field1: "", caret}}. */ FIELD_NAME_ONLY, /** * Only values should be suggested. * Indicates that value initializers are used in this struct literal. * For example, {@code Struct{"", caret}}. */ VALUE_ONLY, /** * Both struct field names and values should be suggested. * Indicates that there's no reliable way to determine whether field:value or value initializers are used. * Example 1: {@code Struct{caret}}. * Example 2: {@code Struct{field1:"", "", caret}} */ BOTH, /** * Indicates that struct literal completion should not be available. */ NONE } @NotNull static Variants allowedVariants(@Nullable GoReferenceExpression structFieldReference) { GoValue value = parent(structFieldReference, GoValue.class); GoElement element = parent(value, GoElement.class); if (element != null && element.getKey() != null) { return Variants.NONE; } GoType type = GoPsiImplUtil.getLiteralType(element, true); if (!(type instanceof GoStructType)) { return Variants.NONE; } boolean hasValueInitializers = false; boolean hasFieldValueInitializers = false; GoLiteralValue literalValue = parent(element, GoLiteralValue.class); List fieldInitializers = literalValue != null ? literalValue.getElementList() : Collections.emptyList(); for (GoElement initializer : fieldInitializers) { if (initializer == element) { continue; } PsiElement colon = initializer.getColon(); hasFieldValueInitializers |= colon != null; hasValueInitializers |= colon == null; } return hasFieldValueInitializers && !hasValueInitializers ? Variants.FIELD_NAME_ONLY : !hasFieldValueInitializers && hasValueInitializers ? Variants.VALUE_ONLY : Variants.BOTH; } @NotNull static Set alreadyAssignedFields(@Nullable GoLiteralValue literal) { if (literal == null) { return Collections.emptySet(); } return ContainerUtil.map2SetNotNull(literal.getElementList(), element -> { GoKey key = element.getKey(); GoFieldName fieldName = key != null ? key.getFieldName() : null; PsiElement identifier = fieldName != null ? fieldName.getIdentifier() : null; return identifier != null ? identifier.getText() : null; }); } @Contract("null,_->null") private static T parent(@Nullable PsiElement of, @NotNull Class parentClass) { return ObjectUtils.tryCast(of != null ? of.getParent() : null, parentClass); } } ================================================ FILE: src/com/goide/completion/GoTestFunctionCompletionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoConstants; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.runconfig.testing.GoTestFunctionType; import com.goide.runconfig.testing.frameworks.gotest.GotestGenerateAction; import com.goide.sdk.GoPackageUtil; import com.goide.stubs.index.GoFunctionIndex; import com.goide.stubs.index.GoIdFilter; import com.goide.stubs.index.GoMethodIndex; import com.goide.stubs.types.GoMethodDeclarationStubElementType; import com.goide.util.GoUtil; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.completion.impl.CamelHumpMatcher; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ProcessingContext; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IdFilter; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Set; public class GoTestFunctionCompletionProvider extends CompletionProvider { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { Project project = parameters.getPosition().getProject(); PsiFile file = parameters.getOriginalFile(); PsiDirectory containingDirectory = file.getContainingDirectory(); if (file instanceof GoFile && containingDirectory != null) { CompletionResultSet resultSet = result.withPrefixMatcher(new CamelHumpMatcher(result.getPrefixMatcher().getPrefix(), false)); Collection allPackageFunctionNames = collectAllFunctionNames(containingDirectory); Set allTestFunctionNames = collectAllTestNames(allPackageFunctionNames, project, (GoFile)file); String fileNameWithoutTestPrefix = StringUtil.trimEnd(file.getName(), GoConstants.TEST_SUFFIX_WITH_EXTENSION) + ".go"; GlobalSearchScope packageScope = GoPackageUtil.packageScope(containingDirectory, ((GoFile)file).getCanonicalPackageName()); GlobalSearchScope scope = new GoUtil.ExceptTestsScope(packageScope); IdFilter idFilter = GoIdFilter.getFilesFilter(scope); for (String functionName : allPackageFunctionNames) { GoFunctionIndex.process(functionName, project, scope, idFilter, declaration -> { addVariants(declaration, functionName, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet); return false; }); } Collection methodKeys = ContainerUtil.newTroveSet(); StubIndex.getInstance().processAllKeys(GoMethodIndex.KEY, new CancellableCollectProcessor<>(methodKeys), scope, idFilter); for (String key : methodKeys) { Processor processor = declaration -> { GoMethodDeclarationStubElementType.calcTypeText(declaration); String typeText = key.substring(Math.min(key.indexOf('.') + 1, key.length())); String methodName = declaration.getName(); if (methodName != null) { if (!declaration.isPublic() || declaration.isBlank()) { return true; } String lookupString = !typeText.isEmpty() ? StringUtil.capitalize(typeText) + "_" + methodName : methodName; addVariants(declaration, lookupString, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet); } return true; }; GoMethodIndex.process(key, project, scope, idFilter, processor); } } } private static void addVariants(@NotNull GoFunctionOrMethodDeclaration declaration, @NotNull String functionName, @NotNull String fileNameWithoutTestPrefix, @NotNull Set allTestFunctionNames, @NotNull CompletionResultSet resultSet) { int priority = fileNameWithoutTestPrefix.equals(declaration.getContainingFile().getName()) ? 5 : 0; addLookupElement(GoConstants.TEST_PREFIX + functionName, priority, allTestFunctionNames, resultSet); addLookupElement(GoConstants.BENCHMARK_PREFIX + functionName, priority, allTestFunctionNames, resultSet); addLookupElement(GoConstants.EXAMPLE_PREFIX + functionName, priority, allTestFunctionNames, resultSet); } private static void addLookupElement(@NotNull String lookupString, int initialPriority, @NotNull Set allTestFunctionNames, @NotNull CompletionResultSet result) { int priority = initialPriority; if (allTestFunctionNames.contains(lookupString)) { priority -= 5; lookupString = UniqueNameGenerator.generateUniqueName(lookupString, allTestFunctionNames); } result.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(lookupString) .withInsertHandler(GenerateTestInsertHandler.INSTANCE), priority)); } @NotNull private static Set collectAllFunctionNames(@NotNull PsiDirectory directory) { GlobalSearchScope packageScope = GoPackageUtil.packageScope(directory, null); IdFilter packageIdFilter = GoIdFilter.getFilesFilter(packageScope); Set result = ContainerUtil.newHashSet(); StubIndex.getInstance().processAllKeys(GoFunctionIndex.KEY, new CancellableCollectProcessor(result) { @Override protected boolean accept(String s) { return !"_".equals(s) && StringUtil.isCapitalized(s); } }, packageScope, packageIdFilter); return result; } @NotNull private static Set collectAllTestNames(@NotNull Collection names, @NotNull Project project, @NotNull GoFile file) { Set result = ContainerUtil.newHashSet(); GlobalSearchScope packageScope = GoPackageUtil.packageScope(file); GlobalSearchScope scope = new GoUtil.TestsScope(packageScope); IdFilter idFilter = GoIdFilter.getFilesFilter(packageScope); for (String name : names) { if (GoTestFunctionType.fromName(name) != null) { GoFunctionIndex.process(name, project, scope, idFilter, declaration -> { result.add(name); return false; }); } } return result; } private static class GenerateTestInsertHandler implements InsertHandler { public static final InsertHandler INSTANCE = new GenerateTestInsertHandler(); @Override public void handleInsert(InsertionContext context, LookupElement item) { PsiElement elementAt = context.getFile().findElementAt(context.getStartOffset()); GoFunctionOrMethodDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(elementAt, GoFunctionOrMethodDeclaration.class); if (declaration != null) { GoTestFunctionType testingType = GoTestFunctionType.fromName(declaration.getName()); if (testingType != null) { String testingQualifier = null; if (testingType.getParamType() != null) { testingQualifier = GotestGenerateAction.importTestingPackageIfNeeded(declaration.getContainingFile()); } GoBlock block = declaration.getBlock(); if (block == null) { block = (GoBlock)declaration.add(GoElementFactory.createBlock(context.getProject())); } else if (block.getStatementList().isEmpty()) { block = (GoBlock)block.replace(GoElementFactory.createBlock(context.getProject())); } GoSignature newSignature = GoElementFactory.createFunctionSignatureFromText(context.getProject(), testingType.getSignature(testingQualifier)); GoSignature signature = declaration.getSignature(); if (signature == null) { declaration.addBefore(newSignature, block); } else if (signature.getParameters().getParameterDeclarationList().isEmpty()) { signature.replace(newSignature); } Document document = context.getDocument(); PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document); GoStatement firstStatement = ContainerUtil.getFirstItem(block.getStatementList()); if (firstStatement != null) { context.getEditor().getCaretModel().moveToOffset(firstStatement.getTextRange().getStartOffset()); } else { PsiElement lbrace = block.getLbrace(); PsiElement rbrace = block.getRbrace(); int lbraceEndOffset = lbrace.getTextRange().getEndOffset(); int startLine = document.getLineNumber(lbraceEndOffset); int endLine = rbrace != null ? document.getLineNumber(rbrace.getTextRange().getStartOffset()) : startLine; int lineDiff = endLine - startLine; if (lineDiff < 2) { document.insertString(lbraceEndOffset, StringUtil.repeat("\n", 2 - lineDiff)); } int offsetToMove = document.getLineStartOffset(startLine + 1); context.getEditor().getCaretModel().moveToOffset(offsetToMove); CodeStyleManager.getInstance(context.getProject()).adjustLineIndent(document, offsetToMove); } } } } } } ================================================ FILE: src/com/goide/completion/SingleCharInsertHandler.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.completion.BasicInsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import org.jetbrains.annotations.NotNull; public class SingleCharInsertHandler extends BasicInsertHandler { private final char myChar; public SingleCharInsertHandler(char aChar) { myChar = aChar; } @Override public void handleInsert(@NotNull InsertionContext context, LookupElement item) { Editor editor = context.getEditor(); int tailOffset = context.getTailOffset(); Document document = editor.getDocument(); context.commitDocument(); boolean staysAtChar = document.getTextLength() > tailOffset && document.getCharsSequence().charAt(tailOffset) == myChar; context.setAddCompletionChar(false); if (!staysAtChar) { document.insertString(tailOffset, String.valueOf(myChar)); } editor.getCaretModel().moveToOffset(tailOffset + 1); AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(editor); } } ================================================ FILE: src/com/goide/configuration/GoBuildTagsUI.form ================================================
    ================================================ FILE: src/com/goide/configuration/GoBuildTagsUI.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.GoConstants; import com.goide.project.GoBuildTargetSettings; import com.goide.sdk.GoSdkService; import com.goide.util.GoUtil; import com.intellij.ProjectTopics; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.ModuleRootAdapter; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.MutableCollectionComboBoxModel; import com.intellij.ui.RawCommandLineEditor; import com.intellij.util.ArrayUtil; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Collection; import java.util.List; public class GoBuildTagsUI implements Disposable { private static final String ENABLED = "Enabled"; private static final String DISABLED = "Disabled"; private JPanel myPanel; private ComboBox myOSCombo; private ComboBox myArchCombo; private ComboBox myGoVersionCombo; private ComboBox myCompilerCombo; private ComboBox myCgoCombo; private RawCommandLineEditor myCustomTagsField; @SuppressWarnings("unused") private JTextPane myDescriptionPane; @NotNull private final MutableCollectionComboBoxModel myCgoComboModel; @NotNull private final String myDefaultOSValue; @NotNull private final String myDefaultArchValue; @NotNull private String myDefaultCgo; @NotNull private String myDefaultGoVersion = ""; @SuppressWarnings("unchecked") public GoBuildTagsUI() { myPanel.setBorder(IdeBorderFactory.createTitledBorder("Build tags")); myDefaultOSValue = "Default (" + GoUtil.systemOS() + ")"; myDefaultArchValue = "Default (" + GoUtil.systemArch() + ")"; myDefaultCgo = "Default (" + cgo(GoUtil.systemCgo(myDefaultOSValue, myDefaultArchValue)) + ")"; myCustomTagsField.setDialogCaption("Custom Build Tags"); myOSCombo.setModel(createModel(GoConstants.KNOWN_OS, myDefaultOSValue)); myArchCombo.setModel(createModel(GoConstants.KNOWN_ARCH, myDefaultArchValue)); myCgoComboModel = createModel(ContainerUtil.newArrayList(ENABLED, DISABLED), myDefaultCgo); myCgoCombo.setModel(myCgoComboModel); myCompilerCombo.setModel(createModel(GoConstants.KNOWN_COMPILERS, GoBuildTargetSettings.ANY_COMPILER)); ActionListener updateCgoListener = event -> { String selected = StringUtil.notNullize(myCgoComboModel.getSelected(), myDefaultCgo); String oldDefault = myDefaultCgo; String os = expandDefault(selected(myOSCombo, myDefaultOSValue), GoUtil.systemOS()); String arch = expandDefault(selected(myArchCombo, myDefaultArchValue), GoUtil.systemArch()); myDefaultCgo = "Default (" + cgo(GoUtil.systemCgo(os, arch)) + ")"; myCgoComboModel.update(ContainerUtil.newArrayList(myDefaultCgo, ENABLED, DISABLED)); myCgoComboModel.setSelectedItem(oldDefault.equals(selected) ? myDefaultCgo : selected); }; myOSCombo.addActionListener(updateCgoListener); myArchCombo.addActionListener(updateCgoListener); } public void initPanel(@NotNull Module module) { if (!module.isDisposed()) { MessageBusConnection connection = module.getMessageBus().connect(this); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { initComboValues(module); } }); initComboValues(module); } } private void initComboValues(@NotNull Module module) { if (!module.isDisposed()) { String sdkVersion = GoSdkService.getInstance(module.getProject()).getSdkVersion(module); myDefaultGoVersion = "Project SDK (" + StringUtil.notNullize(sdkVersion, "any") + ")"; //noinspection unchecked myGoVersionCombo.setModel(createModel(GoConstants.KNOWN_VERSIONS, myDefaultGoVersion)); } } @NotNull private String selectedCompiler() { Object item = myCompilerCombo.getSelectedItem(); return item instanceof String ? (String)item : GoBuildTargetSettings.ANY_COMPILER; } @NotNull private String[] selectedCustomTags() { return ArrayUtil.toStringArray(StringUtil.split(myCustomTagsField.getText(), " ")); } @NotNull private ThreeState selectedCgo() { String string = myCgoComboModel.getSelected(); if (ENABLED.equals(string)) { return ThreeState.YES; } if (DISABLED.equals(string)) { return ThreeState.NO; } return ThreeState.UNSURE; } @NotNull private static String selected(@NotNull ComboBox comboBox, @NotNull String defaultValue) { Object item = comboBox.getSelectedItem(); if (item instanceof String) { return defaultValue.equals(item) ? GoBuildTargetSettings.DEFAULT : (String)item; } return GoBuildTargetSettings.DEFAULT; } @NotNull private static String expandDefault(@NotNull String value, @NotNull String defaultValue) { return GoBuildTargetSettings.DEFAULT.equals(value) ? defaultValue : value; } @NotNull private static MutableCollectionComboBoxModel createModel(@NotNull Collection values, @NotNull String defaultValue) { List items = ContainerUtil.newArrayList(defaultValue); items.addAll(ContainerUtil.sorted(values)); return new MutableCollectionComboBoxModel<>(items, defaultValue); } public boolean isModified(@NotNull GoBuildTargetSettings buildTargetSettings) { return !buildTargetSettings.os.equals(selected(myOSCombo, myDefaultOSValue)) || !buildTargetSettings.arch.equals(selected(myArchCombo, myDefaultArchValue)) || !buildTargetSettings.goVersion.equals(selected(myGoVersionCombo, myDefaultGoVersion)) || buildTargetSettings.cgo != selectedCgo() || !buildTargetSettings.compiler.equals(selectedCompiler()) || !Arrays.equals(buildTargetSettings.customFlags, selectedCustomTags()); } public void apply(@NotNull GoBuildTargetSettings buildTargetSettings) { buildTargetSettings.os = selected(myOSCombo, myDefaultOSValue); buildTargetSettings.arch = selected(myArchCombo, myDefaultArchValue); buildTargetSettings.goVersion = selected(myGoVersionCombo, myDefaultGoVersion); buildTargetSettings.compiler = selectedCompiler(); buildTargetSettings.cgo = selectedCgo(); buildTargetSettings.customFlags = selectedCustomTags(); } public void reset(@NotNull GoBuildTargetSettings buildTargetSettings) { myOSCombo.setSelectedItem(expandDefault(buildTargetSettings.os, myDefaultOSValue)); myArchCombo.setSelectedItem(expandDefault(buildTargetSettings.arch, myDefaultArchValue)); myGoVersionCombo.setSelectedItem(expandDefault(buildTargetSettings.goVersion, myDefaultGoVersion)); myCgoCombo.setSelectedItem(expandDefault(cgo(buildTargetSettings.cgo), myDefaultCgo)); myCompilerCombo.setSelectedItem(buildTargetSettings.compiler); myCustomTagsField.setText(StringUtil.join(buildTargetSettings.customFlags, " ")); } @NotNull public JPanel getPanel() { return myPanel; } @Override public void dispose() { UIUtil.dispose(myPanel); UIUtil.dispose(myOSCombo); UIUtil.dispose(myArchCombo); UIUtil.dispose(myGoVersionCombo); UIUtil.dispose(myCompilerCombo); UIUtil.dispose(myCgoCombo); UIUtil.dispose(myCustomTagsField); } @NotNull private static String cgo(@NotNull ThreeState threeState) { if (threeState == ThreeState.YES) { return ENABLED; } if (threeState == ThreeState.NO) { return DISABLED; } return GoBuildTargetSettings.DEFAULT; } private void createUIComponents() { myDescriptionPane = GoUIUtil.createDescriptionPane(); } } ================================================ FILE: src/com/goide/configuration/GoConfigurableProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.GoConstants; import com.goide.codeInsight.imports.GoAutoImportConfigurable; import com.goide.sdk.GoSdkService; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurableProvider; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.options.UnnamedConfigurable; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoConfigurableProvider extends ConfigurableProvider { @NotNull private final Project myProject; public GoConfigurableProvider(@NotNull Project project) { myProject = project; } @Nullable @Override public Configurable createConfigurable() { Configurable projectSettingsConfigurable = new GoProjectSettingsConfigurable(myProject); Configurable librariesConfigurable = new GoLibrariesConfigurableProvider(myProject).createConfigurable(); Configurable sdkConfigurable = GoSdkService.getInstance(myProject).createSdkConfigurable(); Configurable autoImportConfigurable = new GoAutoImportConfigurable(myProject, false); return sdkConfigurable != null ? new GoCompositeConfigurable(sdkConfigurable, projectSettingsConfigurable, librariesConfigurable, autoImportConfigurable) : new GoCompositeConfigurable(projectSettingsConfigurable, librariesConfigurable, autoImportConfigurable); } private static class GoCompositeConfigurable extends SearchableConfigurable.Parent.Abstract { private Configurable[] myConfigurables; public GoCompositeConfigurable(Configurable... configurables) { myConfigurables = configurables; } @Override protected Configurable[] buildConfigurables() { return myConfigurables; } @NotNull @Override public String getId() { return "go"; } @Nls @Override public String getDisplayName() { return GoConstants.GO; } @Nullable @Override public String getHelpTopic() { return null; } @Override public void disposeUIResources() { super.disposeUIResources(); myConfigurables = null; } } public static class GoProjectSettingsConfigurable extends GoModuleAwareConfigurable { public GoProjectSettingsConfigurable(@NotNull Project project) { super(project, "Project Settings", null); } @NotNull @Override protected UnnamedConfigurable createModuleConfigurable(Module module) { return new GoModuleSettingsConfigurable(module, false); } } } ================================================ FILE: src/com/goide/configuration/GoLibrariesConfigurable.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoLibrariesService; import com.intellij.openapi.fileChooser.FileChooserDialog; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.ui.CollectionListModel; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBList; import com.intellij.util.IconUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import static com.intellij.openapi.fileChooser.FileChooserDescriptorFactory.createMultipleFoldersDescriptor; public class GoLibrariesConfigurable implements SearchableConfigurable, Configurable.NoScroll { @NotNull private final String myDisplayName; private final GoLibrariesService myLibrariesService; private final String[] myReadOnlyPaths; private final JBCheckBox myUseEnvGoPathCheckBox = new JBCheckBox("Use GOPATH that's defined in system environment"); private final JPanel myPanel = new JPanel(new BorderLayout()); private final CollectionListModel myListModel = new CollectionListModel<>(); public GoLibrariesConfigurable(@NotNull String displayName, @NotNull GoLibrariesService librariesService, String... urls) { myDisplayName = displayName; myLibrariesService = librariesService; myReadOnlyPaths = urls; JBList filesList = new JBList(myListModel); filesList.setCellRenderer(new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) { ListItem item = (ListItem)value; String url = item.url; if (item.readOnly) { append("[GOPATH] ", SimpleTextAttributes.GRAY_ATTRIBUTES); } VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file != null) { append(file.getPresentableUrl(), item.readOnly ? SimpleTextAttributes.GRAY_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES); setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, null)); } else { append(VfsUtilCore.urlToPath(url), SimpleTextAttributes.ERROR_ATTRIBUTES); } } }); ToolbarDecorator decorator = ToolbarDecorator.createDecorator(filesList) .setAddAction(button -> { FileChooserDialog fileChooser = FileChooserFactory.getInstance() .createFileChooser(createMultipleFoldersDescriptor(), null, filesList); VirtualFile fileToSelect = null; ListItem lastItem = ContainerUtil.getLastItem(myListModel.getItems()); if (lastItem != null) { fileToSelect = VirtualFileManager.getInstance().findFileByUrl(lastItem.url); } VirtualFile[] newDirectories = fileChooser.choose(null, fileToSelect); if (newDirectories.length > 0) { for (VirtualFile newDirectory : newDirectories) { String newDirectoryUrl = newDirectory.getUrl(); boolean alreadyAdded = false; for (ListItem item : myListModel.getItems()) { if (newDirectoryUrl.equals(item.url) && !item.readOnly) { filesList.clearSelection(); filesList.setSelectedValue(item, true); scrollToSelection(filesList); alreadyAdded = true; break; } } if (!alreadyAdded) { myListModel.add(new ListItem(newDirectoryUrl, false)); } } } }) .setRemoveActionUpdater(event -> { for (Object selectedValue : filesList.getSelectedValuesList()) { if (((ListItem)selectedValue).readOnly) { return false; } } return true; }) .setRemoveAction(button -> { for (Object selectedValue : filesList.getSelectedValuesList()) { myListModel.remove((ListItem)selectedValue); } }); myPanel.add(decorator.createPanel(), BorderLayout.CENTER); if (librariesService instanceof GoApplicationLibrariesService) { myUseEnvGoPathCheckBox.addActionListener(event -> { if (myUseEnvGoPathCheckBox.isSelected()) { addReadOnlyPaths(); } else { removeReadOnlyPaths(); } }); myPanel.add(myUseEnvGoPathCheckBox, BorderLayout.SOUTH); } } private static void scrollToSelection(JList list) { int selectedRow = list.getSelectedIndex(); if (selectedRow >= 0) { list.scrollRectToVisible(list.getCellBounds(selectedRow, 0)); } } @Nullable @Override public JComponent createComponent() { return myPanel; } @Override public boolean isModified() { return !getUserDefinedUrls().equals(myLibrariesService.getLibraryRootUrls()) || myLibrariesService instanceof GoApplicationLibrariesService && ((GoApplicationLibrariesService)myLibrariesService).isUseGoPathFromSystemEnvironment() != myUseEnvGoPathCheckBox.isSelected(); } @Override public void apply() throws ConfigurationException { myLibrariesService.setLibraryRootUrls(getUserDefinedUrls()); if (myLibrariesService instanceof GoApplicationLibrariesService) { ((GoApplicationLibrariesService)myLibrariesService).setUseGoPathFromSystemEnvironment(myUseEnvGoPathCheckBox.isSelected()); } } @Override public void reset() { myListModel.removeAll(); resetLibrariesFromEnvironment(); for (String url : myLibrariesService.getLibraryRootUrls()) { myListModel.add(new ListItem(url, false)); } } private void resetLibrariesFromEnvironment() { if (myLibrariesService instanceof GoApplicationLibrariesService) { myUseEnvGoPathCheckBox.setSelected(((GoApplicationLibrariesService)myLibrariesService).isUseGoPathFromSystemEnvironment()); if (((GoApplicationLibrariesService)myLibrariesService).isUseGoPathFromSystemEnvironment()) { addReadOnlyPaths(); } else { removeReadOnlyPaths(); } } } private void addReadOnlyPaths() { for (String url : myReadOnlyPaths) { myListModel.add(new ListItem(url, true)); } } private void removeReadOnlyPaths() { List toRemove = myListModel.getItems().stream().filter(item -> item.readOnly).collect(Collectors.toList()); for (ListItem item : toRemove) { myListModel.remove(item); } } @Override public void disposeUIResources() { UIUtil.dispose(myUseEnvGoPathCheckBox); UIUtil.dispose(myPanel); myListModel.removeAll(); } @NotNull @Nls @Override public String getDisplayName() { return myDisplayName; } @Nullable @Override public String getHelpTopic() { return null; } @NotNull private Collection getUserDefinedUrls() { Collection libraryUrls = ContainerUtil.newArrayList(); for (ListItem item : myListModel.getItems()) { if (!item.readOnly) { libraryUrls.add(item.url); } } return libraryUrls; } @NotNull @Override public String getId() { return "go.libraries"; } @Nullable @Override public Runnable enableSearch(String option) { return null; } private static class ListItem { final boolean readOnly; final String url; public ListItem(String url, boolean readOnly) { this.readOnly = readOnly; this.url = url; } } } ================================================ FILE: src/com/goide/configuration/GoLibrariesConfigurableProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoModuleLibrariesService; import com.goide.project.GoProjectLibrariesService; import com.goide.sdk.GoSdkUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.HideableDecorator; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.List; import java.util.Locale; public class GoLibrariesConfigurableProvider extends ConfigurableProvider { @NotNull private final Project myProject; public GoLibrariesConfigurableProvider(@NotNull Project project) { myProject = project; } @Nullable @Override public Configurable createConfigurable() { return createConfigurable(false); } @Nullable private Configurable createConfigurable(boolean dialogMode) { return new CompositeConfigurable() { @Nullable @Override public JComponent createComponent() { List configurables = getConfigurables(); Collection hideableDecorators = ContainerUtil.newHashSet(); GridLayoutManager layoutManager = new GridLayoutManager(configurables.size() + 1, 1, new Insets(0, 0, 0, 0), -1, -1); JPanel rootPanel = new JPanel(layoutManager); Spacer spacer = new Spacer(); rootPanel.add(spacer, new GridConstraints(configurables.size(), 0, 1, 1, GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null)); for (int i = 0; i < configurables.size(); i++) { UnnamedConfigurable configurable = configurables.get(i); JComponent configurableComponent = configurable.createComponent(); assert configurableComponent != null; JPanel hideablePanel = new JPanel(new BorderLayout()); rootPanel.add(hideablePanel, configurableConstrains(i)); if (configurable instanceof Configurable) { String displayName = ((Configurable)configurable).getDisplayName(); ListenableHideableDecorator decorator = new ListenableHideableDecorator(hideablePanel, displayName, configurableComponent); decorator.addListener(new MyHideableDecoratorListener(layoutManager, hideablePanel, spacer, hideableDecorators, configurableExpandedPropertyKey((Configurable)configurable) )); hideableDecorators.add(decorator); decorator.setOn(isConfigurableExpanded(i, (Configurable)configurable)); } } if (dialogMode) { rootPanel.setPreferredSize(new Dimension(400, 600)); } rootPanel.revalidate(); return rootPanel; } @NotNull @Override protected List createConfigurables() { List result = ContainerUtil.newArrayList(); String[] urlsFromEnv = ContainerUtil.map2Array(GoSdkUtil.getGoPathsRootsFromEnvironment(), String.class, VirtualFile::getUrl); result.add(new GoLibrariesConfigurable("Global libraries", GoApplicationLibrariesService.getInstance(), urlsFromEnv)); if (!myProject.isDefault()) { result.add(new GoLibrariesConfigurable("Project libraries", GoProjectLibrariesService.getInstance(myProject))); result.add(new GoModuleAwareConfigurable(myProject, "Module libraries", null) { @NotNull @Override protected UnnamedConfigurable createModuleConfigurable(@NotNull Module module) { return new GoLibrariesConfigurable("Module libraries", GoModuleLibrariesService.getInstance(module)); } }); } return result; } @NotNull @Nls @Override public String getDisplayName() { return "Go Libraries"; } @Nullable @Override public String getHelpTopic() { return null; } @NotNull private GridConstraints configurableConstrains(int i) { return new GridConstraints(i, 0, 1, 1, GridConstraints.ANCHOR_NORTHEAST, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_WANT_GROW | GridConstraints.SIZEPOLICY_CAN_SHRINK, GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_CAN_SHRINK, null, null, null); } private boolean isConfigurableExpanded(int index, @NotNull Configurable configurable) { return PropertiesComponent.getInstance(myProject).getBoolean(configurableExpandedPropertyKey(configurable), index < 2); } private void storeConfigurableExpandedProperty(@NotNull String storeKey, @NotNull Boolean value) { PropertiesComponent.getInstance(myProject).setValue(storeKey, value.toString()); } private String configurableExpandedPropertyKey(@NotNull Configurable configurable) { String keyName = "configurable " + configurable.getDisplayName() + " is expanded".toLowerCase(Locale.US); return StringUtil.replaceChar(keyName, ' ', '.'); } class MyHideableDecoratorListener extends ListenableHideableDecorator.MyListener { private final GridLayoutManager myLayoutManager; private final JPanel myHideablePanel; @NotNull private final String myStoreKey; private final Spacer mySpacer; private final Collection myHideableDecorators; public MyHideableDecoratorListener(@NotNull GridLayoutManager layoutManager, @NotNull JPanel hideablePanel, @NotNull Spacer spacer, @NotNull Collection hideableDecorators, @NotNull String storeKey) { myLayoutManager = layoutManager; myHideablePanel = hideablePanel; myStoreKey = storeKey; mySpacer = spacer; myHideableDecorators = hideableDecorators; } @Override public void on() { GridConstraints c = myLayoutManager.getConstraintsForComponent(myHideablePanel); c.setVSizePolicy(c.getVSizePolicy() | GridConstraints.SIZEPOLICY_WANT_GROW); GridConstraints spacerConstraints = myLayoutManager.getConstraintsForComponent(mySpacer); spacerConstraints.setVSizePolicy(spacerConstraints.getVSizePolicy() & ~GridConstraints.SIZEPOLICY_WANT_GROW); storeConfigurableExpandedProperty(myStoreKey, Boolean.TRUE); } @Override public void beforeOff() { GridConstraints c = myLayoutManager.getConstraintsForComponent(myHideablePanel); c.setVSizePolicy(c.getVSizePolicy() & ~GridConstraints.SIZEPOLICY_WANT_GROW); } @Override public void afterOff() { if (isAllDecoratorsCollapsed()) { GridConstraints c = myLayoutManager.getConstraintsForComponent(mySpacer); c.setVSizePolicy(c.getVSizePolicy() | GridConstraints.SIZEPOLICY_WANT_GROW); } storeConfigurableExpandedProperty(myStoreKey, Boolean.FALSE); } private boolean isAllDecoratorsCollapsed() { for (HideableDecorator hideableDecorator : myHideableDecorators) { if (hideableDecorator.isExpanded()) { return false; } } return true; } } }; } public static void showModulesConfigurable(@NotNull Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!project.isDisposed()) { Configurable configurable = new GoLibrariesConfigurableProvider(project).createConfigurable(true); ShowSettingsUtil.getInstance().editConfigurable(project, configurable); } } } ================================================ FILE: src/com/goide/configuration/GoModuleAwareConfigurable.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.sdk.GoSdkService; import com.intellij.application.options.ModuleAwareProjectConfigurable; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public abstract class GoModuleAwareConfigurable extends ModuleAwareProjectConfigurable { public GoModuleAwareConfigurable(@NotNull Project project, String displayName, String helpTopic) { super(project, displayName, helpTopic); } @Override protected boolean isSuitableForModule(@NotNull Module module) { if (module.isDisposed()) { return false; } Project project = module.getProject(); return !project.isDisposed() && GoSdkService.getInstance(project).isGoModule(module); } } ================================================ FILE: src/com/goide/configuration/GoModuleEditorsProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.GoModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleConfigurationEditor; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ui.configuration.*; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.List; public class GoModuleEditorsProvider implements ModuleConfigurationEditorProvider { @Override public ModuleConfigurationEditor[] createEditors(@NotNull ModuleConfigurationState state) { ModifiableRootModel rootModel = state.getRootModel(); Module module = rootModel.getModule(); if (!(ModuleType.get(module) instanceof GoModuleType)) { return ModuleConfigurationEditor.EMPTY; } String moduleName = module.getName(); List editors = ContainerUtil.newArrayList(); editors.add(new ContentEntriesEditor(moduleName, state)); editors.add(new OutputEditorEx(state)); editors.add(new ClasspathEditor(state)); return editors.toArray(new ModuleConfigurationEditor[editors.size()]); } static class OutputEditorEx extends OutputEditor { protected OutputEditorEx(ModuleConfigurationState state) { super(state); } @Override protected JComponent createComponentImpl() { JComponent component = super.createComponentImpl(); component.remove(1); // todo: looks ugly return component; } } } ================================================ FILE: src/com/goide/configuration/GoModuleSettingsConfigurable.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.project.GoModuleSettings; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurableBase; import org.jetbrains.annotations.NotNull; public class GoModuleSettingsConfigurable extends ConfigurableBase { @NotNull private final Module myModule; private final boolean myDialogMode; public GoModuleSettingsConfigurable(@NotNull Module module, boolean dialogMode) { super("go.project.settings", "Go Project Settings", null); myModule = module; myDialogMode = dialogMode; } @NotNull @Override protected GoModuleSettings getSettings() { return GoModuleSettings.getInstance(myModule); } @Override protected GoModuleSettingsUI createUi() { return new GoModuleSettingsUI(myModule, myDialogMode); } } ================================================ FILE: src/com/goide/configuration/GoModuleSettingsUI.form ================================================
    ================================================ FILE: src/com/goide/configuration/GoModuleSettingsUI.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurableUi; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.util.Disposer; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; public class GoModuleSettingsUI implements ConfigurableUi, Disposable { private JPanel myPanel; private JPanel myBuildTagsPanel; private JPanel myVendoringPanel; private GoVendoringUI myVendoringUI; private GoBuildTagsUI myBuildTagsUI; public GoModuleSettingsUI(@NotNull Module module, boolean dialogMode) { if (dialogMode) { myPanel.setPreferredSize(new Dimension(400, -1)); } myVendoringUI.initPanel(module); myBuildTagsUI.initPanel(module); } @Override public void reset(@NotNull GoModuleSettings settings) { myBuildTagsUI.reset(settings.getBuildTargetSettings()); myVendoringUI.reset(settings); } @Override public boolean isModified(@NotNull GoModuleSettings settings) { return myVendoringUI.isModified(settings) || myBuildTagsUI.isModified(settings.getBuildTargetSettings()); } @Override public void apply(@NotNull GoModuleSettings settings) throws ConfigurationException { myVendoringUI.apply(settings); GoBuildTargetSettings newBuildTargetSettings = new GoBuildTargetSettings(); myBuildTagsUI.apply(newBuildTargetSettings); settings.setBuildTargetSettings(newBuildTargetSettings); } @NotNull @Override public JComponent getComponent() { return myPanel; } private void createUIComponents() { myVendoringUI = new GoVendoringUI(); myBuildTagsUI = new GoBuildTagsUI(); myVendoringPanel = myVendoringUI.getPanel(); myBuildTagsPanel = myBuildTagsUI.getPanel(); } @Override public void dispose() { Disposer.dispose(myVendoringUI); Disposer.dispose(myBuildTagsUI); UIUtil.dispose(myPanel); } } ================================================ FILE: src/com/goide/configuration/GoSdkConfigurable.form ================================================
    ================================================ FILE: src/com/goide/configuration/GoSdkConfigurable.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.goide.sdk.GoSmallIDEsSdkService; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.JBCardLayout; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBLabel; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ui.AsyncProcessIcon; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import java.awt.*; public class GoSdkConfigurable implements SearchableConfigurable, Configurable.NoScroll { private static final String VERSION_GETTING = "VERSION_GETTING_CARD"; private static final String VERSION_RESULT = "VERSION_RESULT_CARD"; @NotNull private final Project myProject; @NotNull private final Disposable myDisposable = Disposer.newDisposable(); @NotNull private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable); private JPanel myComponent; private TextFieldWithBrowseButton mySdkPathField; private JPanel myVersionPanel; private JBLabel myVersionLabel; private Color myDefaultLabelColor; public GoSdkConfigurable(@NotNull Project project, boolean dialogMode) { myProject = project; if (dialogMode) { myComponent.setPreferredSize(new Dimension(400, -1)); } FileChooserDescriptor chooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor().withTitle("Select GOROOT"); mySdkPathField.addBrowseFolderListener(myProject, new MyBrowseFolderListener(chooserDescriptor)); listenForPathUpdate(); Disposer.register(myDisposable, mySdkPathField); } @Override public void apply() throws ConfigurationException { ApplicationManager.getApplication().runWriteAction(() -> { if (myProject.isDefault() || myProject.isDisposed()) { return; } LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTable(myProject); Library get = table.getLibraryByName(GoSmallIDEsSdkService.LIBRARY_NAME); Library lib = get != null ? get : table.createLibrary(GoSmallIDEsSdkService.LIBRARY_NAME); Library.ModifiableModel libraryModel = lib.getModifiableModel(); String libUrl = ArrayUtil.getFirstElement(lib.getUrls(OrderRootType.CLASSES)); if (libUrl != null) { libraryModel.removeRoot(libUrl, OrderRootType.CLASSES); } String sdkPath = GoSdkUtil.adjustSdkPath(mySdkPathField.getText()); String versionString = GoSdkUtil.retrieveGoVersion(sdkPath); boolean toRemove = StringUtil.isEmpty(sdkPath) || versionString == null; if (!toRemove) { for (VirtualFile file : GoSdkUtil.getSdkDirectoriesToAttach(sdkPath, versionString)) { libraryModel.addRoot(file, OrderRootType.CLASSES); } } libraryModel.commit(); if (toRemove) { updateModules(myProject, lib, true); table.removeLibrary(lib); } table.getModifiableModel().commit(); if (!toRemove) { updateModules(myProject, lib, false); } GoSdkService.getInstance(myProject).incModificationCount(); }); } @Override public void reset() { mySdkPathField.setText(StringUtil.notNullize(GoSdkService.getInstance(myProject).getSdkHomePath(null))); } @Override public boolean isModified() { String currentPath = StringUtil.notNullize(GoSdkService.getInstance(myProject).getSdkHomePath(null)); return !GoSdkUtil.adjustSdkPath(mySdkPathField.getText()).equals(currentPath); } @NotNull @Override public String getId() { return "go.sdk"; } @Nullable @Override public Runnable enableSearch(String option) { return null; } @Nls @Override public String getDisplayName() { return "Go SDK"; } @Nullable @Override public String getHelpTopic() { return null; } @Nullable @Override public JComponent createComponent() { return myComponent; } private static void updateModules(@NotNull Project project, @NotNull Library lib, boolean remove) { Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel(); if (!remove) { if (model.findLibraryOrderEntry(lib) == null) { LibraryOrderEntry entry = model.addLibraryEntry(lib); entry.setScope(DependencyScope.PROVIDED); } } else { LibraryOrderEntry entry = model.findLibraryOrderEntry(lib); if (entry != null) { model.removeOrderEntry(entry); } } model.commit(); } } private void asyncUpdateSdkVersion(@NotNull String sdkPath) { ApplicationManager.getApplication().assertIsDispatchThread(); ((CardLayout)myVersionPanel.getLayout()).show(myVersionPanel, VERSION_GETTING); if (!myAlarm.isDisposed()) { myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { String version = GoSdkUtil.retrieveGoVersion(GoSdkUtil.adjustSdkPath(sdkPath)); ApplicationManager.getApplication().invokeLater(() -> { if (!Disposer.isDisposed(myDisposable)) { setVersion(version); } }, ModalityState.any()); }, 100); } } private void setVersion(@Nullable String version) { if (version == null) { myVersionLabel.setText("N/A"); myVersionLabel.setForeground(JBColor.RED); } else { myVersionLabel.setText(version); myVersionLabel.setForeground(myDefaultLabelColor); } ((CardLayout)myVersionPanel.getLayout()).show(myVersionPanel, VERSION_RESULT); } private void createUIComponents() { myVersionLabel = new JBLabel(); myDefaultLabelColor = myVersionLabel.getForeground(); myVersionPanel = new JPanel(new JBCardLayout()); JPanel gettingVersionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0)); AsyncProcessIcon gettingVersionIcon = new AsyncProcessIcon("Getting Go version"); gettingVersionPanel.add(gettingVersionIcon); gettingVersionPanel.add(new JLabel("Getting...")); myVersionPanel.add(gettingVersionPanel, VERSION_GETTING); myVersionPanel.add(myVersionLabel, VERSION_RESULT); setVersion(null); } @Override public void disposeUIResources() { UIUtil.dispose(myVersionLabel); UIUtil.dispose(myVersionPanel); UIUtil.dispose(myComponent); myVersionLabel = null; myVersionPanel = null; myDefaultLabelColor = null; Disposer.dispose(myDisposable); } private class MyBrowseFolderListener extends ComponentWithBrowseButton.BrowseFolderActionListener { public MyBrowseFolderListener(@NotNull FileChooserDescriptor descriptor) { super("Select Go SDK Path", "", mySdkPathField, myProject, descriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT); } @Nullable @Override protected VirtualFile getInitialFile() { return ObjectUtils.chooseNotNull(super.getInitialFile(), GoSdkUtil.suggestSdkDirectory()); } } private void listenForPathUpdate() { JTextField textField = mySdkPathField.getTextField(); Ref prevPathRef = Ref.create(StringUtil.notNullize(textField.getText())); textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { String sdkPath = StringUtil.notNullize(textField.getText()); String prevPath = prevPathRef.get(); if (!prevPath.equals(sdkPath)) { asyncUpdateSdkVersion(sdkPath); prevPathRef.set(sdkPath); } } }); } } ================================================ FILE: src/com/goide/configuration/GoUIUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.intellij.ui.BrowserHyperlinkListener; import com.intellij.ui.ColorUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.text.html.HTMLEditorKit; import java.awt.*; public class GoUIUtil { private GoUIUtil() {} @NotNull public static JTextPane createDescriptionPane() { JTextPane result = new JTextPane(); result.addHyperlinkListener(new BrowserHyperlinkListener()); result.setContentType("text/html"); Font descriptionFont = UIUtil.getLabelFont(UIUtil.FontSize.SMALL); HTMLEditorKit editorKit = UIUtil.getHTMLEditorKit(); editorKit.getStyleSheet().addRule("body, p {" + "color:#" + ColorUtil.toHex(UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)) + ";" + "font-family:" + descriptionFont.getFamily() + ";" + "font-size:" + descriptionFont.getSize() + "pt;}"); result.setHighlighter(null); result.setEditorKit(editorKit); return result; } } ================================================ FILE: src/com/goide/configuration/GoVendoringUI.form ================================================
    ================================================ FILE: src/com/goide/configuration/GoVendoringUI.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.goide.project.GoModuleSettings; import com.goide.project.GoVendoringUtil; import com.goide.sdk.GoSdkService; import com.intellij.ProjectTopics; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.ModuleRootAdapter; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.ui.ComboBox; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.MutableCollectionComboBoxModel; import com.intellij.ui.components.JBLabel; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import static com.intellij.util.ThreeState.UNSURE; public class GoVendoringUI implements Disposable { private static final String ENABLED = "Enabled"; private static final String DISABLED = "Disabled"; @NotNull private final MutableCollectionComboBoxModel myVendoringEnabledComboModel = new MutableCollectionComboBoxModel(); @NotNull private String myDefaultComboText = ""; private JPanel myPanel; private JBLabel myErrorMessageLabel; private ComboBox myVendoringEnabledCombo; @SuppressWarnings("unused") private JTextPane myDescriptionPane; public GoVendoringUI() { myPanel.setBorder(IdeBorderFactory.createTitledBorder("Vendor experiment")); } public void initPanel(@NotNull Module module) { if (!module.isDisposed()) { MessageBusConnection connection = module.getMessageBus().connect(this); //noinspection unchecked myVendoringEnabledCombo.setModel(myVendoringEnabledComboModel); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { initComboValues(module); } }); initComboValues(module); } } private void initComboValues(@NotNull Module module) { if (!module.isDisposed()) { String sdkVersion = GoSdkService.getInstance(module.getProject()).getSdkVersion(module); if (!GoVendoringUtil.vendoringCanBeDisabled(sdkVersion)) { myErrorMessageLabel.setIcon(AllIcons.General.BalloonWarning); myErrorMessageLabel.setText("Go " + sdkVersion + " doesn't support disabling vendor experiment"); myErrorMessageLabel.setVisible(true); myVendoringEnabledCombo.setEnabled(false); } else if (!GoVendoringUtil.supportsVendoring(sdkVersion) && sdkVersion != null) { myErrorMessageLabel.setIcon(AllIcons.General.BalloonWarning); myErrorMessageLabel.setText("Go " + sdkVersion + " doesn't support vendor experiment"); myErrorMessageLabel.setVisible(true); myVendoringEnabledCombo.setEnabled(true); } else { myErrorMessageLabel.setVisible(false); myVendoringEnabledCombo.setEnabled(true); } myDefaultComboText = "Default for SDK (" + (GoVendoringUtil.supportsVendoringByDefault(sdkVersion) ? ENABLED : DISABLED) + ")"; //noinspection unchecked myVendoringEnabledComboModel.update(ContainerUtil.newArrayList(myDefaultComboText, ENABLED, DISABLED)); } } public void reset(@NotNull GoModuleSettings settings) { switch (settings.getVendoringEnabled()) { case YES: myVendoringEnabledComboModel.setSelectedItem(ENABLED); break; case NO: myVendoringEnabledComboModel.setSelectedItem(DISABLED); break; case UNSURE: myVendoringEnabledComboModel.setSelectedItem(myDefaultComboText); break; } } public boolean isModified(@NotNull GoModuleSettings settings) { Object item = myVendoringEnabledComboModel.getSelectedItem(); switch (settings.getVendoringEnabled()) { case YES: return !ENABLED.equals(item); case NO: return !DISABLED.equals(item); case UNSURE: return !myDefaultComboText.equals(item); } return true; } public void apply(@NotNull GoModuleSettings settings) { Object item = myVendoringEnabledComboModel.getSelectedItem(); if (ENABLED.equals(item)) { settings.setVendoringEnabled(ThreeState.YES); } else if (DISABLED.equals(item)) { settings.setVendoringEnabled(ThreeState.NO); } else { settings.setVendoringEnabled(UNSURE); } } public JPanel getPanel() { return myPanel; } @Override public void dispose() { UIUtil.dispose(myPanel); UIUtil.dispose(myVendoringEnabledCombo); } private void createUIComponents() { myDescriptionPane = GoUIUtil.createDescriptionPane(); } } ================================================ FILE: src/com/goide/configuration/ListenableHideableDecorator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.configuration; import com.intellij.ui.HideableDecorator; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Collection; class ListenableHideableDecorator extends HideableDecorator { private final Collection myListeners = ContainerUtil.newSmartList(); public ListenableHideableDecorator(@NotNull JPanel panel, @NotNull String displayName, @NotNull JComponent content) { super(panel, displayName, false); setContentComponent(content); } public void addListener(@NotNull MyListener listener) { myListeners.add(listener); } @Override protected void on() { for (MyListener listener : myListeners) { listener.on(); } super.on(); } @Override protected void off() { for (MyListener listener : myListeners) { listener.beforeOff(); } super.off(); for (MyListener listener : myListeners) { listener.afterOff(); } } public static class MyListener { public void on() { } public void beforeOff() { } public void afterOff() { } } } ================================================ FILE: src/com/goide/dlv/DlvCommandProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.goide.dlv.protocol.DlvRequest; import com.goide.dlv.protocol.DlvResponse; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; import org.jetbrains.rpc.CommandProcessor; import org.jetbrains.rpc.CommandProcessorKt; import org.jetbrains.rpc.RequestCallback; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; public abstract class DlvCommandProcessor extends CommandProcessor { @Nullable @Override public DlvResponse readIfHasSequence(@NotNull JsonReaderEx message) { return new DlvResponse.CommandResponseImpl(message, null); } @Override public int getSequence(@NotNull DlvResponse response) { return response.id(); } @Override public void acceptNonSequence(JsonReaderEx message) { } public void processIncomingJson(@NotNull JsonReaderEx reader) { getMessageManager().processIncoming(reader); } @Override public void call(@NotNull DlvResponse response, @NotNull RequestCallback callback) { if (response.result() != null) { callback.onSuccess(response, this); } else { callback.onError(Promise.createError(createMessage(response))); } } @NotNull private static String createMessage(@NotNull DlvResponse r) { DlvResponse.ErrorInfo e = r.error(); if (e == null) return "Internal messaging error"; List data = e.data(); String message = e.message(); if (ContainerUtil.isEmpty(data)) return StringUtil.defaultIfEmpty(message, ""); List list = ContainerUtil.newSmartList(message); list.addAll(data); return list.toString(); } @NotNull @Override public RESULT readResult(@NotNull String method, @NotNull DlvResponse successResponse) { JsonReaderEx result = successResponse.result(); assert result != null : "success result should be not null"; JsonReader reader = result.asGson(); Object o = new GsonBuilder().create().fromJson(reader, getResultType(method.replaceFirst("RPCServer\\.", ""))); //noinspection unchecked return (RESULT)o; } @NotNull private static Type getResultType(@NotNull String method) { for (Class c : DlvRequest.class.getDeclaredClasses()) { if (method.equals(c.getSimpleName())) { Type s = c.getGenericSuperclass(); assert s instanceof ParameterizedType : c.getCanonicalName() + " should have a generic parameter for correct callback processing"; Type[] arguments = ((ParameterizedType)s).getActualTypeArguments(); assert arguments.length == 1 : c.getCanonicalName() + " should have only one generic argument for correct callback processing"; return arguments[0]; } } CommandProcessorKt.getLOG().error("Unknown response " + method + ", please register an appropriate request into com.goide.dlv.protocol.DlvRequest"); return Object.class; } } ================================================ FILE: src/com/goide/dlv/DlvDebugProcess.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.goide.GoConstants; import com.goide.GoFileType; import com.goide.dlv.breakpoint.DlvBreakpointProperties; import com.goide.dlv.breakpoint.DlvBreakpointType; import com.goide.dlv.protocol.DlvRequest; import com.goide.util.GoUtil; import com.intellij.execution.ExecutionResult; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.socketConnection.ConnectionStatus; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.XBreakpoint; import com.intellij.xdebugger.breakpoints.XBreakpointHandler; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProviderBase; import com.intellij.xdebugger.frame.XSuspendContext; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; import org.jetbrains.debugger.DebugProcessImpl; import org.jetbrains.debugger.Location; import org.jetbrains.debugger.StepAction; import org.jetbrains.debugger.Vm; import org.jetbrains.debugger.connection.VmConnection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import static com.goide.dlv.protocol.DlvApi.*; import static com.intellij.util.ObjectUtils.assertNotNull; import static com.intellij.util.ObjectUtils.tryCast; public final class DlvDebugProcess extends DebugProcessImpl> implements Disposable { public static final boolean IS_DLV_DISABLED = !GoConstants.AMD64.equals(GoUtil.systemArch()); private final static Logger LOG = Logger.getInstance(DlvDebugProcess.class); private final AtomicBoolean breakpointsInitiated = new AtomicBoolean(); private final AtomicBoolean connectedListenerAdded = new AtomicBoolean(); private static final Consumer THROWABLE_CONSUMER = LOG::info; @NotNull private final Consumer myStateConsumer = new Consumer() { @Override public void consume(@NotNull DebuggerState o) { if (o.exited) { stop(); return; } XBreakpoint find = findBreak(o.breakPoint); send(new DlvRequest.StacktraceGoroutine()).done(locations -> { DlvSuspendContext context = new DlvSuspendContext(DlvDebugProcess.this, o.currentThread.id, locations, getProcessor()); XDebugSession session = getSession(); if (find == null) { session.positionReached(context); } else { session.breakpointReached(find, null, context); } }); } @Nullable private XBreakpoint findBreak(@Nullable Breakpoint point) { return point == null ? null : breakpoints.get(point.id); } }; @NotNull private Promise send(@NotNull DlvRequest request) { return send(request, getProcessor()); } @NotNull static Promise send(@NotNull DlvRequest request, @NotNull DlvCommandProcessor processor) { return processor.send(request).rejected(THROWABLE_CONSUMER); } @NotNull private DlvCommandProcessor getProcessor() { return assertNotNull(tryCast(getVm(), DlvVm.class)).getCommandProcessor(); } public DlvDebugProcess(@NotNull XDebugSession session, @NotNull VmConnection connection, @Nullable ExecutionResult er) { super(session, connection, new MyEditorsProvider(), null, er); } @NotNull @Override protected XBreakpointHandler[] createBreakpointHandlers() { return new XBreakpointHandler[]{new MyBreakpointHandler()}; } @NotNull @Override public ExecutionConsole createConsole() { ExecutionResult executionResult = getExecutionResult(); return executionResult == null ? super.createConsole() : executionResult.getExecutionConsole(); } @Override protected boolean isVmStepOutCorrect() { return false; } @Override public void dispose() { // todo } @Override public boolean checkCanInitBreakpoints() { if (getConnection().getState().getStatus() == ConnectionStatus.CONNECTED) { // breakpointsInitiated could be set in another thread and at this point work (init breakpoints) could be not yet performed return initBreakpointHandlersAndSetBreakpoints(false); } if (connectedListenerAdded.compareAndSet(false, true)) { getConnection().addListener(status -> { if (status == ConnectionStatus.CONNECTED) { initBreakpointHandlersAndSetBreakpoints(true); } }); } return false; } private boolean initBreakpointHandlersAndSetBreakpoints(boolean setBreakpoints) { if (!breakpointsInitiated.compareAndSet(false, true)) return false; Vm vm = getVm(); assert vm != null : "Vm should be initialized"; if (setBreakpoints) { doSetBreakpoints(); resume(vm); } return true; } private void doSetBreakpoints() { AccessToken token = ReadAction.start(); try { getSession().initBreakpoints(); } finally { token.finish(); } } private void command(@NotNull @MagicConstant(stringValues = {NEXT, CONTINUE, HALT, SWITCH_THREAD, STEP}) String name) { send(new DlvRequest.Command(name)).done(myStateConsumer); } @Nullable @Override protected Promise continueVm(@NotNull Vm vm, @NotNull StepAction stepAction) { switch (stepAction) { case CONTINUE: command(CONTINUE); break; case IN: command(STEP); break; case OVER: command(NEXT); break; case OUT: // todo break; } return null; } @NotNull @Override public List getLocationsForBreakpoint(@NotNull XLineBreakpoint breakpoint) { return Collections.emptyList(); } @Override public void runToPosition(@NotNull XSourcePosition position, @Nullable XSuspendContext context) { // todo } @Override public void stop() { if (getVm() != null) { send(new DlvRequest.Detach(true)); } getSession().stop(); } private static class MyEditorsProvider extends XDebuggerEditorsProviderBase { @NotNull @Override public FileType getFileType() { return GoFileType.INSTANCE; } @Override protected PsiFile createExpressionCodeFragment(@NotNull Project project, @NotNull String text, @Nullable PsiElement context, boolean isPhysical) { return PsiFileFactory.getInstance(project).createFileFromText("dlv-debug.txt", PlainTextLanguage.INSTANCE, text); } } private static final Key ID = Key.create("DLV_BP_ID"); private final Map> breakpoints = ContainerUtil.newConcurrentMap(); private class MyBreakpointHandler extends XBreakpointHandler> { public MyBreakpointHandler() { super(DlvBreakpointType.class); } @Override public void registerBreakpoint(@NotNull XLineBreakpoint breakpoint) { XSourcePosition breakpointPosition = breakpoint.getSourcePosition(); if (breakpointPosition == null) return; VirtualFile file = breakpointPosition.getFile(); int line = breakpointPosition.getLine(); send(new DlvRequest.CreateBreakpoint(file.getPath(), line + 1)) .done(b -> { breakpoint.putUserData(ID, b.id); breakpoints.put(b.id, breakpoint); getSession().updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_verified_breakpoint, null); }) .rejected(t -> { String message = t == null ? null : t.getMessage(); getSession().updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, message); }); } @Override public void unregisterBreakpoint(@NotNull XLineBreakpoint breakpoint, boolean temporary) { XSourcePosition breakpointPosition = breakpoint.getSourcePosition(); if (breakpointPosition == null) return; Integer id = breakpoint.getUserData(ID); if (id == null) return; // obsolete breakpoint.putUserData(ID, null); breakpoints.remove(id); send(new DlvRequest.ClearBreakpoint(id)); } } } ================================================ FILE: src/com/goide/dlv/DlvRemoteVmConnection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.debugger.Vm; import org.jetbrains.debugger.connection.RemoteVmConnection; import org.jetbrains.io.NettyKt; import java.net.InetSocketAddress; public class DlvRemoteVmConnection extends RemoteVmConnection { @NotNull @Override public Bootstrap createBootstrap(@NotNull InetSocketAddress address, @NotNull AsyncPromise vmResult) { return NettyKt.oioClientBootstrap().handler(new ChannelInitializer() { @Override protected void initChannel(@NotNull Channel channel) throws Exception { vmResult.setResult(new DlvVm(getDebugEventListener(), channel)); } }); } @NotNull @Override protected String connectedAddressToPresentation(@NotNull InetSocketAddress address, @NotNull Vm vm) { return address.toString(); } } ================================================ FILE: src/com/goide/dlv/DlvStackFrame.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.goide.GoIcons; import com.goide.dlv.protocol.DlvApi; import com.goide.dlv.protocol.DlvRequest; import com.goide.psi.*; import com.goide.sdk.GoSdkService; import com.intellij.execution.configurations.ModuleBasedConfiguration; import com.intellij.execution.configurations.RunProfile; import com.intellij.icons.AllIcons; import com.intellij.openapi.editor.Document; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.ColoredTextContainer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.xdebugger.XDebuggerUtil; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.XCompositeNode; import com.intellij.xdebugger.frame.XStackFrame; import com.intellij.xdebugger.frame.XValue; import com.intellij.xdebugger.frame.XValueChildrenList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; import javax.swing.*; class DlvStackFrame extends XStackFrame { private final DlvDebugProcess myProcess; private final DlvApi.Location myLocation; private final DlvCommandProcessor myProcessor; private final int myId; public DlvStackFrame(@NotNull DlvDebugProcess process, @NotNull DlvApi.Location location, @NotNull DlvCommandProcessor processor, int id) { myProcess = process; myLocation = location; myProcessor = processor; myId = id; } @Nullable @Override public XDebuggerEvaluator getEvaluator() { return new XDebuggerEvaluator() { @Override public void evaluate(@NotNull String expression, @NotNull XEvaluationCallback callback, @Nullable XSourcePosition expressionPosition) { myProcessor.send(new DlvRequest.EvalSymbol(expression, myId)) .done(variable -> callback.evaluated(createXValue(variable, AllIcons.Debugger.Watch))) .rejected(throwable -> callback.errorOccurred(throwable.getMessage())); } @Nullable private PsiElement findElementAt(@Nullable PsiFile file, int offset) { return file != null ? file.findElementAt(offset) : null; } @Nullable @Override public TextRange getExpressionRangeAtOffset(@NotNull Project project, @NotNull Document document, int offset, boolean sideEffectsAllowed) { Ref currentRange = Ref.create(null); PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> { try { PsiElement elementAtCursor = findElementAt(PsiDocumentManager.getInstance(project).getPsiFile(document), offset); GoTypeOwner e = PsiTreeUtil.getParentOfType(elementAtCursor, GoExpression.class, GoVarDefinition.class, GoConstDefinition.class, GoParamDefinition.class); if (e != null) { currentRange.set(e.getTextRange()); } } catch (IndexNotReadyException ignored) { } }); return currentRange.get(); } }; } @NotNull private XValue createXValue(@NotNull DlvApi.Variable variable, @Nullable Icon icon) { return new DlvXValue(myProcess, variable, myProcessor, myId, icon); } @Nullable @Override public XSourcePosition getSourcePosition() { VirtualFile file = findFile(); return file == null ? null : XDebuggerUtil.getInstance().createPosition(file, myLocation.line - 1); } @Nullable private VirtualFile findFile() { String url = myLocation.file; VirtualFile file = LocalFileSystem.getInstance().findFileByPath(url); if (file == null && SystemInfo.isWindows) { Project project = myProcess.getSession().getProject(); RunProfile profile = myProcess.getSession().getRunProfile(); Module module = profile instanceof ModuleBasedConfiguration ? ((ModuleBasedConfiguration)profile).getConfigurationModule().getModule() : null; String sdkHomePath = GoSdkService.getInstance(project).getSdkHomePath(module); if (sdkHomePath == null) return null; String newUrl = StringUtil.replaceIgnoreCase(url, "c:/go", sdkHomePath); return LocalFileSystem.getInstance().findFileByPath(newUrl); } return file; } @Override public void customizePresentation(@NotNull ColoredTextContainer component) { super.customizePresentation(component); component.append(" at " + myLocation.function.name, SimpleTextAttributes.REGULAR_ATTRIBUTES); component.setIcon(AllIcons.Debugger.StackFrame); } @NotNull private Promise send(@NotNull DlvRequest request) { return DlvDebugProcess.send(request, myProcessor); } @Override public void computeChildren(@NotNull XCompositeNode node) { send(new DlvRequest.ListLocalVars(myId)).done(variables -> { XValueChildrenList xVars = new XValueChildrenList(variables.size()); for (DlvApi.Variable v : variables) xVars.add(v.name, createXValue(v, GoIcons.VARIABLE)); send(new DlvRequest.ListFunctionArgs(myId)).done(args -> { for (DlvApi.Variable v : args) xVars.add(v.name, createXValue(v, GoIcons.PARAMETER)); node.addChildren(xVars, true); }); }); } } ================================================ FILE: src/com/goide/dlv/DlvSuspendContext.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.goide.dlv.protocol.DlvApi; import com.intellij.util.containers.ContainerUtil; import com.intellij.xdebugger.frame.XExecutionStack; import com.intellij.xdebugger.frame.XStackFrame; import com.intellij.xdebugger.frame.XSuspendContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; class DlvSuspendContext extends XSuspendContext { @NotNull private final DlvExecutionStack myStack; public DlvSuspendContext(@NotNull DlvDebugProcess process, int threadId, @NotNull List locations, @NotNull DlvCommandProcessor processor) { myStack = new DlvExecutionStack(process, threadId, locations, processor); } @Nullable @Override public XExecutionStack getActiveExecutionStack() { return myStack; } @NotNull @Override public XExecutionStack[] getExecutionStacks() { return new XExecutionStack[]{myStack}; } private static class DlvExecutionStack extends XExecutionStack { @NotNull private final DlvDebugProcess myProcess; @NotNull private final List myLocations; @NotNull private final DlvCommandProcessor myProcessor; @NotNull private final List myStack; public DlvExecutionStack(@NotNull DlvDebugProcess process, int threadId, @NotNull List locations, @NotNull DlvCommandProcessor processor) { super("Thread #" + threadId); myProcess = process; myLocations = locations; myProcessor = processor; myStack = ContainerUtil.newArrayListWithCapacity(locations.size()); for (int i = 0; i < myLocations.size(); i++) { myStack.add(new DlvStackFrame(myProcess, myLocations.get(i), myProcessor, i)); } } @Nullable @Override public XStackFrame getTopFrame() { return ContainerUtil.getFirstItem(myStack); } @Override public void computeStackFrames(int firstFrameIndex, @NotNull XStackFrameContainer container) { container.addStackFrames(myStack, true); } } } ================================================ FILE: src/com/goide/dlv/DlvVm.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.CharsetToolkit; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.json.JsonObjectDecoder; import org.jetbrains.annotations.NotNull; import org.jetbrains.concurrency.Promise; import org.jetbrains.debugger.*; import org.jetbrains.io.ChannelBufferToString; import org.jetbrains.io.SimpleChannelInboundHandlerAdapter; import org.jetbrains.jsonProtocol.Request; import java.io.IOException; public class DlvVm extends VmBase { private final static Logger LOG = Logger.getInstance(DlvVm.class); @NotNull private final DlvCommandProcessor commandProcessor; @NotNull private final StandaloneVmHelper vmHelper; @NotNull private final DummyBreakpointManager breakpointManager = new DummyBreakpointManager(); public DlvVm(@NotNull DebugEventListener tabListener, @NotNull Channel channel) { super(tabListener); commandProcessor = new DlvCommandProcessor() { @Override public boolean write(@NotNull Request message) throws IOException { ByteBuf content = message.getBuffer(); LOG.info("OUT: " + content.toString(CharsetToolkit.UTF8_CHARSET)); return vmHelper.write(content); } }; vmHelper = new StandaloneVmHelper(this, commandProcessor, channel); channel.pipeline().addLast(new JsonObjectDecoder(), new SimpleChannelInboundHandlerAdapter() { @Override protected void messageReceived(ChannelHandlerContext context, Object message) throws Exception { if (message instanceof ByteBuf) { LOG.info("IN: " + ((ByteBuf)message).toString(CharsetToolkit.UTF8_CHARSET)); CharSequence string = ChannelBufferToString.readChars((ByteBuf)message); JsonReaderEx ex = new JsonReaderEx(string); getCommandProcessor().processIncomingJson(ex); } } }); } @NotNull @Override public AttachStateManager getAttachStateManager() { return vmHelper; } @NotNull public final DlvCommandProcessor getCommandProcessor() { return commandProcessor; } @NotNull @Override public ScriptManagerBase getScriptManager() { throw new UnsupportedOperationException(); } @NotNull @Override public BreakpointManager getBreakpointManager() { return breakpointManager; } /** * Changed API between minor versions, runtime is compatible * Todo: uncomment since 2016.2, when only the last build of 15.0 will be supported */ @SuppressWarnings("unchecked") @NotNull @Override public SuspendContextManagerBase getSuspendContextManager() { return new SuspendContextManagerBase() { @NotNull @Override public Promise continueVm(@NotNull StepAction stepAction, int stepCount) { return Promise.DONE; } @NotNull @Override protected DebugEventListener getDebugListener() { return DlvVm.this.getDebugListener(); } @NotNull @Override protected Promise doSuspend() { return Promise.DONE; } }; } } ================================================ FILE: src/com/goide/dlv/DlvXValue.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.goide.dlv.protocol.DlvApi; import com.goide.dlv.protocol.DlvRequest; import com.goide.psi.GoNamedElement; import com.goide.psi.GoTopLevelDeclaration; import com.goide.psi.GoTypeSpec; import com.goide.stubs.index.GoTypesIndex; import com.intellij.icons.AllIcons; import com.intellij.lang.ASTNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SyntaxTraverser; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerUtil; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation; import com.intellij.xdebugger.frame.presentation.XRegularValuePresentation; import com.intellij.xdebugger.frame.presentation.XStringValuePresentation; import com.intellij.xdebugger.frame.presentation.XValuePresentation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; class DlvXValue extends XNamedValue { @NotNull private final DlvApi.Variable myVariable; private final Icon myIcon; private final DlvDebugProcess myProcess; private final DlvCommandProcessor myProcessor; private final int myFrameId; public DlvXValue(@NotNull DlvDebugProcess process, @NotNull DlvApi.Variable variable, @NotNull DlvCommandProcessor processor, int frameId, @Nullable Icon icon) { super(variable.name); myProcess = process; myVariable = variable; myIcon = icon; myProcessor = processor; myFrameId = frameId; } @Override public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) { XValuePresentation presentation = getPresentation(); boolean hasChildren = myVariable.children.length > 0; node.setPresentation(myIcon, presentation, hasChildren); } @Override public void computeChildren(@NotNull XCompositeNode node) { DlvApi.Variable[] children = myVariable.children; if (children.length == 0) { super.computeChildren(node); } else { XValueChildrenList list = new XValueChildrenList(); for (DlvApi.Variable child : children) { list.add(child.name, new DlvXValue(myProcess, child, myProcessor, myFrameId, AllIcons.Nodes.Field)); } node.addChildren(list, true); } } @Nullable @Override public XValueModifier getModifier() { return new XValueModifier() { @Override public void setValue(@NotNull String newValue, @NotNull XModificationCallback callback) { myProcessor.send(new DlvRequest.SetSymbol(myVariable.name, newValue, myFrameId)) .processed(o -> { if (o != null) { callback.valueModified(); } }) .rejected(throwable -> callback.errorOccurred(throwable.getMessage())); } }; } @NotNull private XValuePresentation getPresentation() { String value = myVariable.value; if (myVariable.isNumber()) return new XNumericValuePresentation(value); if (myVariable.isString()) return new XStringValuePresentation(value); if (myVariable.isBool()) { return new XValuePresentation() { @Override public void renderValue(@NotNull XValueTextRenderer renderer) { renderer.renderValue(value); } }; } String type = myVariable.type; boolean isSlice = myVariable.isSlice(); boolean isArray = myVariable.isArray(); if (isSlice || isArray) { return new XRegularValuePresentation("len:" + myVariable.len + (isSlice ? ", cap:" + myVariable.cap : ""), type.replaceFirst("struct ", "")); } String prefix = myVariable.type + " "; return new XRegularValuePresentation(StringUtil.startsWith(value, prefix) ? value.replaceFirst(Pattern.quote(prefix), "") : value, type); } @Nullable private static PsiElement findTargetElement(@NotNull Project project, @NotNull XSourcePosition position, @NotNull Editor editor, @NotNull String name) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null || !file.getVirtualFile().equals(position.getFile())) return null; ASTNode leafElement = file.getNode().findLeafElementAt(position.getOffset()); if (leafElement == null) return null; GoTopLevelDeclaration topLevel = PsiTreeUtil.getTopmostParentOfType(leafElement.getPsi(), GoTopLevelDeclaration.class); SyntaxTraverser traverser = SyntaxTraverser.psiTraverser(topLevel) .filter(e -> e instanceof GoNamedElement && Comparing.equal(name, ((GoNamedElement)e).getName())); Iterator iterator = traverser.iterator(); return iterator.hasNext() ? iterator.next() : null; } @Override public void computeSourcePosition(@NotNull XNavigatable navigatable) { readActionInPooledThread(new Runnable() { @Override public void run() { navigatable.setSourcePosition(findPosition()); } @Nullable private XSourcePosition findPosition() { XDebugSession debugSession = getSession(); if (debugSession == null) return null; XStackFrame stackFrame = debugSession.getCurrentStackFrame(); if (stackFrame == null) return null; Project project = debugSession.getProject(); XSourcePosition position = debugSession.getCurrentPosition(); Editor editor = ((FileEditorManagerImpl)FileEditorManager.getInstance(project)).getSelectedTextEditor(true); if (editor == null || position == null) return null; String name = myName.startsWith("&") ? myName.replaceFirst("\\&", "") : myName; PsiElement resolved = findTargetElement(project, position, editor, name); if (resolved == null) return null; VirtualFile virtualFile = resolved.getContainingFile().getVirtualFile(); return XDebuggerUtil.getInstance().createPositionByOffset(virtualFile, resolved.getTextOffset()); } }); } private static void readActionInPooledThread(@NotNull Runnable runnable) { ApplicationManager.getApplication().executeOnPooledThread(() -> ApplicationManager.getApplication().runReadAction(runnable)); } @Nullable private Project getProject() { XDebugSession session = getSession(); return session != null ? session.getProject() : null; } @Nullable private XDebugSession getSession() { return myProcess.getSession(); } @NotNull @Override public ThreeState computeInlineDebuggerData(@NotNull XInlineDebuggerDataCallback callback) { computeSourcePosition(callback::computed); return ThreeState.YES; } @Override public boolean canNavigateToSource() { return true; // for the future compatibility } @Override public boolean canNavigateToTypeSource() { return (myVariable.isStructure() || myVariable.isPtr()) && getProject() != null; } @Override public void computeTypeSourcePosition(@NotNull XNavigatable navigatable) { readActionInPooledThread(() -> { boolean isStructure = myVariable.isStructure(); boolean isPtr = myVariable.isPtr(); if (!isStructure && !isPtr) return; Project project = getProject(); if (project == null) return; String dlvType = myVariable.type; String fqn = dlvType.replaceFirst(isPtr ? "\\*struct " : "struct ", ""); List split = StringUtil.split(fqn, "."); boolean noFqn = split.size() == 1; if (split.size() == 2 || noFqn) { String name = ContainerUtil.getLastItem(split); assert name != null; Collection types = GoTypesIndex.find(name, project, GlobalSearchScope.allScope(project), null); for (GoTypeSpec type : types) { if (noFqn || Comparing.equal(fqn, type.getQualifiedName())) { navigatable.setSourcePosition(XDebuggerUtil.getInstance().createPositionByOffset( type.getContainingFile().getVirtualFile(), type.getTextOffset())); return; } } } }); } } ================================================ FILE: src/com/goide/dlv/JsonReaderEx.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv; import com.google.gson.JsonParseException; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.intellij.util.text.CharSequenceReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.Closeable; import java.util.Arrays; public final class JsonReaderEx implements Closeable { /** * The only non-execute prefix this parser permits */ private static final char[] NON_EXECUTE_PREFIX = ")]}'\n".toCharArray(); private static final long MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10; private static final int PEEKED_NONE = 0; private static final int PEEKED_BEGIN_OBJECT = 1; private static final int PEEKED_END_OBJECT = 2; private static final int PEEKED_BEGIN_ARRAY = 3; private static final int PEEKED_END_ARRAY = 4; private static final int PEEKED_TRUE = 5; private static final int PEEKED_FALSE = 6; private static final int PEEKED_NULL = 7; private static final int PEEKED_SINGLE_QUOTED = 8; private static final int PEEKED_DOUBLE_QUOTED = 9; private static final int PEEKED_UNQUOTED = 10; /** * When this is returned, the string value is stored in peekedString. */ private static final int PEEKED_BUFFERED = 11; private static final int PEEKED_SINGLE_QUOTED_NAME = 12; private static final int PEEKED_DOUBLE_QUOTED_NAME = 13; private static final int PEEKED_UNQUOTED_NAME = 14; /** * When this is returned, the integer value is stored in peekedLong. */ private static final int PEEKED_LONG = 15; private static final int PEEKED_NUMBER = 16; private static final int PEEKED_EOF = 17; /* State machine when parsing numbers */ private static final int NUMBER_CHAR_NONE = 0; private static final int NUMBER_CHAR_SIGN = 1; private static final int NUMBER_CHAR_DIGIT = 2; private static final int NUMBER_CHAR_DECIMAL = 3; private static final int NUMBER_CHAR_FRACTION_DIGIT = 4; private static final int NUMBER_CHAR_EXP_E = 5; private static final int NUMBER_CHAR_EXP_SIGN = 6; private static final int NUMBER_CHAR_EXP_DIGIT = 7; @NotNull private final CharSequence in; /** * True to accept non-spec compliant JSON */ private boolean lenient = false; private int position; private final int limit; private int peeked = PEEKED_NONE; /** * A peeked value that was composed entirely of digits with an optional * leading dash. Positive values may not have a leading 0. */ private long peekedLong; /** * The number of characters in a peeked number literal. Increment 'pos' by * this after reading a number. */ private int peekedNumberLength; /** * A peeked string that should be parsed on the next double, long or string. * This is populated before a numeric value is parsed and used if that parsing * fails. */ @Nullable private String peekedString; /* * The nesting stack. Using a manual array rather than an ArrayList saves 20%. */ private int[] stack; private int stackSize = 0; private StringBuilder builder; /** * Creates a new instance that reads a JSON-encoded stream from {@code in}. */ public JsonReaderEx(@NotNull CharSequence in) { this(in, 0); } public JsonReaderEx(@NotNull CharSequence in, int start) { this(in, start, new int[32]); stack[stackSize++] = JsonScope.EMPTY_DOCUMENT; } private JsonReaderEx(@NotNull CharSequence in, int start, @NotNull int[] stack) { this.in = in; position = start; limit = in.length(); this.stack = stack; } private final static class JsonScope { /** * An array with no elements requires no separators or newlines before * it is closed. */ static final int EMPTY_ARRAY = 1; /** * A array with at least one value requires a comma and newline before * the next element. */ static final int NONEMPTY_ARRAY = 2; /** * An object with no name/value pairs requires no separators or newlines * before it is closed. */ static final int EMPTY_OBJECT = 3; /** * An object whose most recent element is a key. The next element must * be a value. */ static final int DANGLING_NAME = 4; /** * An object with at least one name/value pair requires a comma and * newline before the next element. */ static final int NONEMPTY_OBJECT = 5; /** * No object or array has been started. */ static final int EMPTY_DOCUMENT = 6; /** * A document with at an array or object. */ static final int NONEMPTY_DOCUMENT = 7; /** * A document that's been closed and cannot be accessed. */ static final int CLOSED = 8; } @Nullable public JsonReaderEx subReader() { JsonToken nextToken = peek(); switch (nextToken) { case BEGIN_ARRAY: case BEGIN_OBJECT: case STRING: case NUMBER: case BOOLEAN: break; case NULL: // just return null return null; default: throw createParseError("Cannot create sub reader, next token " + nextToken + " is not value"); } JsonReaderEx subReader = new JsonReaderEx(in, position, Arrays.copyOf(stack, stack.length)); subReader.stackSize = stackSize; subReader.peeked = peeked; subReader.peekedLong = peekedLong; subReader.peekedNumberLength = peekedNumberLength; subReader.peekedString = peekedString; return subReader; } @NotNull public JsonReader asGson() { JsonToken nextToken = peek(); switch (nextToken) { case BEGIN_ARRAY: case BEGIN_OBJECT: case STRING: case NUMBER: case BOOLEAN: break; default: throw createParseError("Cannot create sub reader, next token " + nextToken + " is not value"); } CharSequence sequence = position > 0 ? in.subSequence(position - 1, in.length()) : in; return new JsonReader(new CharSequenceReader(sequence)); } /** * Consumes the next token from the JSON stream and asserts that it is the * beginning of a new object. */ @NotNull public JsonReaderEx beginObject() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_BEGIN_OBJECT) { push(JsonScope.EMPTY_OBJECT); peeked = PEEKED_NONE; } else { throw createParseError("Expected BEGIN_OBJECT but was " + peek()); } return this; } /** * Consumes the next token from the JSON stream and asserts that it is the * end of the current object. */ public void endObject() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_END_OBJECT) { stackSize--; peeked = PEEKED_NONE; } else { throw new IllegalStateException("Expected END_OBJECT but was " + peek()); } } /** * Returns true if the current array or object has another element. */ public boolean hasNext() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY; } /** * Returns the type of the next token without consuming it. */ @NotNull public JsonToken peek() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } switch (p) { case PEEKED_BEGIN_OBJECT: return JsonToken.BEGIN_OBJECT; case PEEKED_END_OBJECT: return JsonToken.END_OBJECT; case PEEKED_BEGIN_ARRAY: return JsonToken.BEGIN_ARRAY; case PEEKED_END_ARRAY: return JsonToken.END_ARRAY; case PEEKED_SINGLE_QUOTED_NAME: case PEEKED_DOUBLE_QUOTED_NAME: case PEEKED_UNQUOTED_NAME: return JsonToken.NAME; case PEEKED_TRUE: case PEEKED_FALSE: return JsonToken.BOOLEAN; case PEEKED_NULL: return JsonToken.NULL; case PEEKED_SINGLE_QUOTED: case PEEKED_DOUBLE_QUOTED: case PEEKED_UNQUOTED: case PEEKED_BUFFERED: return JsonToken.STRING; case PEEKED_LONG: case PEEKED_NUMBER: return JsonToken.NUMBER; case PEEKED_EOF: return JsonToken.END_DOCUMENT; default: throw new AssertionError(); } } private int doPeek() { int peekStack = stack[stackSize - 1]; if (peekStack == JsonScope.EMPTY_ARRAY) { stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY; } else if (peekStack == JsonScope.NONEMPTY_ARRAY) { // Look for a comma before the next element. int c = nextNonWhitespace(true); switch (c) { case ']': return peeked = PEEKED_END_ARRAY; case ';': checkLenient(); // fall-through case ',': break; default: throw createParseError("Unterminated array"); } } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) { stack[stackSize - 1] = JsonScope.DANGLING_NAME; // Look for a comma before the next element. if (peekStack == JsonScope.NONEMPTY_OBJECT) { int c = nextNonWhitespace(true); switch (c) { case '}': return peeked = PEEKED_END_OBJECT; case ';': checkLenient(); // fall-through case ',': break; default: throw createParseError("Unterminated object"); } } int c = nextNonWhitespace(true); switch (c) { case '"': return peeked = PEEKED_DOUBLE_QUOTED_NAME; case '\'': checkLenient(); return peeked = PEEKED_SINGLE_QUOTED_NAME; case '}': if (peekStack != JsonScope.NONEMPTY_OBJECT) { return peeked = PEEKED_END_OBJECT; } else { throw createParseError("Expected name"); } default: checkLenient(); position--; // Don't consume the first character in an unquoted string. if (isLiteral((char)c)) { return peeked = PEEKED_UNQUOTED_NAME; } else { throw createParseError("Expected name"); } } } else if (peekStack == JsonScope.DANGLING_NAME) { stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT; // Look for a colon before the value. int c = nextNonWhitespace(true); switch (c) { case ':': break; case '=': checkLenient(); if (position < limit && in.charAt(position) == '>') { position++; } break; default: throw createParseError("Expected ':'"); } } else if (peekStack == JsonScope.EMPTY_DOCUMENT) { if (lenient) { consumeNonExecutePrefix(); } stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT; } else if (peekStack == JsonScope.NONEMPTY_DOCUMENT) { int c = nextNonWhitespace(false); if (c == -1) { return peeked = PEEKED_EOF; } else { checkLenient(); position--; } } else if (peekStack == JsonScope.CLOSED) { throw new IllegalStateException("JsonReader is closed"); } int c = nextNonWhitespace(true); switch (c) { case ']': if (peekStack == JsonScope.EMPTY_ARRAY) { return peeked = PEEKED_END_ARRAY; } // fall-through to handle ",]" case ';': case ',': // In lenient mode, a 0-length literal in an array means 'null'. if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) { checkLenient(); position--; return peeked = PEEKED_NULL; } else { throw createParseError("Unexpected value"); } case '\'': checkLenient(); return peeked = PEEKED_SINGLE_QUOTED; case '"': if (stackSize == 1) { checkLenient(); } return peeked = PEEKED_DOUBLE_QUOTED; case '[': return peeked = PEEKED_BEGIN_ARRAY; case '{': return peeked = PEEKED_BEGIN_OBJECT; default: position--; // Don't consume the first character in a literal value. } if (stackSize == 1) { checkLenient(); // Top-level value isn't an array or an object. } int result = peekKeyword(); if (result != PEEKED_NONE) { return result; } result = peekNumber(); if (result != PEEKED_NONE) { return result; } if (!isLiteral(in.charAt(position))) { throw createParseError("Expected value"); } checkLenient(); return peeked = PEEKED_UNQUOTED; } private int peekKeyword() { // Figure out which keyword we're matching against by its first character. char c = in.charAt(position); String keyword; String keywordUpper; int peeking; if (c == 't' || c == 'T') { keyword = "true"; keywordUpper = "TRUE"; peeking = PEEKED_TRUE; } else if (c == 'f' || c == 'F') { keyword = "false"; keywordUpper = "FALSE"; peeking = PEEKED_FALSE; } else if (c == 'n' || c == 'N') { keyword = "null"; keywordUpper = "NULL"; peeking = PEEKED_NULL; } else { return PEEKED_NONE; } // Confirm that chars [1..length) match the keyword. int length = keyword.length(); for (int i = 1; i < length; i++) { if (position + i >= limit) { return PEEKED_NONE; } c = in.charAt(position + i); if (c != keyword.charAt(i) && c != keywordUpper.charAt(i)) { return PEEKED_NONE; } } if ((position + length < limit) && isLiteral(in.charAt(position + length))) { return PEEKED_NONE; // Don't match trues, falsey or nullsoft! } // We've found the keyword followed either by EOF or by a non-literal character. position += length; return peeked = peeking; } @SuppressWarnings("ConstantConditions") private int peekNumber() { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. CharSequence in = this.in; int p = position; int l = limit; long value = 0; // Negative to accommodate Long.MIN_VALUE more easily. boolean negative = false; boolean fitsInLong = true; int last = NUMBER_CHAR_NONE; int i = 0; charactersOfNumber: for (; true; i++) { if (p + i == l) { if (i == limit) { // Though this looks like a well-formed number, it's too long to continue reading. Give up // and let the application handle this as an unquoted literal. return PEEKED_NONE; } p = position; l = limit; } char c = in.charAt(p + i); switch (c) { case '-': if (last == NUMBER_CHAR_NONE) { negative = true; last = NUMBER_CHAR_SIGN; continue; } else if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case '+': if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case 'e': case 'E': if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) { last = NUMBER_CHAR_EXP_E; continue; } return PEEKED_NONE; case '.': if (last == NUMBER_CHAR_DIGIT) { last = NUMBER_CHAR_DECIMAL; continue; } return PEEKED_NONE; default: if (c < '0' || c > '9') { if (!isLiteral(c)) { break charactersOfNumber; } return PEEKED_NONE; } if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) { value = -(c - '0'); last = NUMBER_CHAR_DIGIT; } else if (last == NUMBER_CHAR_DIGIT) { if (value == 0) { return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal). } long newValue = value * 10 - (c - '0'); fitsInLong &= value > MIN_INCOMPLETE_INTEGER || (value == MIN_INCOMPLETE_INTEGER && newValue < value); value = newValue; } else if (last == NUMBER_CHAR_DECIMAL) { last = NUMBER_CHAR_FRACTION_DIGIT; } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) { last = NUMBER_CHAR_EXP_DIGIT; } } } // We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER. if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) { peekedLong = negative ? value : -value; position += i; return peeked = PEEKED_LONG; } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) { peekedNumberLength = i; return peeked = PEEKED_NUMBER; } else { return PEEKED_NONE; } } /** * Consumes the non-execute prefix if it exists. */ private void consumeNonExecutePrefix() { // fast forward through the leading whitespace nextNonWhitespace(true); position--; if (position + NON_EXECUTE_PREFIX.length > limit) { return; } for (int i = 0; i < NON_EXECUTE_PREFIX.length; i++) { if (in.charAt(position + i) != NON_EXECUTE_PREFIX[i]) { return; // not a security token! } } // we consumed a security token! position += NON_EXECUTE_PREFIX.length; } private boolean isLiteral(char c) { switch (c) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': return false; default: return true; } } /** * Returns the next token, a {@link JsonToken#NAME property name}, and consumes it */ @Nullable public String nextName() { String result = nextNameOrNull(); if (result == null) { throw createParseError("Expected a name but was " + peek()); } return result; } @Nullable public String nextNameOrNull() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED_NAME) { result = nextUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED_NAME) { result = nextQuotedValue('\''); } else if (p == PEEKED_DOUBLE_QUOTED_NAME) { result = nextQuotedValue('"'); } else { if (p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY) { throw createParseError("Expected a name but was " + peek()); } return null; } peeked = PEEKED_NONE; return result; } @Nullable public String nextString() { return nextString(false); } /** * Returns the {@link JsonToken#STRING string} value of the next token, * consuming it. If the next token is a number, this method will return its * string form. * * @throws IllegalStateException if the next token is not a string or if * this reader is closed. */ @Nullable public String nextString(boolean anyPrimitiveAsString) { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } String result; if (p == PEEKED_UNQUOTED) { result = nextUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED) { result = nextQuotedValue('\''); } else if (p == PEEKED_DOUBLE_QUOTED) { result = nextQuotedValue('"'); } else if (p == PEEKED_BUFFERED) { result = peekedString; peekedString = null; } else if (p == PEEKED_LONG) { result = Long.toString(peekedLong); } else if (p == PEEKED_NUMBER) { int end = position + peekedNumberLength; result = in.subSequence(position, end).toString(); position = end; } else if (anyPrimitiveAsString && p == PEEKED_TRUE) { result = "true"; } else if (anyPrimitiveAsString && p == PEEKED_FALSE) { result = "false"; } else if (anyPrimitiveAsString && p == PEEKED_NULL) { result = "null"; } else { throw createParseError("Expected a string but was " + peek()); } peeked = PEEKED_NONE; return result; } /** * Consumes the next token from the JSON stream and asserts that it is a * literal null. * * @throws IllegalStateException if the next token is not null or if this * reader is closed. */ public void nextNull() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_NULL) { peeked = PEEKED_NONE; } else { throw createParseError("Expected null but was " + peek()); } } /** * Returns the string up to but not including {@code quote}, unescaping any * character escape sequences encountered along the way. The opening quote * should have already been read. This consumes the closing quote, but does * not include it in the returned string. * * @param quote either ' or ". * @throws NumberFormatException if any unicode escape sequences are * malformed. */ @NotNull private String nextQuotedValue(char quote) { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. CharSequence in = this.in; int p = position; int l = limit; // the index of the first character not yet appended to the builder int start = p; StringBuilder builder = null; while (p < l) { char c = in.charAt(p++); if (c == quote) { position = p; if (builder == null) { return in.subSequence(start, p - 1).toString(); } else { return builder.append(in, start, p - 1).toString(); } } else if (c == '\\') { position = p; if (builder == null) { if (this.builder == null) { this.builder = new StringBuilder((p - start) + 16); } else { this.builder.setLength(0); } builder = this.builder; } builder.append(in, start, p - 1); builder.append(readEscapeCharacter()); p = position; l = limit; start = p; } //else if (c == '\n') { // //lineNumber++; // //lineStart = p; //} } position = p; throw createParseError("Unterminated string"); } /** * Returns an unquoted value as a string. */ @NotNull private String nextUnquotedValue() { int i = position; findNonLiteralCharacter: for (; i < limit; i++) { switch (in.charAt(i)) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': break findNonLiteralCharacter; } } String result = in.subSequence(position, i).toString(); position = i; return result; } private void skipQuotedValue(char quote) { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. CharSequence in = this.in; int p = position; int l = limit; // the index of the first character not yet appended to the builder while (p < l) { int c = in.charAt(p++); if (c == quote) { position = p; return; } else if (c == '\\') { position = p; readEscapeCharacter(); p = position; l = limit; } //else if (c == '\n') { // //lineNumber++; // //lineStart = p; //} } position = p; throw createParseError("Unterminated string"); } private void skipUnquotedValue() { int i = position; for (; i < limit; i++) { switch (in.charAt(i)) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': position = i; return; } } position = i; } /** * Returns the {@link JsonToken#NUMBER int} value of the next token, * consuming it. If the next token is a string, this method will attempt to * parse it as an int. If the next token's numeric value cannot be exactly * represented by a Java {@code int}, this method throws. * * @throws IllegalStateException if the next token is not a literal value. * @throws NumberFormatException if the next literal value cannot be parsed * as a number, or exactly represented as an int. */ public int nextInt() { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } int result; if (p == PEEKED_LONG) { result = (int)peekedLong; if (peekedLong != result) { // Make sure no precision was lost casting to 'int'. throw new NumberFormatException("Expected an int but was " + peekedLong + " at line " + getLineNumber() + " column " + getColumnNumber()); } peeked = PEEKED_NONE; return result; } if (p == PEEKED_NUMBER) { int end = position + peekedNumberLength; peekedString = in.subSequence(position, end).toString(); position = end; } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_DOUBLE_QUOTED) { peekedString = nextQuotedValue(p == PEEKED_SINGLE_QUOTED ? '\'' : '"'); try { result = Integer.parseInt(peekedString); peeked = PEEKED_NONE; return result; } catch (NumberFormatException ignored) { // Fall back to parse as a double below. } } else { throw createParseError("Expected an int but was " + peek()); } peeked = PEEKED_BUFFERED; double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException. result = (int)asDouble; if (result != asDouble) { // Make sure no precision was lost casting to 'int'. throw new NumberFormatException("Expected an int but was " + peekedString + " at line " + getLineNumber() + " column " + getColumnNumber()); } peekedString = null; peeked = PEEKED_NONE; return result; } /** * Closes this JSON reader and the underlying {@link java.io.Reader}. */ @Override public void close() { peeked = PEEKED_NONE; stack[0] = JsonScope.CLOSED; stackSize = 1; } /** * Skips the next value recursively. If it is an object or array, all nested * elements are skipped. This method is intended for use when the JSON token * stream contains unrecognized or unhandled values. */ public void skipValue() { int count = 0; do { int p = peeked; if (p == PEEKED_NONE) { p = doPeek(); } if (p == PEEKED_BEGIN_ARRAY) { push(JsonScope.EMPTY_ARRAY); count++; } else if (p == PEEKED_BEGIN_OBJECT) { push(JsonScope.EMPTY_OBJECT); count++; } else if (p == PEEKED_END_ARRAY || p == PEEKED_END_OBJECT) { stackSize--; count--; } else if (p == PEEKED_UNQUOTED_NAME || p == PEEKED_UNQUOTED) { skipUnquotedValue(); } else if (p == PEEKED_SINGLE_QUOTED || p == PEEKED_SINGLE_QUOTED_NAME) { skipQuotedValue('\''); } else if (p == PEEKED_DOUBLE_QUOTED || p == PEEKED_DOUBLE_QUOTED_NAME) { skipQuotedValue('"'); } else if (p == PEEKED_NUMBER) { position += peekedNumberLength; } peeked = PEEKED_NONE; } while (count != 0); } private void push(int newTop) { if (stackSize == stack.length) { int[] newStack = new int[stackSize * 2]; System.arraycopy(stack, 0, newStack, 0, stackSize); stack = newStack; } stack[stackSize++] = newTop; } private int getLineNumber() { int result = 1; for (int i = 0; i < position; i++) { if (in.charAt(i) == '\n') { result++; } } return result; } private int getColumnNumber() { int result = 1; for (int i = 0; i < position; i++) { if (in.charAt(i) == '\n') { result = 1; } else { result++; } } return result; } /** * Returns the next character in the stream that is neither whitespace nor a * part of a comment. When this returns, the returned character is always at * {@code buffer[pos-1]}; this means the caller can always push back the * returned character by decrementing {@code position}. */ private int nextNonWhitespace(boolean throwOnEof) { /* * This code uses ugly local variables 'p' and 'l' representing the 'pos' * and 'limit' fields respectively. Using locals rather than fields saves * a few field reads for each whitespace character in a pretty-printed * document, resulting in a 5% speedup. We need to flush 'p' to its field * before any (potentially indirect) call to fillBuffer() and reread both * 'p' and 'l' after any (potentially indirect) call to the same method. */ CharSequence in = this.in; int p = position; int l = limit; while (true) { if (p == l) { position = p; break; } int c = in.charAt(p++); if (c == '\n' || c == ' ' || c == '\r' || c == '\t') { continue; } if (c == '/') { position = p; if (p == l) { position--; // push back '/' so it's still in the buffer when this method returns boolean charsLoaded = (position + 3) < limit; position++; // consume the '/' again if (!charsLoaded) { return c; } } checkLenient(); char peek = in.charAt(position); switch (peek) { case '*': // skip a /* c-style comment */ position++; if (!skipTo("*/")) { throw createParseError("Unterminated comment"); } p = position + 2; l = limit; continue; case '/': // skip a // end-of-line comment position++; skipToEndOfLine(); p = position; l = limit; continue; default: return c; } } else if (c == '#') { position = p; /* * Skip a # hash end-of-line comment. The JSON RFC doesn't * specify this behaviour, but it's required to parse * existing documents. See http://b/2571423. */ checkLenient(); skipToEndOfLine(); p = position; l = limit; } else { position = p; return c; } } if (throwOnEof) { throw createParseError("End of input"); } else { return -1; } } private void checkLenient() { if (!lenient) { throw createParseError("Use JsonReaderEx.setLenient(true) to accept malformed JSON"); } } /** * Advances the position until after the next newline character. If the line * is terminated by "\r\n", the '\n' must be consumed as whitespace by the * caller. */ private void skipToEndOfLine() { while (position < limit) { char c = in.charAt(position++); if (c == '\n' || c == '\r') { break; } } } private boolean skipTo(@NotNull String toFind) { outer: for (; position + toFind.length() <= limit; position++) { if (in.charAt(position) == '\n') { //lineNumber++; //lineStart = pos + 1; continue; } for (int c = 0; c < toFind.length(); c++) { if (in.charAt(position + c) != toFind.charAt(c)) { continue outer; } } return true; } return false; } @NotNull @Override public String toString() { return getClass().getSimpleName() + " at line " + getLineNumber() + " column " + getColumnNumber(); } /** * Unescapes the character identified by the character or characters that * immediately follow a backslash. The backslash '\' should have already * been read. This supports both unicode escapes "u000A" and two-character * escapes "\n". * * @throws NumberFormatException if any unicode escape sequences are * malformed. */ private char readEscapeCharacter() { if (position == limit) { throw createParseError("Unterminated escape sequence"); } char escaped = in.charAt(position++); switch (escaped) { case 'u': if (position + 4 > limit) { throw createParseError("Unterminated escape sequence"); } // Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16); char result = 0; for (int i = position, end = i + 4; i < end; i++) { char c = in.charAt(i); result <<= 4; if (c >= '0' && c <= '9') { result += (c - '0'); } else if (c >= 'a' && c <= 'f') { result += (c - 'a' + 10); } else if (c >= 'A' && c <= 'F') { result += (c - 'A' + 10); } else { throw new NumberFormatException("\\u" + in.subSequence(position, position + 4)); } } position += 4; return result; case 't': return '\t'; case 'b': return '\b'; case 'n': return '\n'; case 'r': return '\r'; case 'f': return '\f'; case '\n': //lineNumber++; //lineStart = pos; // fall-through case '\'': case '"': case '\\': default: return escaped; } } /** * Throws a new IO exception with the given message and a context snippet * with this reader's content. */ @NotNull private JsonParseException createParseError(String message) { throw new JsonParseException(message + " at line " + getLineNumber() + " column " + getColumnNumber()); } } ================================================ FILE: src/com/goide/dlv/breakpoint/DlvBreakpointProperties.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv.breakpoint; import com.intellij.xdebugger.breakpoints.XBreakpointProperties; import org.jetbrains.annotations.Nullable; public class DlvBreakpointProperties extends XBreakpointProperties { @Nullable @Override public DlvBreakpointProperties getState() { return this; } @Override public void loadState(DlvBreakpointProperties state) { } } ================================================ FILE: src/com/goide/dlv/breakpoint/DlvBreakpointType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv.breakpoint; import com.goide.GoFileType; import com.goide.GoParserDefinition; import com.goide.dlv.DlvDebugProcess; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.Processor; import com.intellij.xdebugger.XDebuggerUtil; import com.intellij.xdebugger.breakpoints.XLineBreakpointType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class DlvBreakpointType extends XLineBreakpointType { public static final String ID = "DlvLineBreakpoint"; public static final String NAME = "Dlv breakpoint"; protected DlvBreakpointType() { super(ID, NAME); } @Nullable @Override public DlvBreakpointProperties createBreakpointProperties(@NotNull VirtualFile file, int line) { return new DlvBreakpointProperties(); } @Override public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) { if (line < 0 || DlvDebugProcess.IS_DLV_DISABLED || file.getFileType() != GoFileType.INSTANCE) return false; return isLineBreakpointAvailable(file, line, project); } private static boolean isLineBreakpointAvailable(@NotNull VirtualFile file, int line, @NotNull Project project) { Document document = FileDocumentManager.getInstance().getDocument(file); if (document == null || document.getLineEndOffset(line) == document.getLineStartOffset(line)) return false; Checker canPutAtChecker = new Checker(); XDebuggerUtil.getInstance().iterateLine(project, document, line, canPutAtChecker); return canPutAtChecker.isLineBreakpointAvailable(); } private static final class Checker implements Processor { private boolean myIsLineBreakpointAvailable; @Override public boolean process(@NotNull PsiElement o) { IElementType type = o.getNode().getElementType(); if (GoParserDefinition.COMMENTS.contains(type) || GoParserDefinition.WHITESPACES.contains(type)) { return true; } myIsLineBreakpointAvailable = true; return false; } public boolean isLineBreakpointAvailable() { return myIsLineBreakpointAvailable; } } } ================================================ FILE: src/com/goide/dlv/protocol/DlvApi.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv.protocol; import com.google.gson.annotations.SerializedName; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import java.util.List; @SuppressWarnings("unused") public class DlvApi { private final static Logger LOG = Logger.getInstance(DlvApi.class); // DebuggerState represents the current context of the debugger. public static class DebuggerState { // Breakpoint is the current breakpoint at which the debugged process is // suspended, and may be empty if the process is not suspended. public Breakpoint breakPoint; // CurrentThread is the currently selected debugger thread. public Thread currentThread; // SelectedGoroutine is the currently selected goroutine public Goroutine currentGoroutine; // Information requested by the current breakpoint public BreakpointInfo breakPointInfo; // Exited indicates whether the debugged process has exited. public boolean exited; public int exitStatus; // Filled by RPCClient.Continue, indicates an error public String err; } // Breakpoint addresses a location at which process execution may be // suspended. public static class Breakpoint { // ID is a unique identifier for the breakpoint. public int id; // Addr is the address of the breakpoint. public int addr; // File is the source file for the breakpoint. public String file; // Line is a line in File for the breakpoint. public int line; // FunctionName is the name of the function at the current breakpoint, and // may not always be available. public String functionName; // tracepoint flag @SerializedName("continue") public boolean tracepoint; // number of stack frames to retrieve public int stacktrace; // retrieve goroutine information public boolean goroutine; // variables to evaluate public List variables; // number of times a breakpoint has been reached in a certain goroutine public Object hitCount; // todo: check type map[string]uint64 // number of times a breakpoint has been reached public long totalHitCount; } // Thread is a thread within the debugged process. public static class Thread { // ID is a unique identifier for the thread. public int id; // PC is the current program counter for the thread. public long pc; // File is the file for the program counter. public String file; // Line is the line number for the program counter. public int line; // Function is function information at the program counter. May be nil. public Function function; } public static class Location { public long pc; public String file; public int line; public Function function; } // Function represents thread-scoped function information. public static class Function { // Name is the function name. public String name; public int value; public byte type; public int goclass; // Args are the function arguments in a thread context. public List args; // Locals are the thread local variables. public List locals; } // Variable describes a variable. public static class Variable { // Name of the variable or struct member public String name; // Go type of the variable public String type; // Address of the variable or struct member public Object addr; // Type of the variable after resolving any typedefs public String realType; public int kind; //Strings have their length capped at proc.maxArrayValues, use Len for the real length of a string //Function variables will store the name of the function in this field public String value; // Number of elements in an array or a slice, number of keys for a map, number of struct members for a struct, length of strings public long len; // Cap value for slices public long cap; // Array and slice elements, member fields of structs, key/value pairs of maps, value of complex numbers // The Name field in this slice will always be the empty string except for structs (when it will be the field name) and for complex numbers (when it will be "real" and "imaginary") // For maps each map entry will have to items in this slice, even numbered items will represent map keys and odd numbered items will represent their values // This field's length is capped at proc.maxArrayValues for slices and arrays and 2*proc.maxArrayValues for maps, in the circumnstances where the cap takes effect len(Children) != Len // The other length cap applied to this field is related to maximum recursion depth, when the maximum recursion depth is reached this field is left empty, contrary to the previous one this cap also applies to structs (otherwise structs will always have all thier member fields returned) public Variable[] children; // Unreadable addresses will have this field set public String unreadable; @NotNull private Kind getKind() { try { return Kind.values()[kind]; } catch (Exception e) { LOG.warn("Unknown kind '" + kind + "' of variable '" + name + "'"); return Kind.Invalid; } } private enum Kind { Invalid, Bool, Int, Int8, Int16, Int32, Int64, Uint, Uint8, Uint16, Uint32, Uint64, Uintptr, Float32, Float64, Complex64, Complex128, Array, Chan, Func, Interface, Map, Ptr, Slice, String, Struct, UnsafePointer; private boolean isNumber() { return compareTo(Int) >= 0 && compareTo(Complex128) <= 0; } } public boolean isSlice() { return getKind() == Kind.Slice; } public boolean isArray() { return getKind() == Kind.Array; } public boolean isNumber() { return getKind().isNumber(); } public boolean isString() { return getKind() == Kind.String; } public boolean isBool() { return getKind() == Kind.Bool; } public boolean isStructure() { return getKind() == Kind.Struct; } public boolean isPtr() { return getKind() == Kind.Ptr; } } // Goroutine represents the information relevant to Delve from the runtime's // internal G structure. public static class Goroutine { // ID is a unique identifier for the goroutine. public int id; // PC is the current program counter for the goroutine. public long pc; // File is the file for the program counter. public String file; // Line is the line number for the program counter. public int line; // Current location of the goroutine public Location currentLoc; // Current location of the goroutine, excluding calls inside runtime public Location userCurrentLoc; // Location of the go instruction that started this goroutine public Location goStatementLoc; } // DebuggerCommand is a command which changes the debugger's execution state. public static class DebuggerCommand { // Name is the command to run. public String name; // ThreadID is used to specify which thread to use with the SwitchThread // command. public int threadID; // GoroutineID is used to specify which thread to use with the SwitchGoroutine // command. public int goroutineID; // `json:"goroutineID,omitempty"` } // Informations about the current breakpoint public static class BreakpointInfo { public List stacktrace; public Goroutine goroutine; public List variables; public List arguments; } public static class EvalScope { public int GoroutineID; public int Frame; } public static final String CONTINUE = "continue"; public static final String STEP = "step"; public static final String NEXT = "next"; public static final String SWITCH_THREAD = "switchThread"; public static final String HALT = "halt"; public static final String SWITCH_GOROUTINE = "switchGoroutine"; } ================================================ FILE: src/com/goide/dlv/protocol/DlvRequest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv.protocol; import com.google.gson.stream.JsonWriter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jsonProtocol.OutMessage; import org.jetbrains.jsonProtocol.Request; import java.io.IOException; import java.util.List; /** * Please add your requests as a subclasses, otherwise reflection won't work. * * @param type of callback * @see com.goide.dlv.DlvCommandProcessor#getResultType(String) */ public abstract class DlvRequest extends OutMessage implements Request { private static final String PARAMS = "params"; private static final String ID = "id"; private boolean argumentsObjectStarted; private DlvRequest() { try { getWriter().name("method").value(getMethodName()); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull @Override public String getMethodName() { return "RPCServer." + getClass().getSimpleName(); } @Override public final void beginArguments() { if (!argumentsObjectStarted) { argumentsObjectStarted = true; if (needObject()) { try { getWriter().name(PARAMS); getWriter().beginArray(); getWriter().beginObject(); } catch (IOException e) { throw new RuntimeException(e); } } } } protected boolean needObject() { return true; } @Override public final void finalize(int id) { try { if (argumentsObjectStarted) { if (needObject()) { getWriter().endObject(); getWriter().endArray(); } } getWriter().name(ID).value(id); getWriter().endObject(); getWriter().close(); } catch (IOException e) { throw new RuntimeException(e); } } public final static class ClearBreakpoint extends DlvRequest { public ClearBreakpoint(int id) { writeSingletonIntArray(PARAMS, id); } @Override protected boolean needObject() { return false; } } public final static class CreateBreakpoint extends DlvRequest { public CreateBreakpoint(String path, int line) { writeString("file", path); writeLong("line", line); } } public final static class StacktraceGoroutine extends DlvRequest> { public StacktraceGoroutine() { writeLong("Id", -1); writeLong("Depth", 100); } } private abstract static class Locals extends DlvRequest { Locals(int frameId) { writeLong("GoroutineID", -1); writeLong("Frame", frameId); } } public final static class ListLocalVars extends Locals> { public ListLocalVars(int frameId) { super(frameId); } } public final static class ListFunctionArgs extends Locals> { public ListFunctionArgs(int frameId) { super(frameId); } } public final static class Command extends DlvRequest { public Command(@Nullable String command) { writeString("Name", command); } } public final static class Detach extends DlvRequest { public Detach(boolean kill) { try { beginArguments(); getWriter().name(PARAMS).beginArray().value(kill).endArray(); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected boolean needObject() { return false; } } public final static class EvalSymbol extends DlvRequest { public EvalSymbol(@NotNull String symbol, int frameId) { try { getWriter().name(PARAMS).beginArray(); writeScope(frameId, getWriter()) .name("Symbol").value(symbol) .endObject().endArray(); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected boolean needObject() { return false; } } @NotNull private static JsonWriter writeScope(int frameId, @NotNull JsonWriter writer) throws IOException { // todo: ask vladimir how to simplify this return writer.beginObject() .name("Scope").beginObject() .name("GoroutineID").value(-1) .name("Frame").value(frameId).endObject(); } public final static class SetSymbol extends DlvRequest { public SetSymbol(@NotNull String symbol, @NotNull String value, int frameId) { try { getWriter().name(PARAMS).beginArray(); writeScope(frameId, getWriter()) .name("Symbol").value(symbol) .name("Value").value(value) .endObject().endArray(); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected boolean needObject() { return false; } } } ================================================ FILE: src/com/goide/dlv/protocol/DlvResponse.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.dlv.protocol; import com.goide.dlv.JsonReaderEx; import com.google.gson.stream.JsonToken; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jsonProtocol.JsonType; import org.jetbrains.jsonProtocol.Optional; import java.util.Collections; import java.util.List; @JsonType public interface DlvResponse { int id(); @Nullable @Optional JsonReaderEx result(); @Nullable @Optional ErrorInfo error(); @JsonType interface ErrorInfo { @Nullable String message(); @NotNull @Optional List data(); int code(); } final class CommandResponseImpl implements DlvResponse { @Nullable private DlvResponse.ErrorInfo _error; private int _id = -1; @Nullable private JsonReaderEx _result; public CommandResponseImpl(@NotNull JsonReaderEx reader, @Nullable String name) { if (name == null) { if (reader.hasNext() && reader.beginObject().hasNext()) { name = reader.nextName(); } else { return; } } do { if ("error".equals(name)) { _error = new M5m(reader); } else if ("id".equals(name)) { _id = reader.nextInt(); } else if ("result".equals(name)) { _result = reader.subReader(); reader.skipValue(); } else { reader.skipValue(); } } while ((name = reader.nextNameOrNull()) != null); reader.endObject(); } @Nullable @Override public DlvResponse.ErrorInfo error() { return _error; } @Override public int id() { return _id; } @Nullable @Override public JsonReaderEx result() { return _result; } } final class M5m implements DlvResponse.ErrorInfo { private static final int _code = -1; @NotNull private final List _data = Collections.emptyList(); @Nullable private final String _message; M5m(@NotNull JsonReaderEx reader) { _message = nextNullableString(reader); } @Override public int code() { return _code; } @NotNull @Override public List data() { return _data; } @Nullable @Override public String message() { return _message; } private static String nextNullableString(@NotNull JsonReaderEx reader) { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { return reader.nextString(); } } } } ================================================ FILE: src/com/goide/editor/GoBraceMatcher.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.intellij.lang.BracePair; import com.intellij.lang.PairedBraceMatcher; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoBraceMatcher implements PairedBraceMatcher { private static final BracePair[] PAIRS = new BracePair[]{ new BracePair(GoTypes.LBRACE, GoTypes.RBRACE, true), new BracePair(GoTypes.LPAREN, GoTypes.RPAREN, false), new BracePair(GoTypes.LBRACK, GoTypes.RBRACK, false), }; @NotNull @Override public BracePair[] getPairs() { return PAIRS; } @Override public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lbraceType, @Nullable IElementType type) { return GoParserDefinition.COMMENTS.contains(type) || GoParserDefinition.WHITESPACES.contains(type) || type == GoTypes.SEMICOLON || type == GoTypes.COMMA || type == GoTypes.RPAREN || type == GoTypes.RBRACK || type == GoTypes.RBRACE || type == GoTypes.LBRACE || null == type; } @Override public int getCodeConstructStart(PsiFile file, int openingBraceOffset) { return openingBraceOffset; } } ================================================ FILE: src/com/goide/editor/GoFoldingBuilder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.goide.psi.*; import com.intellij.codeInsight.folding.CodeFoldingSettings; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.CustomFoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.lang.folding.NamedFoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; public class GoFoldingBuilder extends CustomFoldingBuilder implements DumbAware { private static void foldTypes(@Nullable PsiElement e, @NotNull List result) { if (e instanceof GoStructType) { if (((GoStructType)e).getFieldDeclarationList().isEmpty()) return; fold(e, ((GoStructType)e).getLbrace(), ((GoStructType)e).getRbrace(), "{...}", result); } if (e instanceof GoInterfaceType) { if (e.getChildren().length == 0) return; fold(e, ((GoInterfaceType)e).getLbrace(), ((GoInterfaceType)e).getRbrace(), "{...}", result); } } private static void fold(@NotNull PsiElement e, @Nullable PsiElement l, @Nullable PsiElement r, @NotNull String placeholderText, @NotNull List result) { if (l != null && r != null) { result.add(new NamedFoldingDescriptor(e, l.getTextRange().getStartOffset(), r.getTextRange().getEndOffset(), null, placeholderText)); } } // com.intellij.codeInsight.folding.impl.JavaFoldingBuilderBase.addCodeBlockFolds() private static void addCommentFolds(@NotNull PsiElement comment, @NotNull Set processedComments, @NotNull List result) { if (processedComments.contains(comment)) return; PsiElement end = null; for (PsiElement current = comment.getNextSibling(); current != null; current = current.getNextSibling()) { ASTNode node = current.getNode(); if (node == null) break; IElementType elementType = node.getElementType(); if (elementType == GoParserDefinition.LINE_COMMENT) { end = current; processedComments.add(current); continue; } if (elementType == TokenType.WHITE_SPACE) continue; break; } if (end != null) { int startOffset = comment.getTextRange().getStartOffset(); int endOffset = end.getTextRange().getEndOffset(); result.add(new NamedFoldingDescriptor(comment, startOffset, endOffset, null, "/.../")); } } @Override protected void buildLanguageFoldRegions(@NotNull List result, @NotNull PsiElement root, @NotNull Document document, boolean quick) { if (!(root instanceof GoFile)) return; GoFile file = (GoFile)root; if (!file.isContentsLoaded()) return; GoImportList importList = ((GoFile)root).getImportList(); if (importList != null) { GoImportDeclaration firstImport = ContainerUtil.getFirstItem(importList.getImportDeclarationList()); if (firstImport != null) { PsiElement importKeyword = firstImport.getImport(); int offset = importKeyword.getTextRange().getEndOffset(); int startOffset = importKeyword.getNextSibling() instanceof PsiWhiteSpace ? offset + 1 : offset; int endOffset = importList.getTextRange().getEndOffset(); if (endOffset - startOffset > 3) { result.add(new NamedFoldingDescriptor(importList, startOffset, endOffset, null, "...")); } } } for (GoBlock block : PsiTreeUtil.findChildrenOfType(file, GoBlock.class)) { if (block.getTextRange().getLength() > 1) { result.add(new NamedFoldingDescriptor(block.getNode(), block.getTextRange(), null, "{...}")); } } for (GoExprSwitchStatement switchStatement : PsiTreeUtil.findChildrenOfType(file, GoExprSwitchStatement.class)) { fold(switchStatement, switchStatement.getLbrace(), switchStatement.getRbrace(), "{...}", result); } for (GoSelectStatement selectStatement : PsiTreeUtil.findChildrenOfType(file, GoSelectStatement.class)) { fold(selectStatement, selectStatement.getLbrace(), selectStatement.getRbrace(), "{...}", result); } for (GoTypeSpec type : file.getTypes()) { foldTypes(type.getSpecType().getType(), result); } for (GoCaseClause caseClause : PsiTreeUtil.findChildrenOfType(file, GoCaseClause.class)) { PsiElement colon = caseClause.getColon(); if (colon != null && !caseClause.getStatementList().isEmpty()) { fold(caseClause, colon.getNextSibling(), caseClause, "...", result); } } for (GoCommClause commClause : PsiTreeUtil.findChildrenOfType(file, GoCommClause.class)) { PsiElement colon = commClause.getColon(); if (colon != null && !commClause.getStatementList().isEmpty()) { fold(commClause, colon.getNextSibling(), commClause, "...", result); } } for (GoVarDeclaration varDeclaration : PsiTreeUtil.findChildrenOfType(file, GoVarDeclaration.class)) { if (varDeclaration.getVarSpecList().size() > 1) { fold(varDeclaration, varDeclaration.getLparen(), varDeclaration.getRparen(), "(...)", result); } } for (GoConstDeclaration constDeclaration : PsiTreeUtil.findChildrenOfType(file, GoConstDeclaration.class)) { if (constDeclaration.getConstSpecList().size() > 1) { fold(constDeclaration, constDeclaration.getLparen(), constDeclaration.getRparen(), "(...)", result); } } for (GoTypeDeclaration typeDeclaration : PsiTreeUtil.findChildrenOfType(file, GoTypeDeclaration.class)) { if (typeDeclaration.getTypeSpecList().size() > 1) { fold(typeDeclaration, typeDeclaration.getLparen(), typeDeclaration.getRparen(), "(...)", result); } } for (GoCompositeLit compositeLit : PsiTreeUtil.findChildrenOfType(file, GoCompositeLit.class)) { GoLiteralValue literalValue = compositeLit.getLiteralValue(); if (literalValue != null && literalValue.getElementList().size() > 1) { fold(literalValue, literalValue.getLbrace(), literalValue.getRbrace(), "{...}", result); } } if (!quick) { Set processedComments = ContainerUtil.newHashSet(); PsiTreeUtil.processElements(file, element -> { ASTNode node = element.getNode(); IElementType type = node.getElementType(); TextRange range = element.getTextRange(); if (type == GoParserDefinition.MULTILINE_COMMENT && range.getLength() > 2) { result.add(new NamedFoldingDescriptor(node, range, null, "/*...*/")); } if (type == GoParserDefinition.LINE_COMMENT) { addCommentFolds(element, processedComments, result); } foldTypes(element, result); // folding for inner types return true; }); } } @Nullable @Override protected String getLanguagePlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) { return "..."; } @Override protected boolean isRegionCollapsedByDefault(@NotNull ASTNode node) { IElementType type = node.getElementType(); if (type == GoParserDefinition.LINE_COMMENT || type == GoParserDefinition.MULTILINE_COMMENT) { return CodeFoldingSettings.getInstance().COLLAPSE_DOC_COMMENTS; } if (type == GoTypes.BLOCK && CodeFoldingSettings.getInstance().COLLAPSE_METHODS) { ASTNode parent = node.getTreeParent(); return parent != null && parent.getPsi() instanceof GoFunctionOrMethodDeclaration; } return CodeFoldingSettings.getInstance().COLLAPSE_IMPORTS && node.getElementType() == GoTypes.IMPORT_LIST; } } ================================================ FILE: src/com/goide/editor/GoImplementationTextSelectioner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.psi.GoTopLevelDeclaration; import com.intellij.codeInsight.hint.ImplementationTextSelectioner; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; public class GoImplementationTextSelectioner implements ImplementationTextSelectioner { @Override public int getTextStartOffset(@NotNull PsiElement o) { return getTextRange(o).getStartOffset(); } @Override public int getTextEndOffset(@NotNull PsiElement o) { return getTextRange(o).getEndOffset(); } @NotNull private static TextRange getTextRange(@NotNull PsiElement o) { return ObjectUtils.notNull(PsiTreeUtil.getParentOfType(o, GoTopLevelDeclaration.class), o).getTextRange(); } } ================================================ FILE: src/com/goide/editor/GoParameterInfoHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoTypes; import com.goide.psi.*; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.lang.parameterInfo.*; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; public class GoParameterInfoHandler implements ParameterInfoHandlerWithTabActionSupport { @NotNull @Override public GoExpression[] getActualParameters(@NotNull GoArgumentList o) { return ArrayUtil.toObjectArray(o.getExpressionList(), GoExpression.class); } @NotNull @Override public IElementType getActualParameterDelimiterType() { return GoTypes.COMMA; } @NotNull @Override public IElementType getActualParametersRBraceType() { return GoTypes.RPAREN; } @NotNull @Override public Set getArgumentListAllowedParentClasses() { return ContainerUtil.newHashSet(); } @NotNull @Override public Set getArgListStopSearchClasses() { return ContainerUtil.newHashSet(); } @NotNull @Override public Class getArgumentListClass() { return GoArgumentList.class; } @Override public boolean couldShowInLookup() { return true; } @Nullable @Override public Object[] getParametersForLookup(LookupElement item, ParameterInfoContext context) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Nullable @Override public Object[] getParametersForDocumentation(Object p, ParameterInfoContext context) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Nullable @Override public GoArgumentList findElementForParameterInfo(@NotNull CreateParameterInfoContext context) { // todo: see ParameterInfoUtils.findArgumentList return getList(context); } @Nullable private static GoArgumentList getList(@NotNull ParameterInfoContext context) { PsiElement at = context.getFile().findElementAt(context.getOffset()); return PsiTreeUtil.getParentOfType(at, GoArgumentList.class); } @Override public void showParameterInfo(@NotNull GoArgumentList argList, @NotNull CreateParameterInfoContext context) { PsiElement parent = argList.getParent(); if (!(parent instanceof GoCallExpr)) return; GoFunctionType type = findFunctionType(((GoCallExpr)parent).getExpression().getGoType(null)); if (type != null) { context.setItemsToShow(new Object[]{type}); context.showHint(argList, argList.getTextRange().getStartOffset(), this); } } @Nullable private static GoFunctionType findFunctionType(@Nullable GoType type) { if (type instanceof GoFunctionType || type == null) return (GoFunctionType)type; GoType base = type.getUnderlyingType(); return base instanceof GoFunctionType ? (GoFunctionType)base : null; } @Nullable @Override public GoArgumentList findElementForUpdatingParameterInfo(@NotNull UpdateParameterInfoContext context) { return getList(context); } @Override public void updateParameterInfo(@NotNull GoArgumentList list, @NotNull UpdateParameterInfoContext context) { context.setCurrentParameter(ParameterInfoUtils.getCurrentParameterIndex(list.getNode(), context.getOffset(), GoTypes.COMMA)); } @Nullable @Override public String getParameterCloseChars() { return ",("; } @Override public boolean tracksParameterIndex() { return true; } @Override public void updateUI(@Nullable Object p, @NotNull ParameterInfoUIContext context) { updatePresentation(p, context); } static String updatePresentation(@Nullable Object p, @NotNull ParameterInfoUIContext context) { if (p == null) { context.setUIComponentEnabled(false); return null; } GoSignature signature = p instanceof GoSignatureOwner ? ((GoSignatureOwner)p).getSignature() : null; if (signature == null) return null; GoParameters parameters = signature.getParameters(); List parametersPresentations = getParameterPresentations(parameters, PsiElement::getText); StringBuilder builder = new StringBuilder(); int start = 0; int end = 0; if (!parametersPresentations.isEmpty()) { // Figure out what particular presentation is actually selected. Take in // account possibility of the last variadic parameter. int selected = isLastParameterVariadic(parameters.getParameterDeclarationList()) ? Math.min(context.getCurrentParameterIndex(), parametersPresentations.size() - 1) : context.getCurrentParameterIndex(); for (int i = 0; i < parametersPresentations.size(); ++i) { if (i != 0) { builder.append(", "); } if (i == selected) { start = builder.length(); } builder.append(parametersPresentations.get(i)); if (i == selected) { end = builder.length(); } } } else { builder.append(CodeInsightBundle.message("parameter.info.no.parameters")); } return context.setupUIComponentPresentation(builder.toString(), start, end, false, false, false, context.getDefaultParameterColor()); } /** * Creates a list of parameter presentations. For clarity we expand parameters declared as `a, b, c int` into `a int, b int, c int`. */ @NotNull public static List getParameterPresentations(@NotNull GoParameters parameters, @NotNull Function typePresentationFunction) { List paramDeclarations = parameters.getParameterDeclarationList(); List paramPresentations = ContainerUtil.newArrayListWithCapacity(2 * paramDeclarations.size()); for (GoParameterDeclaration paramDeclaration : paramDeclarations) { boolean isVariadic = paramDeclaration.isVariadic(); List paramDefinitionList = paramDeclaration.getParamDefinitionList(); for (GoParamDefinition paramDefinition : paramDefinitionList) { String separator = isVariadic ? " ..." : " "; paramPresentations.add(paramDefinition.getText() + separator + typePresentationFunction.fun(paramDeclaration.getType())); } if (paramDefinitionList.isEmpty()) { String separator = isVariadic ? "..." : ""; paramPresentations.add(separator + typePresentationFunction.fun(paramDeclaration.getType())); } } return paramPresentations; } private static boolean isLastParameterVariadic(@NotNull List declarations) { GoParameterDeclaration lastItem = ContainerUtil.getLastItem(declarations); return lastItem != null && lastItem.isVariadic(); } } ================================================ FILE: src/com/goide/editor/GoQuoteHandler.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoTypes; import com.intellij.codeInsight.editorActions.JavaLikeQuoteHandler; import com.intellij.codeInsight.editorActions.SimpleTokenSetQuoteHandler; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.psi.PsiElement; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; public class GoQuoteHandler extends SimpleTokenSetQuoteHandler implements JavaLikeQuoteHandler { private static final TokenSet SINGLE_LINE_LITERALS = TokenSet.create(GoTypes.STRING); public GoQuoteHandler() { super(GoTypes.STRING, GoTypes.RAW_STRING, GoTypes.CHAR, TokenType.BAD_CHARACTER); } @Override public boolean hasNonClosedLiteral(Editor editor, HighlighterIterator iterator, int offset) { return true; } @Override public TokenSet getConcatenatableStringTokenTypes() { return SINGLE_LINE_LITERALS; } @Override public String getStringConcatenationOperatorRepresentation() { return "+"; } @Override public TokenSet getStringTokenTypes() { return SINGLE_LINE_LITERALS; } @Override public boolean isAppropriateElementTypeForLiteral(@NotNull IElementType tokenType) { return true; } @Override public boolean needParenthesesAroundConcatenation(PsiElement element) { return false; } } ================================================ FILE: src/com/goide/editor/GoStatementMover.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.psi.*; import com.intellij.codeInsight.editorActions.moveUpDown.LineMover; import com.intellij.codeInsight.editorActions.moveUpDown.LineRange; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoStatementMover extends LineMover { @Override public boolean checkAvailable(@NotNull Editor editor, @NotNull PsiFile file, @NotNull MoveInfo info, boolean down) { if (!(file instanceof GoFile && super.checkAvailable(editor, file, info, down))) return false; Couple primeElementRange = getElementRange(editor, file); if (primeElementRange == null) return false; PsiElement commonParent = primeElementRange.first.isEquivalentTo(primeElementRange.second) ? primeElementRange.first.getParent() : PsiTreeUtil.findCommonParent(primeElementRange.first, primeElementRange.second); if (commonParent == null) return false; Couple elementRange = getTopmostElementRange(primeElementRange, commonParent); if (elementRange == null) return false; if (commonParent == elementRange.first) commonParent = commonParent.getParent(); info.toMove = new LineRange(elementRange.first, elementRange.second); if (elementRange.first instanceof GoTopLevelDeclaration && commonParent instanceof GoFile) { PsiElement toMove2 = getNeighborOfType(elementRange, GoTopLevelDeclaration.class, down); info.toMove2 = toMove2 != null ? new LineRange(toMove2) : null; return true; } if (commonParent instanceof GoImportList) { PsiElement toMove2 = getNeighborOfType(elementRange, GoImportDeclaration.class, down); info.toMove2 = toMove2 != null ? new LineRange(toMove2) : null; return true; } return setUpInfo(info, elementRange, commonParent, down); } private static Couple getElementRange(@NotNull Editor editor, @NotNull PsiFile file) { Pair primeElementRangePair = getElementRange(editor, file, getLineRangeFromSelection(editor)); if (primeElementRangePair == null) return null; ASTNode firstNode = TreeUtil.findFirstLeaf(primeElementRangePair.first.getNode()); ASTNode lastNode = TreeUtil.findLastLeaf(primeElementRangePair.second.getNode()); if (firstNode == null || lastNode == null) return null; return Couple.of(firstNode.getPsi(), lastNode.getPsi()); } /** * Return element range which contains TextRange(start, end) of top level elements * common parent of elements is straight parent for each element */ @Nullable private static Couple getTopmostElementRange(@NotNull Couple elementRange, @NotNull PsiElement commonParent) { if (elementRange.first == null || elementRange.second == null) return null; int start = elementRange.first.getTextOffset(); int end = elementRange.second.getTextRange().getEndOffset(); TextRange range = commonParent.getTextRange(); PsiElement[] children = commonParent.getChildren(); if (commonParent.isEquivalentTo(elementRange.first) || commonParent.isEquivalentTo(elementRange.second) || range.getStartOffset() == start && (children.length == 0 || children[0].getTextRange().getStartOffset() > start) || range.getEndOffset() == end && (children.length == 0 || children[children.length - 1].getTextRange().getEndOffset() < end)) { return Couple.of(commonParent, commonParent); } PsiElement startElement = elementRange.first; PsiElement endElement = elementRange.second; for (PsiElement element : children) { range = element.getTextRange(); if (range.contains(start) && !range.contains(end)) { startElement = element; } if (range.contains(end - 1) && !range.contains(start - 1)) { endElement = element; } } return startElement.getParent().isEquivalentTo(endElement.getParent()) ? Couple.of(startElement, endElement) : null; } private static boolean setUpInfo(@NotNull MoveInfo info, @NotNull Couple range, @NotNull PsiElement commonParent, boolean down) { info.toMove = new LineRange(range.first, range.second); info.toMove2 = null; if (range.first instanceof GoPackageClause) return true; PsiElement topLevelElement = PsiTreeUtil.findPrevParent(commonParent.getContainingFile(), commonParent); int nearLine = down ? info.toMove.endLine : info.toMove.startLine - 1; LineRange lineRange = new LineRange(topLevelElement); if (!lineRange.containsLine(down ? info.toMove.endLine + 1 : info.toMove.startLine - 2)) { return true; } info.toMove2 = lineRange.containsLine(down ? info.toMove.endLine + 1 : info.toMove.startLine - 2) ? new LineRange(nearLine, nearLine + 1) : null; return true; } @Nullable private static PsiElement getNeighborOfType(@NotNull Couple range, @NotNull Class clazz, boolean rightNeighbor) { return rightNeighbor ? PsiTreeUtil.getNextSiblingOfType(range.second, clazz) : PsiTreeUtil.getPrevSiblingOfType(range.first, clazz); } } ================================================ FILE: src/com/goide/editor/GoTypeDeclarationProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.psi.GoNamedElement; import com.goide.psi.GoType; import com.goide.psi.GoTypeReferenceExpression; import com.intellij.codeInsight.navigation.actions.TypeDeclarationProvider; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoTypeDeclarationProvider implements TypeDeclarationProvider { @Nullable @Override public PsiElement[] getSymbolTypeDeclarations(@NotNull PsiElement element) { if (!(element instanceof GoNamedElement)) return PsiElement.EMPTY_ARRAY; GoType type = ((GoNamedElement)element).getGoType(null); GoTypeReferenceExpression ref = type != null ? type.getTypeReferenceExpression() : null; PsiElement resolve = ref != null ? ref.resolve() : type; // todo: think about better fallback instead of `type` return resolve != null ? new PsiElement[]{resolve} : PsiElement.EMPTY_ARRAY; } } ================================================ FILE: src/com/goide/editor/GoTypedHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.intellij.codeInsight.template.impl.editorActions.TypedActionHandlerBase; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.TypedActionHandler; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.PsiUtilBase; import org.jetbrains.annotations.NotNull; public class GoTypedHandler extends TypedActionHandlerBase { public GoTypedHandler(TypedActionHandler originalHandler) { super(originalHandler); } @Override public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) { if (myOriginalHandler != null) myOriginalHandler.execute(editor, c, dataContext); if (c != 'e') return; Project project = editor.getProject(); if (project == null) return; int offset = editor.getCaretModel().getOffset(); if (offset < 4) return; TextRange from = TextRange.from(offset - 4, 4); String text = editor.getDocument().getText(from); if ("case".equals(text)) { PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); ApplicationManager.getApplication().runWriteAction(() -> { if (project.isDisposed()) return; PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project); if (file == null) return; CodeStyleManager.getInstance(project).adjustLineIndent(file, from); }); } } } ================================================ FILE: src/com/goide/editor/GoWordSelectioner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.psi.*; import com.intellij.codeInsight.editorActions.wordSelection.AbstractWordSelectioner; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.TextRange; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoWordSelectioner extends AbstractWordSelectioner { @Override public boolean canSelect(@NotNull PsiElement e) { return e.getContainingFile() instanceof GoFile; } @Override public List select(@NotNull PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { PsiElement parent = e.getParent(); List result = super.select(e, editorText, cursorOffset, editor); if (parent instanceof GoImportString || parent instanceof GoStringLiteral) { result.add(ElementManipulators.getValueTextRange(parent).shiftRight(parent.getTextRange().getStartOffset())); } else if (parent instanceof GoImportDeclaration) { result.addAll(extend(editorText, ((GoImportDeclaration)parent).getImportSpecList(), false)); } else if (e instanceof GoSimpleStatement) { result.addAll(expandToWholeLine(editorText, e.getTextRange())); } else if (e instanceof GoArgumentList || e instanceof GoParameters) { if (e.getTextLength() > 2) { result.add(TextRange.create(e.getTextRange().getStartOffset() + 1, e.getTextRange().getEndOffset() - 1)); } } else if (e instanceof GoBlock) { result.addAll(extend(editorText, ((GoBlock)e).getStatementList(), true)); } else if (parent instanceof GoNamedSignatureOwner) { GoSignature signature = ((GoNamedSignatureOwner)parent).getSignature(); if (signature != null) { int nameStartOffset = parent.getTextOffset(); result.add(TextRange.create(nameStartOffset, signature.getParameters().getTextRange().getEndOffset())); result.add(TextRange.create(nameStartOffset, signature.getTextRange().getEndOffset())); } } return result; } @NotNull private static List extend(@NotNull CharSequence editorText, @NotNull List list, boolean expand) { PsiElement first = ContainerUtil.getFirstItem(list); PsiElement last = ContainerUtil.getLastItem(list); if (first != null && last != null) { TextRange range = TextRange.create(first.getTextRange().getStartOffset(), last.getTextRange().getEndOffset()); if (!expand) return ContainerUtil.newSmartList(range); return expandToWholeLine(editorText, range); } return ContainerUtil.emptyList(); } } ================================================ FILE: src/com/goide/editor/marker/GoMethodSeparatorProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.marker; import com.goide.psi.GoFile; import com.goide.psi.GoTopLevelDeclaration; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.codeInsight.daemon.impl.LineMarkersPass; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; public class GoMethodSeparatorProvider implements LineMarkerProvider { private final DaemonCodeAnalyzerSettings myDaemonSettings; private final EditorColorsManager myColorsManager; public GoMethodSeparatorProvider(DaemonCodeAnalyzerSettings daemonSettings, EditorColorsManager colorsManager) { myDaemonSettings = daemonSettings; myColorsManager = colorsManager; } @Nullable @Override public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement o) { if (myDaemonSettings.SHOW_METHOD_SEPARATORS && o instanceof GoTopLevelDeclaration && o.getParent() instanceof GoFile) { return LineMarkersPass.createMethodSeparatorLineMarker(findAnchorElement((GoTopLevelDeclaration)o), myColorsManager); } return null; } @Override public void collectSlowLineMarkers(@NotNull List elements, @NotNull Collection result) { } @NotNull private static PsiElement findAnchorElement(@NotNull GoTopLevelDeclaration o) { PsiElement result = o; PsiElement p = o; while ((p = p.getPrevSibling()) != null) { if (p instanceof PsiComment) { result = p; } else if (p instanceof PsiWhiteSpace) { if (p.getText().contains("\n\n")) return result; } else { break; } } return result; } } ================================================ FILE: src/com/goide/editor/smart/GoSmartEnterProcessor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.smart; import com.goide.inspections.GoDeferGoInspection; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.intellij.lang.SmartEnterProcessorWithFixers; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class GoSmartEnterProcessor extends SmartEnterProcessorWithFixers { public GoSmartEnterProcessor() { addFixers(new IfFixer(), new ForFixer(), new FuncFixer(), new GoDeferExpressionFixer()); addEnterProcessors(new PlainEnterProcessor()); } private static void addBlockIfNeeded(@NotNull GoStatement element) { if (element.getBlock() == null) element.add(GoElementFactory.createBlock(element.getProject())); } @Override public boolean doNotStepInto(PsiElement element) { return element instanceof GoBlock; } @Override protected void collectAdditionalElements(@NotNull PsiElement element, @NotNull List result) { element = PsiTreeUtil.getParentOfType(element, GoStatement.class, GoFunctionOrMethodDeclaration.class, GoFunctionLit.class); if (element != null) { result.add(element); PsiElement parent = element.getParent(); if (parent instanceof GoStatement) { result.add(parent); } } } private static class GoDeferExpressionFixer extends Fixer { @Override public void apply(@NotNull Editor editor, @NotNull SmartEnterProcessorWithFixers processor, @NotNull PsiElement element) throws IncorrectOperationException { Project project = element.getProject(); if (element instanceof GoGoStatement) { PsiElement expr = GoDeferGoInspection.GoAddParensQuickFix.addParensIfNeeded(project, ((GoGoStatement)element).getExpression()); if (expr != null) { element.replace(GoElementFactory.createGoStatement(project, expr.getText())); } } else if (element instanceof GoDeferStatement) { PsiElement expr = GoDeferGoInspection.GoAddParensQuickFix.addParensIfNeeded(project, ((GoDeferStatement)element).getExpression()); if (expr != null) { element.replace(GoElementFactory.createDeferStatement(project, expr.getText())); } } } } private static class FuncFixer extends Fixer { @Override public void apply(@NotNull Editor editor, @NotNull SmartEnterProcessorWithFixers processor, @NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof GoFunctionOrMethodDeclaration && ((GoFunctionOrMethodDeclaration)element).getBlock() == null) { element.add(GoElementFactory.createBlock(element.getProject())); } if (element instanceof GoFunctionLit && ((GoFunctionLit)element).getBlock() == null) { element.add(GoElementFactory.createBlock(element.getProject())); } } } private static class IfFixer extends Fixer { @Override public void apply(@NotNull Editor editor, @NotNull SmartEnterProcessorWithFixers processor, @NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof GoIfStatement) addBlockIfNeeded((GoIfStatement)element); } } private static class ForFixer extends Fixer { @Override public void apply(@NotNull Editor editor, @NotNull SmartEnterProcessorWithFixers processor, @NotNull PsiElement element) throws IncorrectOperationException { if (element instanceof GoForStatement) addBlockIfNeeded((GoStatement)element); } } public static class PlainEnterProcessor extends FixEnterProcessor { @Nullable private static GoBlock findBlock(@Nullable PsiElement element) { element = PsiTreeUtil.getNonStrictParentOfType(element, GoStatement.class, GoBlock.class, GoFunctionOrMethodDeclaration.class, GoFunctionLit.class); if (element instanceof GoSimpleStatement && element.getParent() instanceof GoStatement) { element = element.getParent(); } if (element instanceof GoIfStatement) return ((GoIfStatement)element).getBlock(); if (element instanceof GoForStatement) return ((GoForStatement)element).getBlock(); if (element instanceof GoBlock) return (GoBlock)element; if (element instanceof GoFunctionOrMethodDeclaration) return ((GoFunctionOrMethodDeclaration)element).getBlock(); if (element instanceof GoFunctionLit) return ((GoFunctionLit)element).getBlock(); return null; } @Override public boolean doEnter(PsiElement psiElement, PsiFile file, @NotNull Editor editor, boolean modified) { GoBlock block = findBlock(psiElement); if (block != null) { editor.getCaretModel().moveToOffset(block.getLbrace().getTextRange().getEndOffset()); } plainEnter(editor); return true; } } } ================================================ FILE: src/com/goide/editor/surround/GoBoolExpressionSurrounderBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoExpression; import com.goide.psi.GoIfStatement; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoTypeUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoBoolExpressionSurrounderBase extends GoExpressionSurrounder { @Override public boolean isApplicable(@NotNull PsiElement[] elements) { GoExpression expression = getExpression(elements); return expression != null && GoTypeUtil.isBoolean(expression.getGoType(null)); } @Nullable protected TextRange surroundExpressionWithIfElse(@NotNull PsiElement[] elements, boolean withElse) { GoExpression expression = getExpression(elements); if (expression == null) return null; String condition = expression.getText(); GoIfStatement ifStatement = GoElementFactory.createIfStatement(expression.getProject(), condition, "", withElse ? "" : null); PsiElement replace = expression.replace(ifStatement); int offset = replace.getTextRange().getEndOffset(); return TextRange.create(offset, offset); } } ================================================ FILE: src/com/goide/editor/surround/GoExpressionSurroundDescriptor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoExpression; import com.goide.refactor.GoIntroduceVariableBase; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.internal.statistic.UsageTrigger; import com.intellij.lang.surroundWith.SurroundDescriptor; import com.intellij.lang.surroundWith.Surrounder; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoExpressionSurroundDescriptor implements SurroundDescriptor { private static final Surrounder[] SURROUNDERS = new Surrounder[]{ new GoWithParenthesisSurrounder(), new GoWithIfExpressionSurrounder(), new GoWithIfElseExpressionSurrounder(), new GoWithNotExpressionSurrounder() }; @NotNull @Override public Surrounder[] getSurrounders() { return SURROUNDERS; } @NotNull @Override public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) { GoExpression expr = GoIntroduceVariableBase.findExpressionInSelection(file, startOffset, endOffset); if (expr == null) return PsiElement.EMPTY_ARRAY; UsageTrigger.trigger("go.surroundwith.expression"); FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.surroundwith.expression"); return new PsiElement[]{expr}; } @Override public boolean isExclusive() { return false; } } ================================================ FILE: src/com/goide/editor/surround/GoExpressionSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoExpression; import com.goide.psi.impl.GoElementFactory; import com.intellij.lang.surroundWith.Surrounder; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoExpressionSurrounder implements Surrounder { @Override public boolean isApplicable(@NotNull PsiElement[] elements) { return getExpression(elements) != null; } @Nullable protected TextRange surroundWithParenthesis(@NotNull PsiElement[] elements, boolean withNot) { GoExpression expression = getExpression(elements); if (expression == null) return null; String text = (withNot ? "!" : "") + "(" + expression.getText() + ")"; GoExpression parenthExprNode = GoElementFactory.createExpression(expression.getProject(), text); PsiElement replace = expression.replace(parenthExprNode); int endOffset = replace.getTextRange().getEndOffset(); return TextRange.create(endOffset, endOffset); } @Nullable protected GoExpression getExpression(@NotNull PsiElement[] elements) { return ObjectUtils.tryCast(ArrayUtil.getFirstElement(elements), GoExpression.class); } } ================================================ FILE: src/com/goide/editor/surround/GoStatementsSurroundDescriptor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoFile; import com.goide.psi.GoPsiTreeUtil; import com.goide.psi.GoStatement; import com.intellij.lang.surroundWith.SurroundDescriptor; import com.intellij.lang.surroundWith.Surrounder; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoStatementsSurroundDescriptor implements SurroundDescriptor { private static final Surrounder[] SURROUNDERS = new Surrounder[]{ new GoWithIfSurrounder(), new GoWithIfElseSurrounder(), new GoWithForSurrounder(), new GoWithBlockSurrounder() }; @NotNull @Override public Surrounder[] getSurrounders() { return SURROUNDERS; } @NotNull @Override public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) { return file instanceof GoFile ? GoPsiTreeUtil.getTopLevelElementsInRange((GoFile)file, startOffset, endOffset, GoStatement.class) : PsiElement.EMPTY_ARRAY; } @Override public boolean isExclusive() { return false; } } ================================================ FILE: src/com/goide/editor/surround/GoStatementsSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoBlock; import com.goide.psi.GoIfStatement; import com.goide.psi.impl.GoElementFactory; import com.intellij.lang.surroundWith.Surrounder; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoStatementsSurrounder implements Surrounder { @Override public boolean isApplicable(@NotNull PsiElement[] elements) { return true; } @Override @Nullable public TextRange surroundElements(@NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements) throws IncorrectOperationException { PsiElement container = elements[0].getParent(); if (container == null) return null; return surroundStatements(project, container, elements); } @Nullable protected abstract TextRange surroundStatements(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements) throws IncorrectOperationException; @Nullable protected TextRange surroundStatementsWithIfElse(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements, boolean withElse) { PsiElement first = ArrayUtil.getFirstElement(statements); PsiElement last = ArrayUtil.getLastElement(statements); String block = StringUtil.join(statements, PsiElement::getText, "\n"); GoIfStatement ifStatement = GoElementFactory.createIfStatement(project, "", block, withElse ? "" : null); ifStatement = (GoIfStatement)container.addAfter(ifStatement, last); container.deleteChildRange(first, last); int offset = getOffsetLBraceOfBlock(ifStatement.getBlock()); return offset > -1 ? new TextRange(offset, offset) : null; } protected int getOffsetLBraceOfBlock(@Nullable GoBlock block) { return block != null ? block.getLbrace().getTextRange().getStartOffset() : -1; } } ================================================ FILE: src/com/goide/editor/surround/GoWithBlockSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoBlock; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithBlockSurrounder extends GoStatementsSurrounder { @Override public String getTemplateDescription() { return "{ statements }"; } @Nullable @Override protected TextRange surroundStatements(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements) throws IncorrectOperationException { GoBlock block = GoElementFactory.createBlock(project); PsiElement first = ArrayUtil.getFirstElement(statements); PsiElement last = ArrayUtil.getLastElement(statements); block = (GoBlock)container.addAfter(block, last); block.addRangeAfter(first, last, block.getLbrace()); CodeEditUtil.markToReformat(block.getNode(), true); container.deleteChildRange(first, last); int offset = block.getTextRange().getEndOffset(); return new TextRange(offset, offset); } } ================================================ FILE: src/com/goide/editor/surround/GoWithForSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.psi.GoForStatement; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithForSurrounder extends GoStatementsSurrounder { @Override public String getTemplateDescription() { return "for { statements }"; } @Nullable @Override protected TextRange surroundStatements(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements) throws IncorrectOperationException { String text = StringUtil.join(statements, PsiElement::getText, "\n"); GoForStatement forStatement = GoElementFactory.createForStatement(project, text); PsiElement first = ArrayUtil.getFirstElement(statements); PsiElement last = ArrayUtil.getLastElement(statements); forStatement = (GoForStatement)container.addAfter(forStatement, last); container.deleteChildRange(first, last); int offset = getOffsetLBraceOfBlock(forStatement.getBlock()); return offset > -1 ? new TextRange(offset, offset) : null; } } ================================================ FILE: src/com/goide/editor/surround/GoWithIfElseExpressionSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithIfElseExpressionSurrounder extends GoBoolExpressionSurrounderBase { @Override public String getTemplateDescription() { return "if expression { } else { }"; } @Nullable @Override public TextRange surroundElements(@NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements) throws IncorrectOperationException { return surroundExpressionWithIfElse(elements, true); } } ================================================ FILE: src/com/goide/editor/surround/GoWithIfElseSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithIfElseSurrounder extends GoStatementsSurrounder { @Override public String getTemplateDescription() { return "if { statements } else { }"; } @Nullable @Override protected TextRange surroundStatements(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements) throws IncorrectOperationException { return surroundStatementsWithIfElse(project, container, statements, true); } } ================================================ FILE: src/com/goide/editor/surround/GoWithIfExpressionSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithIfExpressionSurrounder extends GoBoolExpressionSurrounderBase { @Override public String getTemplateDescription() { return "if expression { }"; } @Nullable @Override public TextRange surroundElements(@NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements) throws IncorrectOperationException { return surroundExpressionWithIfElse(elements, false); } } ================================================ FILE: src/com/goide/editor/surround/GoWithIfSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithIfSurrounder extends GoStatementsSurrounder { @Override public String getTemplateDescription() { return "if { statements }"; } @Nullable @Override protected TextRange surroundStatements(@NotNull Project project, @NotNull PsiElement container, @NotNull PsiElement[] statements) throws IncorrectOperationException { return surroundStatementsWithIfElse(project, container, statements, false); } } ================================================ FILE: src/com/goide/editor/surround/GoWithNotExpressionSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithNotExpressionSurrounder extends GoBoolExpressionSurrounderBase { @Override public String getTemplateDescription() { return "!(expression)"; } @Nullable @Override public TextRange surroundElements(@NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements) throws IncorrectOperationException { return surroundWithParenthesis(elements, true); } } ================================================ FILE: src/com/goide/editor/surround/GoWithParenthesisSurrounder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoWithParenthesisSurrounder extends GoExpressionSurrounder { @Override public String getTemplateDescription() { return "(expression)"; } @Nullable @Override public TextRange surroundElements(@NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements) throws IncorrectOperationException { return surroundWithParenthesis(elements, false); } } ================================================ FILE: src/com/goide/formatter/GoFormattingModelBuilder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.formatter; import com.goide.GoLanguage; import com.goide.psi.*; import com.intellij.formatting.*; import com.intellij.formatting.alignment.AlignmentStrategy; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.TokenType; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import static com.goide.GoParserDefinition.*; import static com.goide.GoTypes.*; public class GoFormattingModelBuilder implements FormattingModelBuilder { @NotNull private static SpacingBuilder createSpacingBuilder(@NotNull CodeStyleSettings settings) { return new SpacingBuilder(settings, GoLanguage.INSTANCE) .before(COMMA).spaceIf(false) .after(COMMA).spaceIf(true) .betweenInside(SEMICOLON, SEMICOLON, FOR_CLAUSE).spaces(1) .before(SEMICOLON).spaceIf(false) .after(SEMICOLON).spaceIf(true) .beforeInside(DOT, IMPORT_SPEC).none() .afterInside(DOT, IMPORT_SPEC).spaces(1) .around(DOT).none() .around(ASSIGN).spaces(1) .around(VAR_ASSIGN).spaces(1) .aroundInside(MUL, POINTER_TYPE).none() .before(ARGUMENT_LIST).none() .before(BUILTIN_ARGUMENT_LIST).none() .afterInside(LPAREN, ARGUMENT_LIST).none() .beforeInside(RPAREN, ARGUMENT_LIST).none() .afterInside(LPAREN, BUILTIN_ARGUMENT_LIST).none() .beforeInside(RPAREN, BUILTIN_ARGUMENT_LIST).none() .before(SIGNATURE).none() .afterInside(LPAREN, TYPE_ASSERTION_EXPR).none() .beforeInside(RPAREN, TYPE_ASSERTION_EXPR).none() .afterInside(LPAREN, PARAMETERS).none() .beforeInside(RPAREN, PARAMETERS).none() .afterInside(LPAREN, RESULT).none() .beforeInside(RPAREN, RESULT).none() .between(PARAMETERS, RESULT).spaces(1) .before(BLOCK).spaces(1) .after(FUNC).spaces(1) .after(PACKAGE).spaces(1) .after(IMPORT).spaces(1) .after(CONST).spaces(1) .after(VAR).spaces(1) .after(STRUCT).spaces(1) .after(INTERFACE).spaces(1) .after(RETURN).spaces(1) .after(GO).spaces(1) .after(DEFER).spaces(1) .after(FALLTHROUGH).spaces(1) .after(GOTO).spaces(1) .after(CONTINUE).spaces(1) .after(BREAK).spaces(1) .after(SELECT).spaces(1) .after(FOR).spaces(1) .after(IF).spaces(1) .after(ELSE).spaces(1) .before(ELSE_STATEMENT).spaces(1) .after(CASE).spaces(1) .after(RANGE).spaces(1) .after(SWITCH).spaces(1) .afterInside(SEND_CHANNEL, UNARY_EXPR).none() .aroundInside(SEND_CHANNEL, SEND_STATEMENT).spaces(1) .afterInside(CHAN, CHANNEL_TYPE).spaces(1) .afterInside(MAP, MAP_TYPE).none() .aroundInside(LBRACK, MAP_TYPE).none() .aroundInside(RBRACK, MAP_TYPE).none() .beforeInside(LITERAL_VALUE, COMPOSITE_LIT).none() .afterInside(LBRACE, LITERAL_VALUE).none() .beforeInside(LBRACE, LITERAL_VALUE).none() .afterInside(BIT_AND, UNARY_EXPR).none() .after(LINE_COMMENT).lineBreakInCode() .after(MULTILINE_COMMENT).lineBreakInCode() .between(COMM_CASE, COLON).none() .afterInside(COLON, COMM_CLAUSE).lineBreakInCode() .betweenInside(FIELD_DECLARATION, LINE_COMMENT, STRUCT_TYPE).spaces(1) .betweenInside(FIELD_DECLARATION, MULTILINE_COMMENT, STRUCT_TYPE).spaces(1) .betweenInside(LBRACK, RBRACK, ARRAY_OR_SLICE_TYPE).none() .around(ASSIGN_OP).spaces(1) .aroundInside(OPERATORS, TokenSet.create(MUL_EXPR, ADD_EXPR, OR_EXPR, CONDITIONAL_EXPR)).spaces(1) .betweenInside(LBRACE, RBRACE, BLOCK).spacing(0, 0, 0, true, 1) .afterInside(LBRACE, BLOCK).spacing(0, 0, 1, true, 1) .beforeInside(RBRACE, BLOCK).spacing(0, 0, 1, true, 1) .betweenInside(LPAREN, RPAREN, IMPORT_DECLARATION).spacing(0, 0, 0, false, 0) .afterInside(LPAREN, IMPORT_DECLARATION).spacing(0, 0, 1, false, 0) .beforeInside(RPAREN, IMPORT_DECLARATION).spacing(0, 0, 1, false, 0) .between(IMPORT_SPEC, IMPORT_SPEC).spacing(0, 0, 1, true, 1) .betweenInside(LPAREN, RPAREN, VAR_DECLARATION).spacing(0, 0, 0, false, 0) .afterInside(LPAREN, VAR_DECLARATION).spacing(0, 0, 1, false, 0) .beforeInside(RPAREN, VAR_DECLARATION).spacing(0, 0, 1, false, 0) .beforeInside(TYPE, VAR_SPEC).spaces(1) .between(VAR_SPEC, VAR_SPEC).spacing(0, 0, 1, true, 1) .betweenInside(LPAREN, RPAREN, CONST_DECLARATION).spacing(0, 0, 0, false, 0) .afterInside(LPAREN, CONST_DECLARATION).spacing(0, 0, 1, false, 0) .beforeInside(RPAREN, CONST_DECLARATION).spacing(0, 0, 1, false, 0) .beforeInside(TYPE, CONST_SPEC).spaces(1) .between(CONST_SPEC, CONST_SPEC).spacing(0, 0, 1, true, 1) .between(FIELD_DECLARATION, FIELD_DECLARATION).spacing(0, 0, 1, true, 1) .between(METHOD_SPEC, METHOD_SPEC).spacing(0, 0, 1, true, 1) ; } @NotNull @Override public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); } @Nullable @Override public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) { return null; } private static class GoFormattingBlock extends UserDataHolderBase implements ASTBlock { private static final TokenSet BLOCKS_TOKEN_SET = TokenSet.create( BLOCK, STRUCT_TYPE, INTERFACE_TYPE, SELECT_STATEMENT, EXPR_CASE_CLAUSE, TYPE_CASE_CLAUSE, LITERAL_VALUE ); private static final TokenSet BRACES_TOKEN_SET = TokenSet.create( LBRACE, RBRACE, LBRACK, RBRACK, LPAREN, RPAREN ); private static final Key TYPE_ALIGNMENT_INSIDE_STRUCT = Key.create("TYPE_ALIGNMENT_INSIDE_STRUCT"); @NotNull private final ASTNode myNode; @Nullable private final Alignment myAlignment; @Nullable private final Indent myIndent; @Nullable private final Wrap myWrap; @NotNull private final CodeStyleSettings mySettings; @NotNull private final SpacingBuilder mySpacingBuilder; @Nullable private List mySubBlocks; private GoFormattingBlock(@NotNull ASTNode node, @Nullable Alignment alignment, @Nullable Indent indent, @Nullable Wrap wrap, @NotNull CodeStyleSettings settings, @NotNull SpacingBuilder spacingBuilder) { myNode = node; myAlignment = alignment; myIndent = indent; myWrap = wrap; mySettings = settings; mySpacingBuilder = spacingBuilder; } @NotNull private static Indent indentIfNotBrace(@NotNull ASTNode child) { return BRACES_TOKEN_SET.contains(child.getElementType()) ? Indent.getNoneIndent() : Indent.getNormalIndent(); } private static boolean isTopLevelDeclaration(@NotNull PsiElement element) { return element instanceof GoPackageClause || element instanceof GoImportList || element instanceof GoTopLevelDeclaration && element.getParent() instanceof GoFile; } private static Spacing lineBreak() { return lineBreak(true); } private static Spacing lineBreak(boolean keepLineBreaks) { return lineBreak(0, keepLineBreaks); } private static Spacing lineBreak(int lineBreaks, boolean keepLineBreaks) { return Spacing.createSpacing(0, 0, lineBreaks + 1, keepLineBreaks, keepLineBreaks ? 1 : 0); } private static Spacing none() { return Spacing.createSpacing(0, 0, 0, false, 0); } private static Spacing one() { return Spacing.createSpacing(1, 1, 0, false, 0); } @NotNull @Override public ASTNode getNode() { return myNode; } @NotNull @Override public TextRange getTextRange() { return myNode.getTextRange(); } @Nullable @Override public Wrap getWrap() { return myWrap; } @Nullable @Override public Indent getIndent() { return myIndent; } @Nullable @Override public Alignment getAlignment() { return myAlignment; } @NotNull @Override public List getSubBlocks() { if (mySubBlocks == null) { mySubBlocks = buildSubBlocks(); } return ContainerUtil.newArrayList(mySubBlocks); } @NotNull private List buildSubBlocks() { AlignmentStrategy.AlignmentPerTypeStrategy strategy = null; boolean isStruct = getNode().getElementType() == STRUCT_TYPE; Alignment forType = null; if (isStruct) { strategy = AlignmentStrategy.createAlignmentPerTypeStrategy(ContainerUtil.list(FIELD_DECLARATION, LINE_COMMENT), STRUCT_TYPE, true); forType = Alignment.createAlignment(true); } List blocks = ContainerUtil.newArrayList(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { IElementType childType = child.getElementType(); if (child.getTextRange().getLength() == 0) continue; if (childType == TokenType.WHITE_SPACE) continue; IElementType substitutor = childType == MULTILINE_COMMENT ? LINE_COMMENT : childType; Alignment alignment = strategy != null ? strategy.getAlignment(substitutor) : null; GoFormattingBlock e = buildSubBlock(child, alignment); if (isStruct) { e.putUserDataIfAbsent(TYPE_ALIGNMENT_INSIDE_STRUCT, forType); } blocks.add(e); } return Collections.unmodifiableList(blocks); } @NotNull private GoFormattingBlock buildSubBlock(@NotNull ASTNode child, @Nullable Alignment alignment) { if (child.getPsi() instanceof GoType && child.getTreeParent().getElementType() == FIELD_DECLARATION) { alignment = getUserData(TYPE_ALIGNMENT_INSIDE_STRUCT); } Indent indent = calcIndent(child); return new GoFormattingBlock(child, alignment, indent, null, mySettings, mySpacingBuilder); } @NotNull private Indent calcIndent(@NotNull ASTNode child) { IElementType parentType = myNode.getElementType(); IElementType type = child.getElementType(); if (type == SWITCH_START) return Indent.getNoneIndent(); if (parentType == BLOCK && type == SELECT_STATEMENT) return Indent.getNoneIndent(); if (parentType == SELECT_STATEMENT && type == RBRACE) return Indent.getNormalIndent(); if (parentType == ARGUMENT_LIST && type != LPAREN && type != RPAREN) return Indent.getNormalIndent(); if ((parentType == EXPR_CASE_CLAUSE || parentType == TYPE_CASE_CLAUSE) && (type == CASE || type == DEFAULT)) return Indent.getNoneIndent(); if (BLOCKS_TOKEN_SET.contains(parentType)) return indentIfNotBrace(child); if (parentType == IMPORT_DECLARATION) return indentOfMultipleDeclarationChild(type, IMPORT_SPEC); if (parentType == CONST_DECLARATION) return indentOfMultipleDeclarationChild(type, CONST_SPEC); if (parentType == VAR_DECLARATION) return indentOfMultipleDeclarationChild(type, VAR_SPEC); if (parentType == TYPE_DECLARATION) return indentOfMultipleDeclarationChild(type, TYPE_SPEC); if (parentType == COMM_CLAUSE && child.getPsi() instanceof GoStatement) return Indent.getNormalIndent(); if (child.getPsi() instanceof GoExpression) return Indent.getContinuationWithoutFirstIndent(); return Indent.getNoneIndent(); } private Indent indentOfMultipleDeclarationChild(@NotNull IElementType childType, @NotNull IElementType specType) { if (childType == specType) { return Indent.getNormalIndent(); } return COMMENTS.contains(childType) && myNode.findChildByType(specType) != null ? Indent.getNormalIndent() : Indent.getNoneIndent(); } @Override public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) { if (child1 instanceof GoFormattingBlock && child2 instanceof GoFormattingBlock) { ASTNode n1 = ((GoFormattingBlock)child1).getNode(); ASTNode n2 = ((GoFormattingBlock)child2).getNode(); PsiElement psi1 = n1.getPsi(); PsiElement psi2 = n2.getPsi(); if (n1.getElementType() == FIELD_DEFINITION && psi2 instanceof GoType) return one(); PsiElement parent = psi1.getParent(); if (parent instanceof GoStructType || parent instanceof GoInterfaceType) { boolean oneLineType = !parent.textContains('\n'); if ((n1.getElementType() == STRUCT || n1.getElementType() == INTERFACE) && n2.getElementType() == LBRACE) { return oneLineType ? none() : one(); } if (n1.getElementType() == LBRACE && n2.getElementType() == RBRACE) { return oneLineType ? none() : lineBreak(); } if (n1.getElementType() == LBRACE) { return oneLineType ? one() : lineBreak(false); } if (n2.getElementType() == RBRACE) { return oneLineType ? one() : lineBreak(false); } } if (psi1 instanceof GoStatement && psi2 instanceof GoStatement) { return lineBreak(); } if (isTopLevelDeclaration(psi2) && (isTopLevelDeclaration(psi1) || n1.getElementType() == SEMICOLON)) { // Different declarations should be separated by blank line boolean sameKind = psi1.getClass().equals(psi2.getClass()) || psi1 instanceof GoFunctionOrMethodDeclaration && psi2 instanceof GoFunctionOrMethodDeclaration; return sameKind ? lineBreak() : lineBreak(1, true); } } return mySpacingBuilder.getSpacing(this, child1, child2); } @NotNull @Override public ChildAttributes getChildAttributes(int newChildIndex) { Indent childIndent = Indent.getNoneIndent(); IElementType parentType = myNode.getElementType(); if (BLOCKS_TOKEN_SET.contains(parentType) || parentType == IMPORT_DECLARATION || parentType == CONST_DECLARATION || parentType == VAR_DECLARATION || parentType == TYPE_DECLARATION || parentType == ARGUMENT_LIST) { childIndent = Indent.getNormalIndent(); } if (parentType == EXPR_SWITCH_STATEMENT || parentType == TYPE_SWITCH_STATEMENT || parentType == SELECT_STATEMENT) { List subBlocks = getSubBlocks(); Block block = subBlocks.size() > newChildIndex ? subBlocks.get(newChildIndex - 1) : null; if (block instanceof GoFormattingBlock) { IElementType type = ((GoFormattingBlock)block).getNode().getElementType(); if (type == TYPE_CASE_CLAUSE || type == EXPR_CASE_CLAUSE) { childIndent = Indent.getNormalIndent(); } else if (type == COMM_CLAUSE) { childIndent = Indent.getNormalIndent(true); } } } return new ChildAttributes(childIndent, null); } @Override public boolean isIncomplete() { return false; } @Override public boolean isLeaf() { return myNode.getFirstChildNode() == null; } } } ================================================ FILE: src/com/goide/formatter/settings/GoCodeStyleConfigurable.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.formatter.settings; import com.goide.GoConstants; import com.goide.GoLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.NotNull; public class GoCodeStyleConfigurable extends CodeStyleAbstractConfigurable { public GoCodeStyleConfigurable(@NotNull CodeStyleSettings settings, CodeStyleSettings cloneSettings) { super(settings, cloneSettings, GoConstants.GO); } @NotNull @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) { return new GoCodeStyleMainPanel(getCurrentSettings(), settings); } @Override public String getHelpTopic() { return null; } private static class GoCodeStyleMainPanel extends TabbedLanguageCodeStylePanel { private GoCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) { super(GoLanguage.INSTANCE, currentSettings, settings); } @Override protected void addSpacesTab(CodeStyleSettings settings) { } @Override protected void addBlankLinesTab(CodeStyleSettings settings) { } @Override protected void addWrappingAndBracesTab(CodeStyleSettings settings) { } } } ================================================ FILE: src/com/goide/formatter/settings/GoCodeStyleSettingsProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.formatter.settings; import com.goide.GoConstants; import com.intellij.openapi.options.Configurable; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; public class GoCodeStyleSettingsProvider extends CodeStyleSettingsProvider { @Override public String getConfigurableDisplayName() { return GoConstants.GO; } @NotNull @Override public Configurable createSettingsPage(@NotNull CodeStyleSettings settings, CodeStyleSettings originalSettings) { return new GoCodeStyleConfigurable(settings, originalSettings); } } ================================================ FILE: src/com/goide/formatter/settings/GoLanguageCodeStyleSettingsProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.formatter.settings; import com.goide.GoLanguage; import com.intellij.application.options.IndentOptionsEditor; import com.intellij.application.options.SmartIndentOptionsEditor; import com.intellij.lang.Language; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; import org.jetbrains.annotations.NotNull; public class GoLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSettingsProvider { private static final String DEFAULT_CODE_SAMPLE = "package main\n" + "\n" + "import \"fmt\"\n" + "\n" + "func main() {\n" + "\tfmt.Println(\"Hello\")\n" + "}"; @NotNull @Override public Language getLanguage() { return GoLanguage.INSTANCE; } @NotNull @Override public String getCodeSample(@NotNull SettingsType settingsType) { return DEFAULT_CODE_SAMPLE; } @Override public IndentOptionsEditor getIndentOptionsEditor() { return new SmartIndentOptionsEditor(); } @Override public CommonCodeStyleSettings getDefaultCommonSettings() { CommonCodeStyleSettings defaultSettings = new CommonCodeStyleSettings(getLanguage()); CommonCodeStyleSettings.IndentOptions indentOptions = defaultSettings.initIndentOptions(); indentOptions.INDENT_SIZE = 8; indentOptions.CONTINUATION_INDENT_SIZE = 8; indentOptions.TAB_SIZE = 8; indentOptions.USE_TAB_CHARACTER = true; defaultSettings.BLOCK_COMMENT_AT_FIRST_COLUMN = false; defaultSettings.LINE_COMMENT_AT_FIRST_COLUMN = false; return defaultSettings; } } ================================================ FILE: src/com/goide/generate/GoGenerateTestActionBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.generate; import com.goide.runconfig.testing.GoTestFramework; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.actions.CodeInsightAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; abstract public class GoGenerateTestActionBase extends CodeInsightAction { @NotNull private final GoTestFramework myFramework; @NotNull private final CodeInsightActionHandler myHandler; protected GoGenerateTestActionBase(@NotNull GoTestFramework framework, @NotNull CodeInsightActionHandler handler) { myFramework = framework; myHandler = handler; } @NotNull @Override protected CodeInsightActionHandler getHandler() { return myHandler; } @Override protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { return myFramework.isAvailableOnFile(file); } } ================================================ FILE: src/com/goide/generate/GoGenerateTestMethodActionGroup.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.generate; import com.goide.runconfig.testing.GoTestFramework; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; public class GoGenerateTestMethodActionGroup extends ActionGroup { @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { if (e == null) { return AnAction.EMPTY_ARRAY; } Project project = e.getProject(); Editor editor = e.getData(CommonDataKeys.EDITOR); if (project == null || editor == null) return AnAction.EMPTY_ARRAY; PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project); ArrayList children = ContainerUtil.newArrayList(); for (GoTestFramework framework : GoTestFramework.all()) { if (framework.isAvailableOnFile(file)) { children.addAll(framework.getGenerateMethodActions()); } } return !children.isEmpty() ? children.toArray(new AnAction[children.size()]) : AnAction.EMPTY_ARRAY; } } ================================================ FILE: src/com/goide/go/GoGotoContributorBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.go; import com.goide.psi.GoNamedElement; import com.intellij.navigation.ChooseByNameContributorEx; import com.intellij.navigation.GotoClassContributor; import com.intellij.navigation.NavigationItem; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.util.ArrayUtil; import com.intellij.util.Processor; import com.intellij.util.indexing.FindSymbolParameters; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoGotoContributorBase implements GotoClassContributor, ChooseByNameContributorEx { private final StubIndexKey[] myIndexKeys; @NotNull private final Class myClazz; @SafeVarargs public GoGotoContributorBase(@NotNull Class clazz, @NotNull StubIndexKey... key) { myIndexKeys = key; myClazz = clazz; } @NotNull @Override public String[] getNames(@NotNull Project project, boolean includeNonProjectItems) { return ArrayUtil.EMPTY_STRING_ARRAY; } @NotNull @Override public NavigationItem[] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) { return NavigationItem.EMPTY_NAVIGATION_ITEM_ARRAY; } @Override public void processNames(@NotNull Processor processor, @NotNull GlobalSearchScope scope, IdFilter filter) { for (StubIndexKey key : myIndexKeys) { ProgressManager.checkCanceled(); StubIndex.getInstance().processAllKeys(key, processor, scope, filter); } } @Override public void processElementsWithName(@NotNull String s, @NotNull Processor processor, @NotNull FindSymbolParameters parameters) { for (StubIndexKey key : myIndexKeys) { ProgressManager.checkCanceled(); StubIndex.getInstance().processElements(key, s, parameters.getProject(), parameters.getSearchScope(), parameters.getIdFilter(), myClazz, processor); } } @Nullable @Override public String getQualifiedName(NavigationItem item) { return item instanceof GoNamedElement ? ((GoNamedElement)item).getQualifiedName() : null; } @Nullable @Override public String getQualifiedNameSeparator() { return null; } } ================================================ FILE: src/com/goide/go/GoSymbolContributor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.go; import com.goide.psi.GoNamedElement; import com.goide.stubs.index.GoAllPrivateNamesIndex; import com.goide.stubs.index.GoAllPublicNamesIndex; public class GoSymbolContributor extends GoGotoContributorBase { public GoSymbolContributor() { super(GoNamedElement.class, GoAllPublicNamesIndex.ALL_PUBLIC_NAMES, GoAllPrivateNamesIndex.ALL_PRIVATE_NAMES); } } ================================================ FILE: src/com/goide/go/GoTypeContributor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.go; import com.goide.psi.GoTypeSpec; import com.goide.stubs.index.GoTypesIndex; public class GoTypeContributor extends GoGotoContributorBase { public GoTypeContributor() { super(GoTypeSpec.class, GoTypesIndex.KEY); } } ================================================ FILE: src/com/goide/highlighting/GoAnnotator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.goide.GoConstants; import com.goide.GoTypes; import com.goide.inspections.GoInspectionUtil; import com.goide.psi.*; import com.goide.psi.impl.GoCType; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.goide.quickfix.GoDeleteRangeQuickFix; import com.goide.quickfix.GoEmptySignatureQuickFix; import com.goide.quickfix.GoReplaceWithReturnStatementQuickFix; import com.google.common.collect.Sets; import com.intellij.lang.ASTNode; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; public class GoAnnotator implements Annotator { private static final Set INT_TYPE_NAMES = Sets.newHashSet( "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "uintptr", "rune", "float32", "float64" ); // todo: unify with DlvApi.Variable.Kind @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { if (!(element instanceof GoCompositeElement) || !element.isValid()) return; if (element instanceof GoPackageClause) { PsiElement identifier = ((GoPackageClause)element).getIdentifier(); if (identifier != null && identifier.textMatches("_")) { holder.createErrorAnnotation(identifier, "Invalid package name"); return; } } if (element instanceof GoContinueStatement) { if (!(PsiTreeUtil.getParentOfType(element, GoForStatement.class, GoFunctionLit.class) instanceof GoForStatement)) { Annotation annotation = holder.createErrorAnnotation(element, "Continue statement not inside a for loop"); annotation.registerFix(new GoReplaceWithReturnStatementQuickFix(element)); } } else if (element instanceof GoBreakStatement) { if (GoPsiImplUtil.getBreakStatementOwner(element) == null) { Annotation annotation = holder.createErrorAnnotation(element, "Break statement not inside a for loop, select or switch"); annotation.registerFix(new GoReplaceWithReturnStatementQuickFix(element)); } } else if (element instanceof GoReferenceExpression) { GoReferenceExpression reference = (GoReferenceExpression)element; PsiElement resolvedReference = reference.resolve(); if (resolvedReference instanceof PsiDirectory || resolvedReference instanceof GoImportSpec) { // It's a package reference. It should either be inside a package clause or part of a larger reference expression. if (!(element.getParent() instanceof GoReferenceExpression) && PsiTreeUtil.getParentOfType(reference, GoPackageClause.class) == null) { holder.createErrorAnnotation(element, "Use of package " + element.getText() + " without selector"); } } if (resolvedReference instanceof GoTypeSpec && isIllegalUseOfTypeAsExpression(reference)) { holder.createErrorAnnotation(element, "Type " + element.getText() + " is not an expression"); } if (resolvedReference instanceof GoConstDefinition && resolvedReference.getParent() instanceof GoConstSpec && PsiTreeUtil.getParentOfType(element, GoConstDeclaration.class) != null) { checkSelfReference((GoReferenceExpression)element, resolvedReference, holder); } if (resolvedReference instanceof GoVarDefinition && resolvedReference.getParent() instanceof GoVarSpec && PsiTreeUtil.getParentOfType(element, GoVarDeclaration.class) != null) { checkSelfReference((GoReferenceExpression)element, resolvedReference, holder); } } else if (element instanceof GoLiteralTypeExpr) { if (isIllegalUseOfTypeAsExpression(element)) { holder.createErrorAnnotation(element, "Type " + element.getText() + " is not an expression"); } } else if (element instanceof GoCompositeLit) { GoCompositeLit literal = (GoCompositeLit)element; if (literal.getType() instanceof GoMapType) { GoLiteralValue literalValue = literal.getLiteralValue(); if (literalValue != null) { for (GoElement literalElement : literalValue.getElementList()) { if (literalElement.getKey() == null) { holder.createErrorAnnotation(literalElement, "Missing key in map literal"); } } } } } else if (element instanceof GoTypeAssertionExpr) { GoType type = ((GoTypeAssertionExpr)element).getExpression().getGoType(null); if (type != null) { GoType underlyingType = type.getUnderlyingType(); if (!(underlyingType instanceof GoInterfaceType)) { String message = String.format("Invalid type assertion: %s, (non-interface type %s on left)", element.getText(), type.getText()); holder.createErrorAnnotation(((GoTypeAssertionExpr)element).getExpression(), message); } } } else if (element instanceof GoBuiltinCallExpr) { GoBuiltinCallExpr call = (GoBuiltinCallExpr)element; if ("make".equals(call.getReferenceExpression().getText())) { checkMakeCall(call, holder); } } else if (element instanceof GoCallExpr) { GoCallExpr call = (GoCallExpr)element; GoExpression callExpression = call.getExpression(); if (GoInspectionUtil.getFunctionResultCount(call) == 0) { PsiElement parent = call.getParent(); boolean simpleStatement = parent instanceof GoLeftHandExprList && parent.getParent() instanceof GoSimpleStatement; boolean inDeferOrGo = parent instanceof GoDeferStatement || parent instanceof GoGoStatement; if (!simpleStatement && !inDeferOrGo) { holder.createErrorAnnotation(call, call.getText() + " used as value"); } } if (callExpression instanceof GoReferenceExpression) { GoReferenceExpression reference = (GoReferenceExpression)callExpression; if (reference.textMatches("cap")) { if (GoPsiImplUtil.builtin(reference.resolve())) { checkCapCall(call, holder); } } } } else if (element instanceof GoTopLevelDeclaration) { if (element.getParent() instanceof GoFile) { if (element instanceof GoTypeDeclaration) { for (GoTypeSpec spec : ((GoTypeDeclaration)element).getTypeSpecList()) { if (spec.getIdentifier().textMatches(GoConstants.INIT)) { holder.createErrorAnnotation(spec, "Cannot declare init, must be a function"); } } } else if (element instanceof GoVarDeclaration) { for (GoVarSpec spec : ((GoVarDeclaration)element).getVarSpecList()) { for (GoVarDefinition definition : spec.getVarDefinitionList()) { if (definition.getIdentifier().textMatches(GoConstants.INIT)) { holder.createErrorAnnotation(spec, "Cannot declare init, must be a function"); } } } } else if (element instanceof GoConstDeclaration) { for (GoConstSpec spec : ((GoConstDeclaration)element).getConstSpecList()) { for (GoConstDefinition definition : spec.getConstDefinitionList()) { if (definition.getIdentifier().textMatches(GoConstants.INIT)) { holder.createErrorAnnotation(spec, "Cannot declare init, must be a function"); } } } } else if (element instanceof GoFunctionDeclaration) { GoFunctionDeclaration declaration = (GoFunctionDeclaration)element; if (declaration.getIdentifier().textMatches(GoConstants.INIT) || declaration.getIdentifier().textMatches(GoConstants.MAIN) && GoConstants.MAIN.equals(declaration.getContainingFile().getPackageName())) { GoSignature signature = declaration.getSignature(); if (signature != null) { GoResult result = signature.getResult(); if (result != null && !result.isVoid()) { Annotation annotation = holder.createErrorAnnotation(result, declaration.getName() + " function must have no arguments and no return values"); annotation.registerFix(new GoEmptySignatureQuickFix(declaration)); } GoParameters parameters = signature.getParameters(); if (!parameters.getParameterDeclarationList().isEmpty()) { Annotation annotation = holder.createErrorAnnotation(parameters, declaration.getName() + " function must have no arguments and no return values"); annotation.registerFix(new GoEmptySignatureQuickFix(declaration)); } } } } } } else if (element instanceof GoIndexOrSliceExpr) { GoIndexOrSliceExpr slice = (GoIndexOrSliceExpr)element; GoExpression expr = slice.getExpression(); GoExpression thirdIndex = slice.getIndices().third; if (expr == null || thirdIndex == null) { return; } if (GoTypeUtil.isString(expr.getGoType(null))) { ASTNode[] colons = slice.getNode().getChildren(TokenSet.create(GoTypes.COLON)); if (colons.length == 2) { PsiElement secondColon = colons[1].getPsi(); TextRange r = TextRange.create(secondColon.getTextRange().getStartOffset(), thirdIndex.getTextRange().getEndOffset()); Annotation annotation = holder.createErrorAnnotation(r, "Invalid operation " + slice.getText() + " (3-index slice of string)"); annotation.registerFix(new GoDeleteRangeQuickFix(secondColon, thirdIndex, "Delete third index")); } } } } private static void checkCapCall(@NotNull GoCallExpr capCall, @NotNull AnnotationHolder holder) { List exprs = capCall.getArgumentList().getExpressionList(); if (exprs.size() != 1) return; GoExpression first = ContainerUtil.getFirstItem(exprs); //noinspection ConstantConditions GoType exprType = first.getGoType(null); // todo: context if (exprType == null) return; GoType baseType = GoPsiImplUtil.unwrapPointerIfNeeded(exprType.getUnderlyingType()); if (baseType instanceof GoArrayOrSliceType || baseType instanceof GoChannelType) return; holder.createErrorAnnotation(first, "Invalid argument for cap"); } private static void checkMakeCall(@NotNull GoBuiltinCallExpr call, @NotNull AnnotationHolder holder) { GoBuiltinArgumentList args = call.getBuiltinArgumentList(); if (args == null) { holder.createErrorAnnotation(call, "Missing argument to make"); return; } GoType type = args.getType(); if (type == null) { GoExpression first = ContainerUtil.getFirstItem(args.getExpressionList()); if (first != null) { holder.createErrorAnnotation(call, first.getText() + " is not a type"); } else { holder.createErrorAnnotation(args, "Missing argument to make"); } } else { // We have a type, is it valid? GoType baseType = type.getUnderlyingType(); if (canMakeType(baseType)) { // We have a type and we can make the type, are the parameters to make valid? checkMakeArgs(call, baseType, args.getExpressionList(), holder); } else { holder.createErrorAnnotation(type, "Cannot make " + type.getText()); } } } private static boolean canMakeType(@Nullable GoType type) { if (type instanceof GoArrayOrSliceType) { // Only slices (no size expression) can be make()'d. return ((GoArrayOrSliceType)type).getExpression() == null; } return type instanceof GoChannelType || type instanceof GoMapType; } private static void checkMakeArgs(@NotNull GoBuiltinCallExpr call, @Nullable GoType baseType, @NotNull List list, @NotNull AnnotationHolder holder) { if (baseType instanceof GoArrayOrSliceType) { if (list.isEmpty()) { holder.createErrorAnnotation(call, "Missing len argument to make"); return; } else if (list.size() > 2) { holder.createErrorAnnotation(call, "Too many arguments to make"); return; } } if (baseType instanceof GoChannelType || baseType instanceof GoMapType) { if (list.size() > 1) { holder.createErrorAnnotation(call, "Too many arguments to make"); return; } } for (int i = 0; i < list.size(); i++) { GoExpression expression = list.get(i); GoType type = expression.getGoType(null); // todo: context if (type != null) { GoType expressionBaseType = type.getUnderlyingType(); if (!(isIntegerConvertibleType(expressionBaseType) || isCType(type))) { String argName = i == 0 ? "size" : "capacity"; holder.createErrorAnnotation(expression, "Non-integer " + argName + " argument to make"); } } } } private static boolean isCType(@Nullable GoType type) { return type instanceof GoCType; } private static boolean isIntegerConvertibleType(@Nullable GoType type) { if (type == null) return false; GoTypeReferenceExpression ref = type.getTypeReferenceExpression(); if (ref == null) return false; return INT_TYPE_NAMES.contains(ref.getText()) && GoPsiImplUtil.builtin(ref.resolve()); } private static void checkSelfReference(@NotNull GoReferenceExpression o, PsiElement definition, AnnotationHolder holder) { GoExpression value = null; if (definition instanceof GoVarDefinition) { value = ((GoVarDefinition)definition).getValue(); } else if (definition instanceof GoConstDefinition) { value = ((GoConstDefinition)definition).getValue(); } if (value != null && value.equals(GoPsiImplUtil.getNonStrictTopmostParentOfType(o, GoExpression.class))) { holder.createErrorAnnotation(o, "Cyclic definition detected"); } } /** * Returns {@code true} if the given element is in an invalid location for a type literal or type reference. */ private static boolean isIllegalUseOfTypeAsExpression(@NotNull PsiElement e) { PsiElement parent = PsiTreeUtil.skipParentsOfType(e, GoParenthesesExpr.class, GoUnaryExpr.class); // Part of a selector such as T.method if (parent instanceof GoReferenceExpression || parent instanceof GoSelectorExpr) return false; // A situation like T("foo"). return !(parent instanceof GoCallExpr); } } ================================================ FILE: src/com/goide/highlighting/GoColorsAndFontsPage.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.goide.GoFileType; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Map; import static com.goide.highlighting.GoSyntaxHighlightingColors.*; public class GoColorsAndFontsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Line comment", LINE_COMMENT), new AttributesDescriptor("Block comment", BLOCK_COMMENT), new AttributesDescriptor("Keyword", KEYWORD), new AttributesDescriptor("Identifier", IDENTIFIER), new AttributesDescriptor("String", STRING), new AttributesDescriptor("Number", NUMBER), new AttributesDescriptor("Semicolon", SEMICOLON), new AttributesDescriptor("Colon", COLON), new AttributesDescriptor("Comma", COMMA), new AttributesDescriptor("Dot", DOT), new AttributesDescriptor("Operator", OPERATOR), new AttributesDescriptor("Brackets", BRACKETS), new AttributesDescriptor("Braces", BRACES), new AttributesDescriptor("Parentheses", PARENTHESES), new AttributesDescriptor("Bad character", BAD_CHARACTER), new AttributesDescriptor("Type specification", TYPE_SPECIFICATION), new AttributesDescriptor("Type reference", TYPE_REFERENCE), new AttributesDescriptor("Builtin type", BUILTIN_TYPE_REFERENCE), new AttributesDescriptor("Builtin function", BUILTIN_FUNCTION), new AttributesDescriptor("Exported function", EXPORTED_FUNCTION), new AttributesDescriptor("Local function", LOCAL_FUNCTION), new AttributesDescriptor("Package exported interface", PACKAGE_EXPORTED_INTERFACE), new AttributesDescriptor("Package exported struct", PACKAGE_EXPORTED_STRUCT), new AttributesDescriptor("Package exported constant", PACKAGE_EXPORTED_CONSTANT), new AttributesDescriptor("Package exported variable", PACKAGE_EXPORTED_VARIABLE), new AttributesDescriptor("Package local interface", PACKAGE_LOCAL_INTERFACE), new AttributesDescriptor("Package local struct", PACKAGE_LOCAL_STRUCT), new AttributesDescriptor("Package local constant", PACKAGE_LOCAL_CONSTANT), new AttributesDescriptor("Package local variable", PACKAGE_LOCAL_VARIABLE), new AttributesDescriptor("Struct exported member", STRUCT_EXPORTED_MEMBER), new AttributesDescriptor("Struct local member", STRUCT_LOCAL_MEMBER), new AttributesDescriptor("Method receiver", METHOD_RECEIVER), new AttributesDescriptor("Function parameter", FUNCTION_PARAMETER), new AttributesDescriptor("Local constant", LOCAL_CONSTANT), new AttributesDescriptor("Local variable", LOCAL_VARIABLE), new AttributesDescriptor("Scope declared variable", SCOPE_VARIABLE), new AttributesDescriptor("Label", LABEL) }; private static final Map ATTRIBUTES_KEY_MAP = ContainerUtil.newTroveMap(); static { ATTRIBUTES_KEY_MAP.put("tr", TYPE_REFERENCE); ATTRIBUTES_KEY_MAP.put("ts", TYPE_SPECIFICATION); ATTRIBUTES_KEY_MAP.put("bt", BUILTIN_TYPE_REFERENCE); ATTRIBUTES_KEY_MAP.put("bf", BUILTIN_FUNCTION); ATTRIBUTES_KEY_MAP.put("kw", KEYWORD); ATTRIBUTES_KEY_MAP.put("ef", EXPORTED_FUNCTION); ATTRIBUTES_KEY_MAP.put("lf", LOCAL_FUNCTION); ATTRIBUTES_KEY_MAP.put("pei", PACKAGE_EXPORTED_INTERFACE); ATTRIBUTES_KEY_MAP.put("pes", PACKAGE_EXPORTED_STRUCT); ATTRIBUTES_KEY_MAP.put("pec", PACKAGE_EXPORTED_CONSTANT); ATTRIBUTES_KEY_MAP.put("pev", PACKAGE_EXPORTED_VARIABLE); ATTRIBUTES_KEY_MAP.put("pli", PACKAGE_LOCAL_INTERFACE); ATTRIBUTES_KEY_MAP.put("pls", PACKAGE_LOCAL_STRUCT); ATTRIBUTES_KEY_MAP.put("plc", PACKAGE_LOCAL_CONSTANT); ATTRIBUTES_KEY_MAP.put("plv", PACKAGE_LOCAL_VARIABLE); ATTRIBUTES_KEY_MAP.put("sem", STRUCT_EXPORTED_MEMBER); ATTRIBUTES_KEY_MAP.put("slm", STRUCT_LOCAL_MEMBER); ATTRIBUTES_KEY_MAP.put("mr", METHOD_RECEIVER); ATTRIBUTES_KEY_MAP.put("fp", FUNCTION_PARAMETER); ATTRIBUTES_KEY_MAP.put("lc", LOCAL_CONSTANT); ATTRIBUTES_KEY_MAP.put("lv", LOCAL_VARIABLE); ATTRIBUTES_KEY_MAP.put("sv", SCOPE_VARIABLE); ATTRIBUTES_KEY_MAP.put("ll", LABEL); } @Override @NotNull public String getDisplayName() { return GoFileType.INSTANCE.getName(); } @Override public Icon getIcon() { return GoFileType.INSTANCE.getIcon(); } @Override @NotNull public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @Override @NotNull public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @Override @NotNull public SyntaxHighlighter getHighlighter() { return new GoSyntaxHighlighter(); } @Override @NotNull public String getDemoText() { return "/*\n" + " * Go highlight sample \n" + " */\n" + "\n" + "// Package main\n"+ "package main\n" + "\n" + "import \"fmt\"\n" + "\n" + "type (\n" + " PublicInterface interface {\n" + " PublicFunc() int\n" + " privateFunc() int\n" + " }\n" + "\n" + " private interface {\n" + " PublicFunc() int\n" + " privateFunc() int\n" + " }\n" + "\n" + " PublicStruct struct {\n" + " PublicField int\n" + " privateField int\n" + " }\n" + "\n" + " privateStruct struct {\n" + " PublicField int\n" + " privateField int\n" + " }\n" + "\n" + " demoInt int\n" + ")\n" + "\n" + "const (\n" + " PublicConst = 1\n" + " privateConst = 2\n" + ")\n" + "\n" + "var (\n" + " PublicVar = 1\n" + " privateVar = 2\n" + ")\n" + "\n" + "func PublicFunc() int {\n" + " const LocalConst = 1\n" + " localVar := PublicVar\n" + " return localVar\n" + "}\n" + "\n" + "func privateFunc() (int, int) {\n" + " const localConst = 2\n" + " LocalVar := privateVar\n" + " return LocalVar, PublicVar\n" + "}\n" + "\n" + "func (ps PublicStruct) PublicFunc() int {\n" + " return ps.privateField\n" + "}\n" + "\n" + "func (ps PublicStruct) privateFunc() {\n" + " return ps.PublicField\n" + "}\n" + "\n" + "func (ps privateStruct) PublicFunc() int {\n" + " return ps.privateField\n" + "}\n" + "\n" + "func (ps privateStruct) privateFunc() {\n" + " return ps.PublicField\n" + "}\n" + "\n" + "func variableFunc(demo1 int) {\n" + " demo1 = 3\n" + " a := PublicStruct{}\n" + " a.privateFunc()\n" + " demo2 := 4\n" + " if demo1, demo2 := privateFunc(); demo1 != 3 {\n" + " _ = demo1\n" + " _ = demo2\n" + " return\n" + " }\n" + "demoLabel:\n" + " for demo1 := range []int{1, 2, 3, 4} {\n" + " _ = demo1\n" + " continue demoLabel\n" + " }\n" + "\n" + " switch {\n" + " case 1 == 2:\n" + " demo1, demo2 := privateFunc()\n" + " _ = demo1\n" + " _ = demo2\n" + " default:\n" + " _ = demo1\n" + " }\n" + "\n" + " b := func() int {\n" + " return 1\n" + " }\n" + " _ = b()\n" + " _ = PublicFunc()\n" + " _ = variableFunc(1)\n" + " _ = demo1\n" + " _ = demo2\n" + " println(\"builtin function\")" + "\n" + "}\n" + "\n" + "func main() {\n" + " fmt.Println(\"demo\")\n" + " variableFunc(1)\n" + " c := bt\n" + " d := nil\n" + " _, _ = c, d\n" + "}\n"; } @Override @NotNull public Map getAdditionalHighlightingTagToDescriptorMap() { return ATTRIBUTES_KEY_MAP; } } ================================================ FILE: src/com/goide/highlighting/GoHighlightingAnnotator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoReferenceBase; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.stream.Collectors; import static com.goide.highlighting.GoSyntaxHighlightingColors.*; public class GoHighlightingAnnotator implements Annotator { private static void highlightRefIfNeeded(@NotNull GoReferenceExpressionBase o, @Nullable PsiElement resolve, @NotNull AnnotationHolder holder) { if (resolve instanceof GoTypeSpec) { TextAttributesKey key = GoPsiImplUtil.builtin(resolve) ? BUILTIN_TYPE_REFERENCE : getColor((GoTypeSpec)resolve); if (o.getParent() instanceof GoType) { GoType topmostType = PsiTreeUtil.getTopmostParentOfType(o, GoType.class); if (topmostType != null && topmostType.getParent() instanceof GoReceiver) { key = TYPE_REFERENCE; } } setHighlighting(o.getIdentifier(), holder, key); } else if (resolve instanceof GoConstDefinition) { TextAttributesKey color = GoPsiImplUtil.builtin(resolve) ? BUILTIN_TYPE_REFERENCE : getColor((GoConstDefinition)resolve); setHighlighting(o.getIdentifier(), holder, color); } else if (resolve instanceof GoVarDefinition) { TextAttributesKey color = GoPsiImplUtil.builtin(resolve) ? BUILTIN_TYPE_REFERENCE : getColor((GoVarDefinition)resolve); setHighlighting(o.getIdentifier(), holder, color); } else if (resolve instanceof GoFieldDefinition) { setHighlighting(o.getIdentifier(), holder, getColor((GoFieldDefinition)resolve)); } else if (resolve instanceof GoFunctionOrMethodDeclaration || resolve instanceof GoMethodSpec) { setHighlighting(o.getIdentifier(), holder, getColor((GoNamedSignatureOwner)resolve)); } else if (resolve instanceof GoReceiver) { setHighlighting(o.getIdentifier(), holder, METHOD_RECEIVER); } else if (resolve instanceof GoParamDefinition) { setHighlighting(o.getIdentifier(), holder, FUNCTION_PARAMETER); } } private static TextAttributesKey getColor(GoConstDefinition o) { if (isPackageWide(o)) { return o.isPublic() ? PACKAGE_EXPORTED_CONSTANT : PACKAGE_LOCAL_CONSTANT; } return LOCAL_CONSTANT; } private static TextAttributesKey getColor(GoFieldDefinition o) { return o.isPublic() ? STRUCT_EXPORTED_MEMBER : STRUCT_LOCAL_MEMBER; } private static TextAttributesKey getColor(GoVarDefinition o) { if (PsiTreeUtil.getParentOfType(o, GoForStatement.class) != null || PsiTreeUtil.getParentOfType(o, GoIfStatement.class) != null || PsiTreeUtil.getParentOfType(o, GoSwitchStatement.class) != null) { return SCOPE_VARIABLE; } if (isPackageWide(o)) { return o.isPublic() ? PACKAGE_EXPORTED_VARIABLE : PACKAGE_LOCAL_VARIABLE; } return LOCAL_VARIABLE; } private static TextAttributesKey getColor(GoNamedSignatureOwner o) { if (GoPsiImplUtil.builtin(o)) return BUILTIN_FUNCTION; return o.isPublic() ? EXPORTED_FUNCTION : LOCAL_FUNCTION; } private static TextAttributesKey getColor(@Nullable GoTypeSpec o) { GoType type = o != null ? o.getGoType(null) : null; if (type != null) { type = type instanceof GoSpecType ? ((GoSpecType)type).getType() : type; boolean isPublic = o.isPublic(); if (type instanceof GoInterfaceType) { return isPublic ? PACKAGE_EXPORTED_INTERFACE : PACKAGE_LOCAL_INTERFACE; } else if (type instanceof GoStructType) { return isPublic ? PACKAGE_EXPORTED_STRUCT : PACKAGE_LOCAL_STRUCT; } } return TYPE_SPECIFICATION; } private static void setHighlighting(@NotNull PsiElement element, @NotNull AnnotationHolder holder, @NotNull TextAttributesKey key) { holder.createInfoAnnotation(element, null).setEnforcedTextAttributes(TextAttributes.ERASE_MARKER); String description = ApplicationManager.getApplication().isUnitTestMode() ? key.getExternalName() : null; holder.createInfoAnnotation(element, description).setTextAttributes(key); } private static boolean isPackageWide(@NotNull GoVarDefinition o) { GoVarDeclaration declaration = PsiTreeUtil.getParentOfType(o, GoVarDeclaration.class); return declaration != null && declaration.getParent() instanceof GoFile; } private static boolean isPackageWide(@NotNull GoConstDefinition o) { GoConstDeclaration declaration = PsiTreeUtil.getParentOfType(o, GoConstDeclaration.class); return declaration != null && declaration.getParent() instanceof GoFile; } @Override public void annotate(@NotNull PsiElement o, @NotNull AnnotationHolder holder) { if (!o.isValid()) return; if (o instanceof GoImportSpec && ((GoImportSpec)o).isDot()) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (o) { List importUsers = o.getUserData(GoReferenceBase.IMPORT_USERS); if (importUsers != null) { List newImportUsers = ContainerUtil.newSmartList(); newImportUsers.addAll(importUsers.stream().filter(PsiElement::isValid).collect(Collectors.toList())); o.putUserData(GoReferenceBase.IMPORT_USERS, newImportUsers.isEmpty() ? null : newImportUsers); } } } else if (o instanceof GoLiteral) { if (((GoLiteral)o).getHex() != null || ((GoLiteral)o).getOct() != null) { setHighlighting(o, holder, NUMBER); } } else if (o instanceof GoReferenceExpressionBase) { PsiReference reference = o.getReference(); highlightRefIfNeeded((GoReferenceExpressionBase)o, reference != null ? reference.resolve() : null, holder); } else if (o instanceof GoTypeSpec) { TextAttributesKey key = getColor((GoTypeSpec)o); setHighlighting(((GoTypeSpec)o).getIdentifier(), holder, key); } else if (o instanceof GoConstDefinition) { setHighlighting(o, holder, getColor((GoConstDefinition)o)); } else if (o instanceof GoVarDefinition) { setHighlighting(o, holder, getColor((GoVarDefinition)o)); } else if (o instanceof GoFieldDefinition) { setHighlighting(o, holder, getColor((GoFieldDefinition)o)); } else if (o instanceof GoParamDefinition) { setHighlighting(o, holder, FUNCTION_PARAMETER); } else if (o instanceof GoReceiver) { PsiElement identifier = ((GoReceiver)o).getIdentifier(); if (identifier != null) { setHighlighting(identifier, holder, METHOD_RECEIVER); } } else if (o instanceof GoLabelDefinition || o instanceof GoLabelRef) { setHighlighting(o, holder, LABEL); } else if (o instanceof GoNamedSignatureOwner) { PsiElement identifier = ((GoNamedSignatureOwner)o).getIdentifier(); if (identifier != null) { setHighlighting(identifier, holder, getColor((GoNamedSignatureOwner)o)); } } } } ================================================ FILE: src/com/goide/highlighting/GoProblemFileHighlightFilter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.goide.GoFileType; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFile; public class GoProblemFileHighlightFilter implements Condition { @Override public boolean value(VirtualFile virtualFile) { return virtualFile.getFileType() == GoFileType.INSTANCE; } } ================================================ FILE: src/com/goide/highlighting/GoSyntaxHighlighter.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.goide.lexer.GoLexer; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import static com.goide.highlighting.GoSyntaxHighlightingColors.*; public class GoSyntaxHighlighter extends SyntaxHighlighterBase { private static final Map ATTRIBUTES = new HashMap(); static { fillMap(ATTRIBUTES, LINE_COMMENT, GoParserDefinition.LINE_COMMENT); fillMap(ATTRIBUTES, BLOCK_COMMENT, GoParserDefinition.MULTILINE_COMMENT); fillMap(ATTRIBUTES, PARENTHESES, GoTypes.LPAREN, GoTypes.RPAREN); fillMap(ATTRIBUTES, BRACES, GoTypes.LBRACE, GoTypes.RBRACE); fillMap(ATTRIBUTES, BRACKETS, GoTypes.LBRACK, GoTypes.RBRACK); fillMap(ATTRIBUTES, BAD_CHARACTER, TokenType.BAD_CHARACTER); fillMap(ATTRIBUTES, IDENTIFIER, GoTypes.IDENTIFIER); fillMap(ATTRIBUTES, DOT, GoTypes.DOT, GoTypes.TRIPLE_DOT); fillMap(ATTRIBUTES, COLON, GoTypes.COLON); fillMap(ATTRIBUTES, SEMICOLON, GoTypes.SEMICOLON); fillMap(ATTRIBUTES, COMMA, GoTypes.COMMA); fillMap(ATTRIBUTES, GoParserDefinition.OPERATORS, OPERATOR); fillMap(ATTRIBUTES, GoParserDefinition.KEYWORDS, KEYWORD); fillMap(ATTRIBUTES, GoParserDefinition.NUMBERS, NUMBER); fillMap(ATTRIBUTES, GoParserDefinition.STRING_LITERALS, STRING); } @NotNull public Lexer getHighlightingLexer() { return new GoLexer(); } @NotNull public TextAttributesKey[] getTokenHighlights(IElementType tokenType) { return pack(ATTRIBUTES.get(tokenType)); } } ================================================ FILE: src/com/goide/highlighting/GoSyntaxHighlighterFactory.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoSyntaxHighlighterFactory extends SyntaxHighlighterFactory { @NotNull @Override public SyntaxHighlighter getSyntaxHighlighter(@Nullable Project project, @Nullable VirtualFile virtualFile) { return new GoSyntaxHighlighter(); } } ================================================ FILE: src/com/goide/highlighting/GoSyntaxHighlightingColors.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey; public class GoSyntaxHighlightingColors { public static final TextAttributesKey LINE_COMMENT = createTextAttributesKey("GO_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey BLOCK_COMMENT = createTextAttributesKey("GO_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT); public static final TextAttributesKey KEYWORD = createTextAttributesKey("GO_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey STRING = createTextAttributesKey("GO_STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = createTextAttributesKey("GO_NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey BRACKETS = createTextAttributesKey("GO_BRACKET", DefaultLanguageHighlighterColors.BRACKETS); public static final TextAttributesKey BRACES = createTextAttributesKey("GO_BRACES", DefaultLanguageHighlighterColors.BRACES); public static final TextAttributesKey PARENTHESES = createTextAttributesKey("GO_PARENTHESES", DefaultLanguageHighlighterColors.PARENTHESES); public static final TextAttributesKey OPERATOR = createTextAttributesKey("GO_OPERATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN); public static final TextAttributesKey IDENTIFIER = createTextAttributesKey("GO_IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey DOT = createTextAttributesKey("GO_DOT", DefaultLanguageHighlighterColors.DOT); public static final TextAttributesKey SEMICOLON = createTextAttributesKey("GO_SEMICOLON", DefaultLanguageHighlighterColors.SEMICOLON); public static final TextAttributesKey COLON = createTextAttributesKey("GO_COLON", HighlighterColors.TEXT); public static final TextAttributesKey COMMA = createTextAttributesKey("GO_COMMA", DefaultLanguageHighlighterColors.COMMA); public static final TextAttributesKey BAD_CHARACTER = createTextAttributesKey("GO_BAD_TOKEN", HighlighterColors.BAD_CHARACTER); public static final TextAttributesKey TYPE_SPECIFICATION = createTextAttributesKey("GO_TYPE_SPECIFICATION", DefaultLanguageHighlighterColors.CLASS_NAME); public static final TextAttributesKey TYPE_REFERENCE = createTextAttributesKey("GO_TYPE_REFERENCE", DefaultLanguageHighlighterColors.CLASS_REFERENCE); public static final TextAttributesKey BUILTIN_TYPE_REFERENCE = createTextAttributesKey("GO_BUILTIN_TYPE_REFERENCE", DefaultLanguageHighlighterColors.CLASS_REFERENCE); public static final TextAttributesKey BUILTIN_FUNCTION = createTextAttributesKey("GO_BUILTIN_FUNCTION", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION); public static final TextAttributesKey EXPORTED_FUNCTION = createTextAttributesKey("GO_EXPORTED_FUNCTION", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION); public static final TextAttributesKey LOCAL_FUNCTION = createTextAttributesKey("GO_LOCAL_FUNCTION", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION); public static final TextAttributesKey PACKAGE_EXPORTED_INTERFACE = createTextAttributesKey("GO_PACKAGE_EXPORTED_INTERFACE", DefaultLanguageHighlighterColors.INTERFACE_NAME); public static final TextAttributesKey PACKAGE_EXPORTED_STRUCT = createTextAttributesKey("GO_PACKAGE_EXPORTED_STRUCT", DefaultLanguageHighlighterColors.CLASS_NAME); public static final TextAttributesKey PACKAGE_EXPORTED_CONSTANT = createTextAttributesKey("GO_PACKAGE_EXPORTED_CONSTANT", DefaultLanguageHighlighterColors.CONSTANT); public static final TextAttributesKey PACKAGE_EXPORTED_VARIABLE = createTextAttributesKey("GO_PACKAGE_EXPORTED_VARIABLE", DefaultLanguageHighlighterColors.GLOBAL_VARIABLE); public static final TextAttributesKey PACKAGE_LOCAL_INTERFACE = createTextAttributesKey("GO_PACKAGE_LOCAL_INTERFACE", DefaultLanguageHighlighterColors.INTERFACE_NAME); public static final TextAttributesKey PACKAGE_LOCAL_STRUCT = createTextAttributesKey("GO_PACKAGE_LOCAL_STRUCT", DefaultLanguageHighlighterColors.CLASS_NAME); public static final TextAttributesKey PACKAGE_LOCAL_CONSTANT = createTextAttributesKey("GO_PACKAGE_LOCAL_CONSTANT", DefaultLanguageHighlighterColors.CONSTANT); public static final TextAttributesKey PACKAGE_LOCAL_VARIABLE = createTextAttributesKey("GO_PACKAGE_LOCAL_VARIABLE", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey STRUCT_EXPORTED_MEMBER = createTextAttributesKey("GO_STRUCT_EXPORTED_MEMBER", DefaultLanguageHighlighterColors.GLOBAL_VARIABLE); public static final TextAttributesKey STRUCT_LOCAL_MEMBER = createTextAttributesKey("GO_STRUCT_LOCAL_MEMBER", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey METHOD_RECEIVER = createTextAttributesKey("GO_METHOD_RECEIVER", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey FUNCTION_PARAMETER = createTextAttributesKey("GO_FUNCTION_PARAMETER", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey LOCAL_CONSTANT = createTextAttributesKey("GO_LOCAL_CONSTANT", DefaultLanguageHighlighterColors.CONSTANT); public static final TextAttributesKey LOCAL_VARIABLE = createTextAttributesKey("GO_LOCAL_VARIABLE", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey SCOPE_VARIABLE = createTextAttributesKey("GO_SCOPE_VARIABLE", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); public static final TextAttributesKey LABEL = createTextAttributesKey("GO_LABEL", DefaultLanguageHighlighterColors.LABEL); private GoSyntaxHighlightingColors() { } } ================================================ FILE: src/com/goide/highlighting/exitpoint/GoBreakStatementExitPointHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting.exitpoint; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoBreakStatementExitPointHandler extends HighlightUsagesHandlerBase { @NotNull private final PsiElement myTarget; @Nullable private final GoBreakStatement myBreakStatement; @Nullable private final PsiElement myOwner; private GoBreakStatementExitPointHandler(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement target, @Nullable GoBreakStatement breakStatement, @Nullable PsiElement owner) { super(editor, file); myTarget = target; myBreakStatement = breakStatement; myOwner = owner; } @NotNull @Override public List getTargets() { return Collections.singletonList(myTarget); } @Override protected void selectTargets(List targets, @NotNull Consumer> selectionConsumer) { selectionConsumer.consume(targets); } @Override public void computeUsages(List targets) { PsiElement breakStmtOwner = findBreakStatementOwner(); GoRecursiveVisitor visitor = new GoRecursiveVisitor() { @Override public void visitLabelDefinition(@NotNull GoLabelDefinition o) { if (o == breakStmtOwner) { addOccurrence(o); } super.visitLabelDefinition(o); } @Override public void visitBreakStatement(@NotNull GoBreakStatement o) { if (o == myBreakStatement || getBreakStatementOwnerOrResolve(o) == breakStmtOwner) { addOccurrence(o); } super.visitBreakStatement(o); } @Override public void visitSwitchStatement(@NotNull GoSwitchStatement o) { if (o == breakStmtOwner) { GoSwitchStart switchStart = o.getSwitchStart(); if (switchStart != null) { addOccurrence(switchStart.getSwitch()); } } super.visitSwitchStatement(o); } @Override public void visitForStatement(@NotNull GoForStatement o) { if (o == breakStmtOwner) { addOccurrence(o.getFor()); } super.visitForStatement(o); } @Override public void visitSelectStatement(@NotNull GoSelectStatement o) { if (o == breakStmtOwner) { addOccurrence(o.getSelect()); } super.visitSelectStatement(o); } }; if (breakStmtOwner != null) { PsiElement parent = breakStmtOwner.getParent(); if (parent instanceof GoCompositeElement) { visitor.visitCompositeElement((GoCompositeElement)parent); } } } @Nullable private PsiElement findBreakStatementOwner() { if (myOwner != null) return myOwner; if (myBreakStatement != null) return getBreakStatementOwnerOrResolve(myBreakStatement); return null; } @Nullable public static PsiElement getBreakStatementOwnerOrResolve(@NotNull GoBreakStatement breakStatement) { GoLabelRef label = breakStatement.getLabelRef(); if (label != null) { return label.getReference().resolve(); } return GoPsiImplUtil.getBreakStatementOwner(breakStatement); } @Nullable public static GoBreakStatementExitPointHandler createForElement(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement element) { PsiElement target = PsiTreeUtil.getParentOfType(element, GoBreakStatement.class, GoSwitchStatement.class, GoSelectStatement.class, GoForStatement.class); if (target == null) { return null; } return target instanceof GoBreakStatement ? new GoBreakStatementExitPointHandler(editor, file, element, (GoBreakStatement)target, null) : new GoBreakStatementExitPointHandler(editor, file, element, null, target); } } ================================================ FILE: src/com/goide/highlighting/exitpoint/GoFunctionExitPointHandler.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting.exitpoint; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoFunctionExitPointHandler extends HighlightUsagesHandlerBase { @NotNull private final PsiElement myTarget; @NotNull private final GoTypeOwner myFunction; private GoFunctionExitPointHandler(Editor editor, PsiFile file, @NotNull PsiElement target, @NotNull GoTypeOwner function) { super(editor, file); myTarget = target; myFunction = function; } @NotNull @Override public List getTargets() { return Collections.singletonList(myTarget); } @Override protected void selectTargets(List targets, @NotNull Consumer> selectionConsumer) { selectionConsumer.consume(targets); } @Override public void computeUsages(List targets) { if (myFunction instanceof GoFunctionOrMethodDeclaration) { addOccurrence(((GoFunctionOrMethodDeclaration)myFunction).getFunc()); } new GoRecursiveVisitor() { @Override public void visitFunctionLit(@NotNull GoFunctionLit literal) { } @Override public void visitReturnStatement(@NotNull GoReturnStatement statement) { addOccurrence(statement); } @Override public void visitCallExpr(@NotNull GoCallExpr o) { if (GoPsiImplUtil.isPanic(o)) addOccurrence(o); super.visitCallExpr(o); } }.visitTypeOwner(myFunction); } @Nullable public static GoFunctionExitPointHandler createForElement(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement element) { GoTypeOwner function = PsiTreeUtil.getParentOfType(element, GoFunctionLit.class, GoFunctionOrMethodDeclaration.class); return function != null ? new GoFunctionExitPointHandler(editor, file, element, function) : null; } } ================================================ FILE: src/com/goide/highlighting/exitpoint/GoHighlightExitPointsHandlerFactory.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.highlighting.exitpoint; import com.goide.GoTypes; import com.goide.psi.GoCallExpr; import com.goide.psi.GoReferenceExpression; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase; import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerFactoryBase; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoHighlightExitPointsHandlerFactory extends HighlightUsagesHandlerFactoryBase { private static final TokenSet BREAK_HIGHLIGHTING_TOKENS = TokenSet.create(GoTypes.BREAK, GoTypes.SWITCH, GoTypes.FOR, GoTypes.SELECT); @Nullable @Override public HighlightUsagesHandlerBase createHighlightUsagesHandler(@NotNull Editor editor, @NotNull PsiFile file, @NotNull PsiElement target) { if (target instanceof LeafPsiElement) { IElementType elementType = ((LeafPsiElement)target).getElementType(); if (elementType == GoTypes.RETURN || elementType == GoTypes.FUNC || isPanicCall(target)) { return GoFunctionExitPointHandler.createForElement(editor, file, target); } else if (BREAK_HIGHLIGHTING_TOKENS.contains(elementType)) { return GoBreakStatementExitPointHandler.createForElement(editor, file, target); } } return null; } private static boolean isPanicCall(@NotNull PsiElement e) { PsiElement parent = e.getParent(); if (parent instanceof GoReferenceExpression) { PsiElement grandPa = parent.getParent(); if (grandPa instanceof GoCallExpr) return GoPsiImplUtil.isPanic((GoCallExpr)grandPa); } return false; } } ================================================ FILE: src/com/goide/inspections/GoAddTrailingCommaInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoElement; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiErrorElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoAddTrailingCommaInspection extends GoInspectionBase { public static final String QUICK_FIX_NAME = "Add comma"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitErrorElement(PsiErrorElement o) { GoElement element = PsiTreeUtil.getPrevSiblingOfType(o, GoElement.class); if (element != null) { holder.registerProblem(element, "Need trailing comma before newline in composite literal", new MyAddCommaFix()); } } }; } private static class MyAddCommaFix extends LocalQuickFixBase { private MyAddCommaFix() {super(QUICK_FIX_NAME, QUICK_FIX_NAME);} @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement e = descriptor.getPsiElement(); if (!(e instanceof GoElement)) return; PsiErrorElement error = PsiTreeUtil.getNextSiblingOfType(e, PsiErrorElement.class); if (error == null) return; new WriteCommandAction.Simple(project, getName(), e.getContainingFile()) { @Override protected void run() { error.replace(GoElementFactory.createComma(project)); } }.execute(); } } } ================================================ FILE: src/com/goide/inspections/GoAnonymousFieldDefinitionTypeInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoAnonymousFieldDefinition; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoCreateWrapperTypeQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoAnonymousFieldDefinitionTypeInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitAnonymousFieldDefinition(@NotNull GoAnonymousFieldDefinition o) { if (o.getTypeReferenceExpression() == null) { holder.registerProblem(o, "Invalid type " + o.getType().getText() + ": must be typeName or *typeName", new GoCreateWrapperTypeQuickFix(o.getType())); } } }; } } ================================================ FILE: src/com/goide/inspections/GoAssignmentNilWithoutExplicitTypeInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoConstants; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoReferenceExpressionImpl; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.List; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; public class GoAssignmentNilWithoutExplicitTypeInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitVarDeclaration(@NotNull GoVarDeclaration o) { for (GoVarSpec spec : o.getVarSpecList()) { checkVar(spec); } } @Override public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { checkVar(o); } @Override public void visitConstDeclaration(@NotNull GoConstDeclaration o) { for (GoConstSpec spec : o.getConstSpecList()) { checkConst(spec); } } private void checkVar(@NotNull GoVarSpec spec) { if (spec.getType() != null) return; checkExpressions(spec.getRightExpressionsList()); } private void checkConst(@NotNull GoConstSpec spec) { if (spec.getType() != null) return; checkExpressions(spec.getExpressionList()); } private void checkExpressions(@NotNull List expressions) { for (GoExpression expr : expressions) { if (expr instanceof GoReferenceExpressionImpl) { GoReferenceExpressionImpl ref = (GoReferenceExpressionImpl)expr; PsiElement resolve = ref.resolve(); if (ref.getIdentifier().textMatches(GoConstants.NIL) && resolve != null && GoPsiImplUtil.builtin(resolve)) { holder.registerProblem(expr, "Cannot assign nil without explicit type", GENERIC_ERROR_OR_WARNING); } } } } }; } } ================================================ FILE: src/com/goide/inspections/GoAssignmentToReceiverInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoPointerType; import com.goide.psi.GoReceiver; import com.goide.psi.GoReferenceExpression; import com.goide.psi.GoUnaryExpr; import com.goide.psi.GoVisitor; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInspection.ProblemHighlightType.WEAK_WARNING; public class GoAssignmentToReceiverInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitReferenceExpression(@NotNull GoReferenceExpression o) { super.visitReferenceExpression(o); if (o.getReadWriteAccess() == ReadWriteAccessDetector.Access.Write) { PsiElement resolve = o.resolve(); if (resolve instanceof GoReceiver) { String message = "Assignment to method receiver doesn't propagate to other calls"; if (((GoReceiver)resolve).getType() instanceof GoPointerType) { if (o.getParent() instanceof GoUnaryExpr) { GoUnaryExpr p = (GoUnaryExpr)o.getParent(); if (p.getMul() != null) { // pointer dereference return; } } message = "Assignment to method receiver propagates only to callees but not to callers"; } holder.registerProblem(o, message, WEAK_WARNING); } } } }; } } ================================================ FILE: src/com/goide/inspections/GoBoolExpressionsInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoExpressionUtil; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.quickfix.GoSimplifyBoolExprQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.progress.ProgressManager; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoBoolExpressionsInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitAndExpr(@NotNull GoAndExpr o) { visitExpr(o, true); } @Override public void visitOrExpr(@NotNull GoOrExpr o) { visitExpr(o, false); } private void visitExpr(GoBinaryExpr o, boolean and) { if (!isTopmostOperationOfType(o, and)) return; List elements = collect(o, and); for (int i = 0; i < elements.size(); i++) { GoExpression l = elements.get(i); if (l instanceof GoReferenceExpression && (l.textMatches("true") || l.textMatches("false")) && GoPsiImplUtil.builtin(((GoReferenceExpression)l).resolve())) { registerProblem(o, holder); return; } for (int j = i + 1; j < elements.size(); j++) { ProgressManager.checkCanceled(); GoExpression r = elements.get(j); if (isEqualsWithNot(l, r) || isEqualsWithNot(r, l) || GoExpressionUtil.identical(l, r)) { registerProblem(o, holder); return; } // todo expr evaluating! x != c1 || x != c2 (c1, c2 const, c1 != c2) } } } private boolean isTopmostOperationOfType(GoBinaryExpr o, boolean isAndType) { PsiElement parent = PsiTreeUtil.skipParentsOfType(o, GoParenthesesExpr.class); return !(parent instanceof GoBinaryExpr) || !isSameOp((GoExpression)parent, isAndType); } }; } private static void registerProblem(@NotNull GoBinaryExpr o, @NotNull ProblemsHolder holder) { holder.registerProblem(o, "Simplify", new GoSimplifyBoolExprQuickFix(o)); } public static boolean isEqualsWithNot(@Nullable GoExpression not, @Nullable GoExpression expr) { return not instanceof GoUnaryExpr && ((GoUnaryExpr)not).getNot() != null && GoExpressionUtil.identical(((GoUnaryExpr)not).getExpression(), expr); } @NotNull public static List collect(GoBinaryExpr o, boolean and) { List result = ContainerUtil.newSmartList(); result.addAll(processExpr(o.getLeft(), and)); result.addAll(processExpr(o.getRight(), and)); return result; } @NotNull private static List processExpr(@Nullable GoExpression e, boolean and) { if (e == null) return ContainerUtil.emptyList(); if (isSameOp(e, and)) { return collect((GoBinaryExpr)e, and); } if (e instanceof GoParenthesesExpr) { return processExpr(((GoParenthesesExpr)e).getExpression(), and); } return Collections.singletonList(e); } private static boolean isSameOp(GoExpression expr, boolean and) { return and ? expr instanceof GoAndExpr : expr instanceof GoOrExpr; } } ================================================ FILE: src/com/goide/inspections/GoCgoInTestInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoCgoInTestInspection extends GoInspectionBase { @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } } } ================================================ FILE: src/com/goide/inspections/GoCommentStartInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoConstants; import com.goide.GoDocumentationProvider; import com.goide.psi.GoCompositeElement; import com.goide.psi.GoNamedElement; import com.goide.psi.GoPackageClause; import com.goide.psi.GoVisitor; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiComment; import org.jetbrains.annotations.NotNull; import java.util.List; /** * golint inspection from: * https://github.com/golang/lint/blob/32a87160691b3c96046c0c678fe57c5bef761456/lint.go#L744 */ public class GoCommentStartInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitPackageClause(@NotNull GoPackageClause o) { String packageName = o.getName(); if (GoConstants.MAIN.equals(packageName)) { return; } List comments = GoDocumentationProvider.getCommentsForElement(o); String commentText = GoDocumentationProvider.getCommentText(comments, false); if (!comments.isEmpty() && !commentText.isEmpty() && !commentText.startsWith("Package " + packageName)) { registerProblem(comments, "Package comment should be of the form 'Package " + packageName + " ...'", holder); } } @Override public void visitCompositeElement(@NotNull GoCompositeElement o) { if (!(o instanceof GoNamedElement) || !((GoNamedElement)o).isPublic()) { return; } List comments = GoDocumentationProvider.getCommentsForElement(o); String commentText = GoDocumentationProvider.getCommentText(comments, false); String elementName = ((GoNamedElement)o).getName(); if (elementName != null && !comments.isEmpty() && !commentText.isEmpty()) { if (!isCorrectComment(commentText, elementName)) { registerProblem(comments, "Comment should start with '" + elementName + "'", holder); } // +1 stands for Element_Name else if (commentText.length() <= elementName.length() + 1) { registerProblem(comments, "Comment should be meaningful or it should be removed", holder); } } } }; } private static void registerProblem(List comments, String description, @NotNull ProblemsHolder holder) { for (PsiComment comment : comments) { holder.registerProblem(comment, description, ProblemHighlightType.WEAK_WARNING); } } private static boolean isCorrectComment(String commentText, String elementName) { return commentText.startsWith(elementName) || commentText.startsWith("A " + elementName) || commentText.startsWith("An " + elementName) || commentText.startsWith("The " + elementName); } } ================================================ FILE: src/com/goide/inspections/GoDeferGoInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.quickfix.GoDeleteQuickFix; import com.intellij.codeInspection.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoDeferGoInspection extends GoInspectionBase { public static final String ADD_CALL_QUICK_FIX_NAME = "Add function call"; public static final String UNWRAP_PARENTHESES_QUICK_FIX_NAME = "Unwrap parentheses"; public static final String REPLACE_WITH_CORRECT_DEFER_RECOVER = "Replace with correct defer construct"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @SuppressWarnings("DialogTitleCapitalization") @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { super.visitDeferStatement(o); GoExpression expression = o.getExpression(); if (expression instanceof GoCallExpr) { GoCallExpr callExpr = (GoCallExpr)expression; if (GoPsiImplUtil.isPanic(callExpr)) { holder.registerProblem(o, "defer should not call panic() directly #loc", ProblemHighlightType.WEAK_WARNING, new GoDeleteQuickFix("Delete statement", GoDeferStatement.class)); return; } if (GoPsiImplUtil.isRecover(callExpr)) { holder.registerProblem(o, "defer should not call recover() directly #loc", ProblemHighlightType.WEAK_WARNING, new GoReplaceWithCorrectDeferRecoverQuickFix()); return; } } checkExpression(expression, "defer"); } @SuppressWarnings("DialogTitleCapitalization") @Override public void visitGoStatement(@NotNull GoGoStatement o) { super.visitGoStatement(o); GoExpression expression = o.getExpression(); if (expression instanceof GoCallExpr) { GoCallExpr callExpr = (GoCallExpr)expression; if (GoPsiImplUtil.isPanic(callExpr)) { holder.registerProblem(o, "go should not call panic() directly #loc", ProblemHighlightType.WEAK_WARNING, new GoDeleteQuickFix("Delete statement", GoGoStatement.class)); return; } if (GoPsiImplUtil.isRecover(callExpr)) { holder.registerProblem(o, "go should not call recover() directly #loc", ProblemHighlightType.WEAK_WARNING, new GoDeleteQuickFix("Delete statement", GoGoStatement.class)); return; } } checkExpression(expression, "go"); } private void checkExpression(@Nullable GoExpression o, @NotNull String who) { if (o == null) return; if (o instanceof GoCallExpr || o instanceof GoBuiltinCallExpr) { if (GoPsiImplUtil.isConversionExpression(o)) { holder.registerProblem(o, who + " requires function call, not conversion #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } return; } if (o instanceof GoParenthesesExpr) { holder.registerProblem(o, "Expression in " + who + " must not be parenthesized", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoUnwrapParensExpression()); } LocalQuickFix[] fixes = o.getGoType(null) instanceof GoFunctionType ? new LocalQuickFix[]{new GoAddParensQuickFix()} : LocalQuickFix.EMPTY_ARRAY; holder.registerProblem(o, "Expression in " + who + " must be function call", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fixes); } }; } public static class GoAddParensQuickFix extends LocalQuickFixBase { public GoAddParensQuickFix() { super(ADD_CALL_QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { addParensIfNeeded(project, descriptor.getStartElement()); } public static PsiElement addParensIfNeeded(@NotNull Project project, @Nullable PsiElement element) { if (element instanceof GoExpression && !(element instanceof GoCallExpr || element instanceof GoBuiltinCallExpr)) { if (((GoExpression)element).getGoType(null) instanceof GoFunctionType) { return element.replace(GoElementFactory.createExpression(project, element.getText() + "()")); } } return null; } } private static class GoUnwrapParensExpression extends LocalQuickFixBase { public GoUnwrapParensExpression() { super(UNWRAP_PARENTHESES_QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if (element instanceof GoParenthesesExpr) { GoExpression innerExpression = ((GoParenthesesExpr)element).getExpression(); while (innerExpression instanceof GoParenthesesExpr) { innerExpression = ((GoParenthesesExpr)innerExpression).getExpression(); } if (innerExpression != null) { element.replace(GoElementFactory.createExpression(project, innerExpression.getText())); } } } } public static class GoReplaceWithCorrectDeferRecoverQuickFix extends LocalQuickFixBase { public GoReplaceWithCorrectDeferRecoverQuickFix() { super(REPLACE_WITH_CORRECT_DEFER_RECOVER); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element == null || !element.isValid()) return; if (element instanceof GoStatement) { element.replace(GoElementFactory.createDeferStatement(project, "func() {\n" + "\tif r := recover(); r != nil {\n" + "\t\t\n" + "\t}\n" + "\t}()}")); } } } } ================================================ FILE: src/com/goide/inspections/GoDeferInLoopInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoDeferStatement; import com.goide.psi.GoForStatement; import com.goide.psi.GoFunctionLit; import com.goide.psi.GoVisitor; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoDeferInLoopInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { if (PsiTreeUtil.getParentOfType(o, GoForStatement.class, GoFunctionLit.class) instanceof GoForStatement) { holder.registerProblem(o.getDefer(), "Possible resource leak, 'defer' is called in a for loop.", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; } } ================================================ FILE: src/com/goide/inspections/GoDirectAssignToStructFieldInMapInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; public class GoDirectAssignToStructFieldInMapInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitLeftHandExprList(@NotNull GoLeftHandExprList o) { super.visitLeftHandExprList(o); for (GoExpression expression : o.getExpressionList()) { if (!(expression instanceof GoSelectorExpr)) continue; GoExpression expr = ContainerUtil.getFirstItem(((GoSelectorExpr)expression).getExpressionList()); if (expr instanceof GoIndexOrSliceExpr) { GoType exprType = expr.getGoType(null); if (exprType != null && !(exprType instanceof GoPointerType) && exprType.getParent() instanceof GoMapType) { holder.registerProblem(o, "cannot assign to " + expression.getText(), GENERIC_ERROR_OR_WARNING); } } } } }; } } ================================================ FILE: src/com/goide/inspections/GoDuplicateArgumentInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; public class GoDuplicateArgumentInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCompositeElement(@NotNull GoCompositeElement o) { if (o instanceof GoSignatureOwner) { check(((GoSignatureOwner)o).getSignature(), holder); } } }; } protected void check(@Nullable GoSignature o, @NotNull ProblemsHolder holder) { if (o != null) { checkParameters(holder, o.getParameters(), ContainerUtil.newLinkedHashSet()); } } protected static void checkParameters(@NotNull ProblemsHolder holder, @NotNull GoParameters parameters, @NotNull Set parameterNames) { for (GoParameterDeclaration fp : parameters.getParameterDeclarationList()) { for (GoParamDefinition parameter : fp.getParamDefinitionList()) { if (parameter.isBlank()) continue; String name = parameter.getName(); if (name != null && parameterNames.contains(name)) { holder.registerProblem(parameter, "Duplicate argument #ref #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } else { parameterNames.add(name); } } } } } ================================================ FILE: src/com/goide/inspections/GoDuplicateFieldsOrMethodsInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; public class GoDuplicateFieldsOrMethodsInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitStructType(@NotNull GoStructType type) { List fields = ContainerUtil.newArrayList(); type.accept(new GoRecursiveVisitor() { @Override public void visitFieldDefinition(@NotNull GoFieldDefinition o) { addField(o); } @Override public void visitAnonymousFieldDefinition(@NotNull GoAnonymousFieldDefinition o) { addField(o); } private void addField(@NotNull GoNamedElement o) { if (!o.isBlank()) fields.add(o); } @Override public void visitType(@NotNull GoType o) { if (o == type) super.visitType(o); } }); check(fields, holder, "field"); super.visitStructType(type); } @Override public void visitInterfaceType(@NotNull GoInterfaceType o) { check(o.getMethodSpecList(), holder, "method"); super.visitInterfaceType(o); } }; } private static void check(@NotNull List fields, @NotNull ProblemsHolder problemsHolder, @NotNull String what) { Set names = ContainerUtil.newHashSet(); for (GoCompositeElement field : fields) { if (field instanceof GoMethodSpec && ((GoMethodSpec) field).getSignature() == null) { // It's an embedded type, not a method or a field. continue; } if (field instanceof GoNamedElement) { String name = ((GoNamedElement)field).getName(); if (names.contains(name)) { PsiElement id = ((GoNamedElement)field).getIdentifier(); problemsHolder.registerProblem(id != null ? id : field, "Duplicate " + what + " #ref #loc", GENERIC_ERROR_OR_WARNING); } else { ContainerUtil.addIfNotNull(names, name); } } } } } ================================================ FILE: src/com/goide/inspections/GoDuplicateFunctionOrMethodInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.sdk.GoPackageUtil; import com.goide.stubs.index.GoFunctionIndex; import com.goide.stubs.index.GoIdFilter; import com.goide.stubs.index.GoMethodIndex; import com.goide.stubs.types.GoMethodDeclarationStubElementType; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Comparing; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import static com.goide.GoConstants.INIT; import static com.goide.GoConstants.MAIN; public class GoDuplicateFunctionOrMethodInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitMethodDeclaration(@NotNull GoMethodDeclaration method) { if (method.isBlank()) return; String methodName = method.getName(); if (methodName == null) return; String typeText = GoMethodDeclarationStubElementType.calcTypeText(method); if (typeText == null) return; GoFile file = method.getContainingFile(); GlobalSearchScope scope = GoPackageUtil.packageScope(file); IdFilter idFilter = GoIdFilter.getFilesFilter(scope); Module module = ModuleUtilCore.findModuleForPsiElement(file); String key = file.getPackageName() + "." + typeText; GoMethodIndex.process(key, file.getProject(), scope, idFilter, declaration -> { ProgressManager.checkCanceled(); if (!method.isEquivalentTo(declaration)) { if (Comparing.equal(declaration.getName(), methodName) && GoPsiImplUtil.allowed(declaration.getContainingFile(), file, module)) { PsiElement identifier = method.getNameIdentifier(); holder.registerProblem(identifier == null ? method : identifier, "Duplicate method name"); return false; } } return true; }); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration func) { if (func.isBlank()) return; String funcName = func.getName(); if (funcName == null) return; if (INIT.equals(funcName) && zeroArity(func)) return; GoFile file = func.getContainingFile(); boolean isMainFunction = MAIN.equals(funcName) && MAIN.equals(file.getPackageName()) && zeroArity(func); Module module = ModuleUtilCore.findModuleForPsiElement(file); GlobalSearchScope scope = GoPackageUtil.packageScope(file); IdFilter idFilter = GoIdFilter.getFilesFilter(scope); GoFunctionIndex.process(funcName, file.getProject(), scope, idFilter, declaration -> { ProgressManager.checkCanceled(); if (!func.isEquivalentTo(declaration) && GoPsiImplUtil.allowed(declaration.getContainingFile(), file, module)) { if (!isMainFunction || Comparing.equal(declaration.getContainingFile(), file)) { PsiElement identifier = func.getNameIdentifier(); holder.registerProblem(identifier == null ? func : identifier, "Duplicate function name"); return false; } } return true; }); } }; } private static boolean zeroArity(@NotNull GoFunctionDeclaration o) { GoSignature signature = o.getSignature(); return signature == null || signature.getParameters().getParameterDeclarationList().isEmpty(); } } ================================================ FILE: src/com/goide/inspections/GoDuplicateReturnArgumentInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; public class GoDuplicateReturnArgumentInspection extends GoDuplicateArgumentInspection { @Override public void check(@Nullable GoSignature o, @NotNull ProblemsHolder holder) { if (o == null) return; Set names = getParamNames(o); GoResult result = o.getResult(); if (result == null) return; GoParameters parameters = result.getParameters(); if (parameters == null) return; checkParameters(holder, parameters, names); } @NotNull private static Set getParamNames(@NotNull GoSignature o) { List params = o.getParameters().getParameterDeclarationList(); Set names = ContainerUtil.newLinkedHashSet(); for (GoParameterDeclaration fp : params) { for (GoParamDefinition parameter : fp.getParamDefinitionList()) { if (parameter.isBlank()) continue; ContainerUtil.addIfNotNull(names, parameter.getName()); } } return names; } } ================================================ FILE: src/com/goide/inspections/GoEmbeddedInterfacePointerInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoEmbeddedInterfacePointerInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitAnonymousFieldDefinition(@NotNull GoAnonymousFieldDefinition o) { if (!(o.getType() instanceof GoPointerType)) return; GoTypeReferenceExpression reference = o.getTypeReferenceExpression(); GoType goType = reference != null ? reference.resolveType() : null; if (!(goType instanceof GoSpecType)) return; if (!(((GoSpecType)goType).getType() instanceof GoInterfaceType)) return; holder.registerProblem(o, "Embedded type cannot be a pointer to interface", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } }; } } ================================================ FILE: src/com/goide/inspections/GoEmptyDeclarationInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoDocumentationProvider; import com.goide.psi.*; import com.goide.quickfix.GoDeleteQuickFix; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoEmptyDeclarationInspection extends GoInspectionBase implements CleanupLocalInspectionTool { public final static String QUICK_FIX_NAME = "Delete empty declaration"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitConstDeclaration(@NotNull GoConstDeclaration o) { visitDeclaration(o); } @Override public void visitVarDeclaration(@NotNull GoVarDeclaration o) { if (o.getParent() instanceof GoFile) { visitDeclaration(o); } } @Override public void visitTypeDeclaration(@NotNull GoTypeDeclaration o) { visitDeclaration(o); } @Override public void visitImportDeclaration(@NotNull GoImportDeclaration o) { visitDeclaration(o); } private void visitDeclaration (PsiElement o) { if (o.getChildren().length == 0 && GoDocumentationProvider.getCommentsForElement(o instanceof GoImportDeclaration && o.getPrevSibling() == null ? o.getParent() : o).isEmpty() && PsiTreeUtil.findChildrenOfType(o, PsiComment.class).isEmpty()) { holder.registerProblem(o, "Empty declaration #ref #loc", ProblemHighlightType.LIKE_UNUSED_SYMBOL, new GoDeleteQuickFix(QUICK_FIX_NAME, o.getClass())); } } }; } } ================================================ FILE: src/com/goide/inspections/GoExportedOwnDeclarationInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.*; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; /** * Part of the golint tool *

    * https://github.com/golang/lint/blob/32a87160691b3c96046c0c678fe57c5bef761456/lint.go#L827 */ public class GoExportedOwnDeclarationInspection extends GoInspectionBase { public static final String QUICK_FIX_NAME = "Extract to own declaration"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitConstDeclaration(@NotNull GoConstDeclaration o) { if (o.getParent() instanceof GoFile) { for (GoConstSpec spec : o.getConstSpecList()) { boolean first = true; for (GoConstDefinition constDefinition : spec.getConstDefinitionList()) { if (!first && constDefinition.isPublic()) { String errorText = "Exported const #ref should have its own declaration #loc"; holder.registerProblem(constDefinition, errorText, ProblemHighlightType.WEAK_WARNING, new ExtractConstantDefinitionFix()); } first = false; } } } } @Override public void visitVarDeclaration(@NotNull GoVarDeclaration o) { if (o.getParent() instanceof GoFile) { for (GoVarSpec spec : o.getVarSpecList()) { boolean first = true; for (GoVarDefinition varDefinition : spec.getVarDefinitionList()) { if (!first && varDefinition.isPublic()) { String errorText = "Exported variable #ref should have its own declaration #loc"; holder.registerProblem(varDefinition, errorText, ProblemHighlightType.WEAK_WARNING, new ExtractVarDefinitionFix()); } first = false; } } } } }; } private static class ExtractConstantDefinitionFix extends LocalQuickFixBase { private static final Logger LOG = Logger.getInstance(ExtractConstantDefinitionFix.class); ExtractConstantDefinitionFix() { super(QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (!element.isValid() || !(element instanceof GoConstDefinition)) { return; } String name = ((GoConstDefinition)element).getName(); if (StringUtil.isEmpty(name)) { return; } GoType type = ((GoConstDefinition)element).findSiblingType(); GoExpression value = ((GoConstDefinition)element).getValue(); WriteCommandAction.runWriteCommandAction(project, () -> { PsiElement parent = element.getParent(); PsiElement grandParent = parent != null ? parent.getParent() : null; if (parent instanceof GoConstSpec && grandParent instanceof GoConstDeclaration) { if (!parent.isValid() || ((GoConstSpec)parent).getConstDefinitionList().indexOf(element) <= 0) { return; } String typeText = type != null ? type.getText() : ""; String valueText = value != null ? value.getText() : ""; ((GoConstSpec)parent).deleteDefinition((GoConstDefinition)element); if (grandParent.isValid()) { ((GoConstDeclaration)grandParent).addSpec(name, typeText, valueText, (GoConstSpec)parent); return; } } LOG.error("Cannot run quick fix", AttachmentFactory.createAttachment(element.getContainingFile().getVirtualFile())); }); } } private static class ExtractVarDefinitionFix extends LocalQuickFixBase { private static final Logger LOG = Logger.getInstance(ExtractVarDefinitionFix.class); ExtractVarDefinitionFix() { super(QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (!element.isValid() || !(element instanceof GoVarDefinition)) { return; } String name = ((GoVarDefinition)element).getName(); if (StringUtil.isEmpty(name)) { return; } GoType type = ((GoVarDefinition)element).findSiblingType(); GoExpression value = ((GoVarDefinition)element).getValue(); WriteCommandAction.runWriteCommandAction(project, () -> { PsiElement parent = element.getParent(); PsiElement grandParent = parent != null ? parent.getParent() : null; if (parent instanceof GoVarSpec && grandParent instanceof GoVarDeclaration) { if (!parent.isValid() || ((GoVarSpec)parent).getVarDefinitionList().indexOf(element) <= 0) { return; } String typeText = type != null ? type.getText() : ""; String valueText = value != null ? value.getText() : ""; ((GoVarSpec)parent).deleteDefinition((GoVarDefinition)element); if (grandParent.isValid()) { ((GoVarDeclaration)grandParent).addSpec(name, typeText, valueText, (GoVarSpec)parent); return; } } LOG.error("Cannot run quick fix", AttachmentFactory.createAttachment(element.getContainingFile().getVirtualFile())); }); } } } ================================================ FILE: src/com/goide/inspections/GoFileIgnoredByBuildToolNotificationProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoFileType; import com.goide.project.GoModuleSettings; import com.goide.util.GoUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Set; public class GoFileIgnoredByBuildToolNotificationProvider extends EditorNotifications.Provider implements DumbAware { private static final Key KEY = Key.create("Go file ignored by build tool"); private static final String DO_NOT_SHOW_NOTIFICATION_ABOUT_IGNORE_BY_BUILD_TOOL = "DO_NOT_SHOW_NOTIFICATION_ABOUT_IGNORE_BY_BUILD_TOOL"; private final Project myProject; public GoFileIgnoredByBuildToolNotificationProvider(@NotNull Project project, @NotNull EditorNotifications notifications, @NotNull FileEditorManager fileEditorManager) { myProject = project; MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(GoModuleSettings.TOPIC, module -> notifications.updateAllNotifications()); connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener.Adapter() { @Override public void after(@NotNull List events) { if (!myProject.isDisposed()) { Set openFiles = ContainerUtil.newHashSet(fileEditorManager.getSelectedFiles()); for (VFileEvent event : events) { VirtualFile file = event.getFile(); if (file != null && openFiles.contains(file)) { notifications.updateNotifications(file); } } } } }); } @NotNull @Override public Key getKey() { return KEY; } @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) { if (file.getFileType() == GoFileType.INSTANCE) { PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); if (InjectedLanguageUtil.findInjectionHost(psiFile) != null) { return null; } Module module = psiFile != null ? ModuleUtilCore.findModuleForPsiElement(psiFile) : null; if (GoUtil.fileToIgnore(file.getName())) { if (!PropertiesComponent.getInstance().getBoolean(DO_NOT_SHOW_NOTIFICATION_ABOUT_IGNORE_BY_BUILD_TOOL, false)) { return createIgnoredByBuildToolPanel(myProject, file); } } else if (module != null && !GoUtil.matchedForModuleBuildTarget(psiFile, module)) { return createMismatchedTargetPanel(module, file); } } return null; } private static EditorNotificationPanel createIgnoredByBuildToolPanel(@NotNull Project project, @NotNull VirtualFile file) { EditorNotificationPanel panel = new EditorNotificationPanel(); String fileName = file.getName(); panel.setText("'" + fileName + "' will be ignored by build tool since its name starts with '" + fileName.charAt(0) + "'"); panel.createActionLabel("Do not show again", () -> { PropertiesComponent.getInstance().setValue(DO_NOT_SHOW_NOTIFICATION_ABOUT_IGNORE_BY_BUILD_TOOL, true); EditorNotifications.getInstance(project).updateAllNotifications(); }); return panel; } @NotNull private static EditorNotificationPanel createMismatchedTargetPanel(@NotNull Module module, @NotNull VirtualFile file) { EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText("'" + file.getName() + "' doesn't match to target system. File will be ignored by build tool"); panel.createActionLabel("Edit Go project settings", () -> GoModuleSettings.showModulesConfigurable(module)); return panel; } } ================================================ FILE: src/com/goide/inspections/GoFunctionCallInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoFunctionCallInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { super.visitCallExpr(o); PsiElement resolve = GoPsiImplUtil.resolveCallRaw(o); GoExpression expression = o.getExpression(); if (resolve != null && expression instanceof GoReferenceExpression) { List list = o.getArgumentList().getExpressionList(); int actualSize = list.size(); if (resolve instanceof GoTypeSpec && actualSize != 1) { String message = String.format("%sto conversion to %s: %s.", actualSize == 0 ? "Missing argument " : "Too many arguments ", expression.getText(), o.getText()); holder.registerProblem(o, message); } else if (resolve instanceof GoSignatureOwner) { GoSignature signature = ((GoSignatureOwner)resolve).getSignature(); if (signature == null) return; int expectedSize = 0; GoParameters parameters = signature.getParameters(); for (GoParameterDeclaration declaration : parameters.getParameterDeclarationList()) { if (declaration.isVariadic() && actualSize >= expectedSize) return; int size = declaration.getParamDefinitionList().size(); expectedSize += size == 0 ? 1 : size; } if (actualSize == 1) { GoExpression first = ContainerUtil.getFirstItem(list); GoSignatureOwner firstResolve = GoPsiImplUtil.resolveCall(first); if (firstResolve != null) { actualSize = GoInspectionUtil.getFunctionResultCount(firstResolve); } } GoReferenceExpression qualifier = ((GoReferenceExpression)expression).getQualifier(); boolean isMethodExpr = qualifier != null && qualifier.resolve() instanceof GoTypeSpec; if (isMethodExpr) actualSize -= 1; // todo: a temp workaround for method specs if (actualSize == expectedSize) return; String tail = " arguments in call to " + expression.getText(); holder.registerProblem(o.getArgumentList(), (actualSize > expectedSize ? "too many" : "not enough") + tail); } } } }; } } ================================================ FILE: src/com/goide/inspections/GoFunctionVariadicParameterInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.quickfix.GoDeleteQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.List; import static com.goide.GoTypes.TRIPLE_DOT; public class GoFunctionVariadicParameterInspection extends GoInspectionBase { private static final GoDeleteQuickFix DELETE_QUICK_FIX = new GoDeleteQuickFix("Delete ...", TRIPLE_DOT); @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCompositeElement(@NotNull GoCompositeElement o) { if (o instanceof GoSignatureOwner) { GoSignature signature = ((GoSignatureOwner)o).getSignature(); if (signature != null) { checkResult(signature, holder); checkParameters(signature, holder); } } } }; } private static void checkResult(@NotNull GoSignature o, @NotNull ProblemsHolder holder) { GoResult result = o.getResult(); if (result == null) return; GoParameters parameters = result.getParameters(); if (parameters == null) return; for (GoParameterDeclaration declaration : parameters.getParameterDeclarationList()) { PsiElement dot = declaration.getTripleDot(); if (dot != null) { holder.registerProblem(dot, "Cannot use ... in output argument list", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, DELETE_QUICK_FIX); } } } private static void checkParameters(@NotNull GoSignature o, @NotNull ProblemsHolder holder) { GoParameters parameters = o.getParameters(); List list = parameters.getParameterDeclarationList(); int size = list.size(); for (int i = 0; i < size; i++) { GoParameterDeclaration declaration = list.get(i); PsiElement dot = declaration.getTripleDot(); if (dot != null) { if (declaration.getParamDefinitionList().size() > 1 || i != size - 1) { holder.registerProblem(dot, "Can only use ... as final argument in list", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, DELETE_QUICK_FIX); } } } } } ================================================ FILE: src/com/goide/inspections/GoImportUsedAsNameInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.quickfix.GoRenameQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageViewTypeLocation; import org.jetbrains.annotations.NotNull; public class GoImportUsedAsNameInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitTypeSpec(@NotNull GoTypeSpec o) { super.visitTypeSpec(o); check(o, holder); } @Override public void visitConstDefinition(@NotNull GoConstDefinition o) { super.visitConstDefinition(o); check(o, holder); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { super.visitFunctionDeclaration(o); check(o, holder); } @Override public void visitVarDefinition(@NotNull GoVarDefinition o) { super.visitVarDefinition(o); check(o, holder); } }; } private static void check(@NotNull GoNamedElement element, @NotNull ProblemsHolder holder) { String name = element.getName(); if (StringUtil.isNotEmpty(name) && !"_".equals(name) && element.getContainingFile().getImportMap().containsKey(name)) { registerProblem(holder, element); } } private static void registerProblem(@NotNull ProblemsHolder holder, @NotNull GoNamedElement element) { PsiElement identifier = element.getIdentifier(); if (identifier != null) { String elementDescription = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE); String message = StringUtil.capitalize(elementDescription) + " #ref collides with imported package name #loc"; holder.registerProblem(identifier, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoRenameQuickFix(element)); } } } ================================================ FILE: src/com/goide/inspections/GoInfiniteForInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.quickfix.GoReplaceWithSelectStatementQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoInfiniteForInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitForStatement(@NotNull GoForStatement o) { super.visitForStatement(o); if (o.getExpression() == null && isEmpty(o.getBlock()) && !hasRangeClause(o.getRangeClause()) && !hasClause(o.getForClause())) { holder.registerProblem(o, "Infinite for loop", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoReplaceWithSelectStatementQuickFix()); } } }; } private static boolean isEmpty(@Nullable GoBlock block) { return block != null && block.getStatementList().isEmpty(); } private static boolean hasRangeClause(@Nullable GoRangeClause rangeClause) { return rangeClause != null && !rangeClause.getExpressionList().isEmpty(); } private static boolean hasClause(@Nullable GoForClause forClause) { return forClause != null && !forClause.getStatementList().isEmpty(); } } ================================================ FILE: src/com/goide/inspections/GoInspectionBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFile; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.*; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; abstract public class GoInspectionBase extends LocalInspectionTool { protected static final GoVisitor DUMMY_VISITOR = new GoVisitor() { }; @NotNull @Override public final PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { GoFile file = ObjectUtils.tryCast(session.getFile(), GoFile.class); return file != null && GoPsiImplUtil.allowed(file, null, ModuleUtilCore.findModuleForPsiElement(file)) ? buildGoVisitor(holder, session) : DUMMY_VISITOR; } @NotNull @Override public final PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) { throw new IllegalStateException(); } @Nullable @Override public final ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) { throw new IllegalStateException(); } @NotNull protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFile(PsiFile file) { checkFile((GoFile)file, holder); } }; } protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { } } ================================================ FILE: src/com/goide/inspections/GoInspectionUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoInspectionUtil { public static final int UNKNOWN_COUNT = -1; private GoInspectionUtil() {} public static int getExpressionResultCount(GoExpression call) { if (call instanceof GoLiteral || call instanceof GoStringLiteral || call instanceof GoBinaryExpr || call instanceof GoUnaryExpr && ((GoUnaryExpr)call).getSendChannel() == null || call instanceof GoBuiltinCallExpr || call instanceof GoCompositeLit || call instanceof GoIndexOrSliceExpr || call instanceof GoFunctionLit) { return 1; } if (call instanceof GoParenthesesExpr) { return getExpressionResultCount(((GoParenthesesExpr)call).getExpression()); } if (call instanceof GoTypeAssertionExpr) { return getTypeAssertionResultCount((GoTypeAssertionExpr)call); } if (GoPsiImplUtil.isConversionExpression(call)) { return 1; } if (call instanceof GoCallExpr) { return getFunctionResultCount((GoCallExpr)call); } if (call instanceof GoReferenceExpression) { // todo: always 1? PsiElement resolve = ((GoReferenceExpression)call).resolve(); if (resolve instanceof GoVarDefinition || resolve instanceof GoParamDefinition || resolve instanceof GoReceiver) return 1; } return UNKNOWN_COUNT; } private static int getTypeAssertionResultCount(@NotNull GoTypeAssertionExpr expression) { // todo: ??? PsiElement parent = expression.getParent(); if (parent instanceof GoAssignmentStatement) { // TODO: get expressions and identifiers of assign statement return UNKNOWN_COUNT; } if (!(parent instanceof GoVarSpec)) { return 1; } List identifiers = ((GoVarSpec)parent).getVarDefinitionList(); List expressions = ((GoVarSpec)parent).getRightExpressionsList(); // if the type assertion is the only expression, and there are two variables. // The result of the type assertion is a pair of values with types (T, bool) if (identifiers.size() == 2 && expressions.size() == 1) { return 2; } return 1; } public static int getFunctionResultCount(@NotNull GoCallExpr call) { GoSignatureOwner signatureOwner = GoPsiImplUtil.resolveCall(call); return signatureOwner == null ? UNKNOWN_COUNT : getFunctionResultCount(signatureOwner); } public static int getFunctionResultCount(@NotNull GoSignatureOwner function) { int count = 0; GoSignature signature = function.getSignature(); GoResult result = signature != null ? signature.getResult() : null; GoParameters parameters = result != null ? result.getParameters() : null; if (parameters != null) { for (GoParameterDeclaration p : parameters.getParameterDeclarationList()) { count += Math.max(p.getParamDefinitionList().size(), 1); } return count; } if (result != null) { GoType type = result.getType(); if (type instanceof GoTypeList) return ((GoTypeList)type).getTypeList().size(); if (type != null) return 1; } return count; } } ================================================ FILE: src/com/goide/inspections/GoInvalidPackageImportInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoConstants; import com.goide.project.GoVendoringUtil; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.psi.impl.imports.GoImportReference; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.quickfix.GoDisableVendoringInModuleQuickFix; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoPackageUtil; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Set; public class GoInvalidPackageImportInspection extends GoInspectionBase { public static final String DELETE_ALIAS_QUICK_FIX_NAME = "Delete alias"; @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { Module module = ModuleUtilCore.findModuleForPsiElement(file); VirtualFile sdkHome = GoSdkUtil.getSdkSrcDir(file.getProject(), module); boolean supportsVendoring = GoVendoringUtil.isVendoringEnabled(module); String sdkVersion = GoSdkService.getInstance(file.getProject()).getSdkVersion(module); boolean supportsInternalPackages = GoVendoringUtil.supportsInternalPackages(sdkVersion); boolean supportsInternalPackagesInSdk = sdkHome != null && GoVendoringUtil.supportsSdkInternalPackages(sdkVersion); for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { PsiElement dot = importSpec.getDot(); if (dot != null) { problemsHolder.registerProblem(importSpec, "Cannot rename import `C`", new GoDeleteImportSpecAlias(), new GoDeleteImportQuickFix()); } PsiElement identifier = importSpec.getIdentifier(); if (identifier != null) { problemsHolder.registerProblem(importSpec, "Cannot import 'builtin' package", new GoDeleteImportSpecAlias(), new GoDeleteImportQuickFix()); } continue; } PsiDirectory resolve = importSpec.getImportString().resolve(); if (resolve != null) { if (GoPackageUtil.isBuiltinPackage(resolve)) { problemsHolder.registerProblem(importSpec, "Cannot import 'builtin' package", new GoDeleteImportQuickFix()); } Collection packagesInDirectory = GoPackageUtil.getAllPackagesInDirectory(resolve, module, true); if (packagesInDirectory.isEmpty()) { problemsHolder.registerProblem(importSpec, "'" + resolve.getVirtualFile().getPath() + "' has no buildable Go source files", new GoDeleteImportQuickFix()); continue; } if (!GoTestFinder.isTestFile(file) && packagesInDirectory.size() == 1 && packagesInDirectory.contains(GoConstants.MAIN)) { problemsHolder.registerProblem(importSpec, "'" + importSpec.getPath() + "' is a program, not an importable package", new GoDeleteImportQuickFix()); continue; } if (packagesInDirectory.size() > 1) { problemsHolder.registerProblem(importSpec, "Found several packages [" + StringUtil.join(packagesInDirectory, ", ") + "] in '" + resolve.getVirtualFile().getPath() + "'", new GoDeleteImportQuickFix()); continue; } VirtualFile contextFile = file.getVirtualFile(); VirtualFile resolvedFile = resolve.getVirtualFile(); boolean resolvedToSdk = sdkHome != null && VfsUtilCore.isAncestor(sdkHome, resolvedFile, false); boolean validateInternal = supportsInternalPackages || supportsInternalPackagesInSdk && resolvedToSdk; if (supportsVendoring || validateInternal || resolvedToSdk) { Set sourceRoots = GoSdkUtil.getSourcesPathsToLookup(file.getProject(), module); for (PsiReference reference : importSpec.getImportString().getReferences()) { if (reference instanceof GoImportReference) { String canonicalText = reference.getCanonicalText(); if (resolvedToSdk && GoConstants.TESTDATA_NAME.equals(canonicalText)) { problemsHolder.registerProblem(importSpec, "Use of testdata package from SDK is not allowed", new GoDeleteImportQuickFix()); break; } else if (validateInternal && GoConstants.INTERNAL.equals(canonicalText)) { if (GoSdkUtil.isUnreachableInternalPackage(resolvedFile, contextFile, sourceRoots)) { problemsHolder.registerProblem(importSpec, "Use of internal package is not allowed", new GoDeleteImportQuickFix()); break; } } else if (supportsVendoring && GoConstants.VENDOR.equals(canonicalText)) { if (GoSdkUtil.isUnreachableVendoredPackage(resolvedFile, contextFile, sourceRoots)) { problemsHolder.registerProblem(importSpec, "Use of vendored package is not allowed", new GoDeleteImportQuickFix(), GoDisableVendoringInModuleQuickFix.create(module)); break; } else { String vendoredImportPath = GoSdkUtil.getImportPath(resolve, true); if (vendoredImportPath != null) { problemsHolder.registerProblem(importSpec, "Must be imported as '" + vendoredImportPath + "'", new GoReplaceImportPath(vendoredImportPath), new GoDeleteImportQuickFix(), GoDisableVendoringInModuleQuickFix.create(module)); break; } } } } } } } else { for (PsiReference reference : importSpec.getImportString().getReferences()) { if (reference instanceof GoImportReference) { if (((GoImportReference)reference).getFileReferenceSet().isAbsolutePathReference()) { problemsHolder.registerProblem(importSpec, "Cannot import absolute path", new GoDeleteImportQuickFix()); break; } } } } } } private static class GoDeleteImportSpecAlias extends LocalQuickFixBase { protected GoDeleteImportSpecAlias() { super(DELETE_ALIAS_QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { GoImportSpec element = ObjectUtils.tryCast(descriptor.getPsiElement(), GoImportSpec.class); if (element != null) { WriteCommandAction.runWriteCommandAction(project, () -> { PsiElement dot = element.getDot(); if (dot != null) { dot.delete(); return; } PsiElement identifier = element.getIdentifier(); if (identifier != null) { identifier.delete(); } }); } } } private static class GoReplaceImportPath extends LocalQuickFixBase implements HighPriorityAction { @NotNull private final String myNewImportPath; protected GoReplaceImportPath(@NotNull String newImportPath) { super("Replace with '" + newImportPath + "'"); myNewImportPath = newImportPath; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { GoImportSpec element = ObjectUtils.tryCast(descriptor.getPsiElement(), GoImportSpec.class); if (element != null) { ElementManipulators.handleContentChange(element.getImportString(), myNewImportPath); } } } } ================================================ FILE: src/com/goide/inspections/GoInvalidStringOrCharInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoLiteral; import com.goide.psi.GoStringLiteral; import com.goide.psi.GoVisitor; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.jetbrains.annotations.NotNull; public class GoInvalidStringOrCharInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitStringLiteral(@NotNull GoStringLiteral o) { PsiElement s = o.getString(); if (s instanceof LeafPsiElement) { int length = ((LeafPsiElement)s).getCachedLength(); if (length == 1 || ((LeafPsiElement)s).charAt(length - 1) != '"') { holder.registerProblem(s, "New line in string"); } } } @Override public void visitLiteral(@NotNull GoLiteral o) { PsiElement c = o.getChar(); if (c instanceof LeafPsiElement) { int length = ((LeafPsiElement)c).getCachedLength(); if (length == 3 && ((LeafPsiElement)c).charAt(1) == '\'') { holder.registerProblem(c, "Empty character literal or unescaped ' in character literal"); } if (length < 3) { holder.registerProblem(c, "Missing '"); } } } }; } } ================================================ FILE: src/com/goide/inspections/GoMissingReturnInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.highlighting.exitpoint.GoBreakStatementExitPointHandler; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoMissingReturnInspection extends GoInspectionBase { public static final String ADD_RETURN_STATEMENT_QUICK_FIX_NAME = "Add return statement"; private static void check(@Nullable GoSignature signature, @Nullable GoBlock block, @NotNull ProblemsHolder holder) { if (block == null) return; GoResult result = signature != null ? signature.getResult() : null; if (result == null || result.isVoid() || isTerminating(block)) return; PsiElement brace = block.getRbrace(); holder.registerProblem(brace == null ? block : brace, "Missing return at end of function", brace == null ? new LocalQuickFix[]{} : new LocalQuickFix[]{new AddReturnFix(block)}); } // https://tip.golang.org/ref/spec#Terminating_statements private static boolean isTerminating(@Nullable GoCompositeElement s) { if (s instanceof GoReturnStatement || s instanceof GoGotoStatement) { return true; } if (s instanceof GoSimpleStatement) { GoLeftHandExprList list = ((GoSimpleStatement)s).getLeftHandExprList(); GoExpression expression = ContainerUtil.getFirstItem(list != null ? list.getExpressionList() : null); if (expression instanceof GoCallExpr && GoPsiImplUtil.isPanic((GoCallExpr)expression)) return true; } else if (s instanceof GoBlock) { return isTerminating(ContainerUtil.getLastItem(((GoBlock)s).getStatementList())); } else if (s instanceof GoIfStatement) { GoBlock block = ((GoIfStatement)s).getBlock(); GoStatement st = ((GoIfStatement)s).getElseStatement(); return block != null && isTerminating(block) && st != null && isTerminating(st); } else if (s instanceof GoElseStatement) { GoIfStatement ifStatement = ((GoElseStatement)s).getIfStatement(); if (ifStatement != null) return isTerminating(ifStatement); GoBlock block = ((GoElseStatement)s).getBlock(); if (block != null) return isTerminating(block); return false; } else if (s instanceof GoForStatement) { GoForStatement f = (GoForStatement)s; GoForClause forClause = f.getForClause(); if (forClause != null && forClause.getExpression() != null || f.getExpression() != null || f.getRangeClause() != null) return false; GoBlock block = f.getBlock(); return block == null || !hasReferringBreakStatement(f); } else if (s instanceof GoExprSwitchStatement) { return isTerminating((GoExprSwitchStatement)s, ((GoExprSwitchStatement)s).getExprCaseClauseList()); } else if (s instanceof GoTypeSwitchStatement) { return isTerminating((GoTypeSwitchStatement)s, ((GoTypeSwitchStatement)s).getTypeCaseClauseList()); } else if (s instanceof GoSelectStatement) { GoSelectStatement selectStatement = (GoSelectStatement)s; for (GoCommClause clause : selectStatement.getCommClauseList()) { List statements = clause.getStatementList(); if (hasReferringBreakStatement(selectStatement)) return false; if (!isTerminating(ContainerUtil.getLastItem(statements))) return false; } return true; } else if (s instanceof GoLabeledStatement) { GoLabeledStatement labeledStatement = (GoLabeledStatement)s; return isTerminating(labeledStatement.getStatement()); } else if (s instanceof GoStatement && ((GoStatement)s).getBlock() != null) { return isTerminating(((GoStatement)s).getBlock()); } return false; } private static boolean isTerminating(@NotNull GoSwitchStatement switchStatement, @NotNull List clauses) { boolean hasDefault = false; for (GoCaseClause clause : clauses) { hasDefault |= clause.getDefault() != null; List statements = clause.getStatementList(); if (hasReferringBreakStatement(switchStatement)) return false; GoStatement last = ContainerUtil.getLastItem(statements); if (!(last instanceof GoFallthroughStatement) && !isTerminating(last)) return false; } return hasDefault; } private static boolean hasReferringBreakStatement(@NotNull PsiElement breakStatementOwner) { return !GoPsiImplUtil.goTraverser().withRoot(breakStatementOwner).traverse().filter(GoBreakStatement.class).filter(statement -> { PsiElement owner = GoBreakStatementExitPointHandler.getBreakStatementOwnerOrResolve(statement); if (breakStatementOwner.equals(owner)) { return true; } if (owner instanceof GoLabelDefinition) { PsiElement parent = owner.getParent(); if (parent instanceof GoLabeledStatement && breakStatementOwner.equals(((GoLabeledStatement)parent).getStatement())) { return true; } } return false; }).isEmpty(); } @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { check(o.getSignature(), o.getBlock(), holder); } }; } private static class AddReturnFix extends LocalQuickFixAndIntentionActionOnPsiElement { public AddReturnFix(@NotNull GoBlock block) { super(block); } @NotNull @Override public String getText() { return ADD_RETURN_STATEMENT_QUICK_FIX_NAME; } @NotNull @Override public String getFamilyName() { return getName(); } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!(file instanceof GoFile) || editor == null || !(startElement instanceof GoBlock)) return; PsiElement brace = ((GoBlock)startElement).getRbrace(); if (brace == null) return; Template template = TemplateSettings.getInstance().getTemplateById("go_lang_add_return"); if (template == null) return; int start = brace.getTextRange().getStartOffset(); editor.getCaretModel().moveToOffset(start); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); template.setToReformat(true); TemplateManager.getInstance(project).startTemplate(editor, template, true, Collections.emptyMap(), null); } } } ================================================ FILE: src/com/goide/inspections/GoMixedNamedUnnamedParametersInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.progress.ProgressManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoMixedNamedUnnamedParametersInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitMethodDeclaration(@NotNull GoMethodDeclaration o) { super.visitMethodDeclaration(o); visitDeclaration(holder, o.getSignature(), "Method"); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { super.visitFunctionDeclaration(o); visitDeclaration(holder, o.getSignature(), "Function"); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); visitDeclaration(holder, o.getSignature(), "Closure"); } }; } private static void visitDeclaration(@NotNull ProblemsHolder holder, @Nullable GoSignature signature, @NotNull String ownerType) { if (signature == null) return; GoParameters parameters = signature.getParameters(); visitParameterList(holder, parameters, ownerType, "parameters"); GoResult result = signature.getResult(); parameters = result != null ? result.getParameters() : null; visitParameterList(holder, parameters, ownerType, "return parameters"); } private static void visitParameterList(@NotNull ProblemsHolder holder, @Nullable GoParameters parameters, @NotNull String ownerType, @NotNull String what) { if (parameters == null || parameters.getParameterDeclarationList().isEmpty()) return; boolean hasNamed = false; boolean hasUnnamed = false; for (GoParameterDeclaration parameterDeclaration : parameters.getParameterDeclarationList()) { ProgressManager.checkCanceled(); if (parameterDeclaration.getParamDefinitionList().isEmpty()) { hasUnnamed = true; } else { hasNamed = true; } if (hasNamed && hasUnnamed) { holder.registerProblem(parameters, ownerType + " has both named and unnamed " + what + " #ref #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } } } } ================================================ FILE: src/com/goide/inspections/GoMultiplePackagesInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoConstants; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.goide.quickfix.GoMultiplePackagesQuickFix; import com.goide.sdk.GoPackageUtil; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.ide.scratch.ScratchFileType; import com.intellij.psi.PsiDirectory; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GoMultiplePackagesInspection extends GoInspectionBase { @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (((ScratchFileType)ScratchFileType.INSTANCE).isMyFileType(file.getVirtualFile())) return; GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)) return; PsiDirectory dir = file.getContainingDirectory(); Collection packages = GoPackageUtil.getAllPackagesInDirectory(dir, null, true); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { Collection fixes = ContainerUtil.newArrayList(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } } } ================================================ FILE: src/com/goide/inspections/GoNoNewVariablesInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoNoNewVariablesInspection extends GoInspectionBase { public static final String QUICK_FIX_NAME = "Replace with '='"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRecvStatement(@NotNull GoRecvStatement o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } @Override public void visitRangeClause(@NotNull GoRangeClause o) { visitVarDefinitionList(o, o.getVarDefinitionList()); } private void visitVarDefinitionList(@NotNull PsiElement o, @NotNull List list) { GoVarDefinition first = ContainerUtil.getFirstItem(list); GoVarDefinition last = ContainerUtil.getLastItem(list); if (first == null || last == null) return; if (hasNonNewVariables(list)) { TextRange textRange = TextRange.create(first.getStartOffsetInParent(), last.getStartOffsetInParent() + last.getTextLength()); holder.registerProblem(o, textRange, "No new variables on left side of :=", new MyLocalQuickFixBase()); } } }; } public static boolean hasNonNewVariables(@NotNull List list) { if (list.isEmpty()) return false; for (GoVarDefinition def : list) { if (def.isBlank()) continue; PsiReference reference = def.getReference(); if (reference == null || reference.resolve() == null) return false; } return true; } public static void replaceWithAssignment(@NotNull Project project, @NotNull PsiElement element) { if (element instanceof GoShortVarDeclaration) { PsiElement parent = element.getParent(); if (parent instanceof GoSimpleStatement) { String left = GoPsiImplUtil.joinPsiElementText(((GoShortVarDeclaration)element).getVarDefinitionList()); String right = GoPsiImplUtil.joinPsiElementText(((GoShortVarDeclaration)element).getRightExpressionsList()); parent.replace(GoElementFactory.createAssignmentStatement(project, left, right)); } } else if (element instanceof GoRangeClause) { String left = GoPsiImplUtil.joinPsiElementText(((GoRangeClause)element).getVarDefinitionList()); GoExpression rangeExpression = ((GoRangeClause)element).getRangeExpression(); String right = rangeExpression != null ? rangeExpression.getText() : ""; element.replace(GoElementFactory.createRangeClauseAssignment(project, left, right)); } else if (element instanceof GoRecvStatement) { String left = GoPsiImplUtil.joinPsiElementText(((GoRecvStatement)element).getVarDefinitionList()); GoExpression recvExpression = ((GoRecvStatement)element).getRecvExpression(); String right = recvExpression != null ? recvExpression.getText() : ""; element.replace(GoElementFactory.createRecvStatementAssignment(project, left, right)); } } private static class MyLocalQuickFixBase extends LocalQuickFixBase { public MyLocalQuickFixBase() { super(QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if (element.isValid()) { replaceWithAssignment(project, element); } } } } ================================================ FILE: src/com/goide/inspections/GoPlaceholderChecker.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import static com.goide.GoConstants.TESTING_PATH; import static com.goide.inspections.GoPlaceholderChecker.PrintfArgumentType.*; public class GoPlaceholderChecker { // This holds the name of the known formatting functions and position of the string to be formatted private static final Map FORMATTING_FUNCTIONS = ContainerUtil.newHashMap( Pair.pair("errorf", 0), Pair.pair("fatalf", 0), Pair.pair("fprintf", 1), Pair.pair("fscanf", 1), Pair.pair("logf", 0), Pair.pair("panicf", 0), Pair.pair("printf", 0), Pair.pair("scanf", 0), Pair.pair("skipf", 0), Pair.pair("sprintf", 0), Pair.pair("sscanf", 1)); private static final Set PRINTING_FUNCTIONS = ContainerUtil.newHashSet( "error", "error", "fatal", "fprint", "fprintln", "log", "panic", "panicln", "print", "println", "sprint", "sprintln" ); protected enum PrintfArgumentType { ANY(-1), BOOL(1), INT(2), RUNE(3), STRING(4), FLOAT(5), COMPLEX(6), POINTER(7); private int myMask; PrintfArgumentType(int mask) { myMask = mask; } public int getValue() { return myMask; } } enum PrintVerb { Percent('%', "", 0), b('b', " -+.0", INT.getValue() | FLOAT.getValue() | COMPLEX.getValue()), c('c', "-", RUNE.getValue() | INT.getValue()), d('d', " -+.0", INT.getValue()), e('e', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), E('E', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), f('f', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), F('F', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), g('g', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), G('G', " -+.0", FLOAT.getValue() | COMPLEX.getValue()), o('o', " -+.0#", INT.getValue()), p('p', "-#", POINTER.getValue()), q('q', " -+.0#", RUNE.getValue() | INT.getValue() | STRING.getValue()), s('s', " -+.0", STRING.getValue()), t('t', "-", BOOL.getValue()), T('T', "-", ANY.getValue()), U('U', "-#", RUNE.getValue() | INT.getValue()), V('v', " -+.0#", ANY.getValue()), x('x', " -+.0#", RUNE.getValue() | INT.getValue() | STRING.getValue()), X('X', " -+.0#", RUNE.getValue() | INT.getValue() | STRING.getValue()); private char myVerb; private String myFlags; private int myMask; PrintVerb(char verb, String flags, int mask) { myVerb = verb; myFlags = flags; myMask = mask; } public char getVerb() { return myVerb; } @NotNull public String getFlags() { return myFlags; } public int getMask() { return myMask; } @Nullable public static PrintVerb getByVerb(char verb) { for (PrintVerb v : values()) { if (verb == v.getVerb()) return v; } return null; } } public static boolean isFormattingFunction(String functionName) { return FORMATTING_FUNCTIONS.containsKey(functionName); } public static boolean isPrintingFunction(String functionName) { return PRINTING_FUNCTIONS.contains(functionName); } static class Placeholder { private final String placeholder; private final int startPos; private final State state; private final PrintVerb verb; private final List arguments; private final String flags; enum State { OK, MISSING_VERB_AT_END, ARGUMENT_INDEX_NOT_NUMERIC } Placeholder(State state, int startPos, String placeholder, String flags, List arguments, PrintVerb verb) { this.placeholder = placeholder; this.startPos = startPos; this.verb = verb; this.state = state; this.arguments = arguments; this.flags = flags; } public String getPlaceholder() { return placeholder; } public int getPosition() { return arguments.get(arguments.size() - 1); } public State getState() { return state; } public PrintVerb getVerb() { return verb; } public List getArguments() { return arguments; } public String getFlags() { return flags; } public int getStartPos() { return startPos; } } @NotNull public static List parsePrintf(@NotNull String placeholderText) { List placeholders = ContainerUtil.newArrayList(); int argNum = 1; int w; for (int i = 0; i < placeholderText.length(); i += w) { w = 1; if (placeholderText.charAt(i) == '%') { FormatState state = parsePrintfVerb(placeholderText.substring(i), i, argNum); w = state.format.length(); // We are not interested in %% which prints % if (state.state == Placeholder.State.OK && state.verb == PrintVerb.Percent) { // Special magic case for allowing things like %*% to pass (which are sadly valid expressions) if (state.format.length() == 2) continue; } placeholders.add(state.toPlaceholder()); // We only consider ok states as valid to increase the number of arguments. Should we? if (state.state != Placeholder.State.OK) continue; if (!state.indexed) { if (!state.argNums.isEmpty()) { int maxArgNum = Collections.max(state.argNums); if (argNum < maxArgNum) { argNum = maxArgNum; } } } else { argNum = state.argNums.get(state.argNums.size() - 1); } argNum++; } } return placeholders; } protected static int getPlaceholderPosition(@NotNull GoFunctionOrMethodDeclaration function) { Integer position = FORMATTING_FUNCTIONS.get(StringUtil.toLowerCase(function.getName())); if (position != null) { String importPath = function.getContainingFile().getImportPath(false); if ("fmt".equals(importPath) || "log".equals(importPath) || TESTING_PATH.equals(importPath)) { return position; } } return -1; } private static class FormatState { @Nullable private PrintVerb verb; // the format verb: 'd' for "%d" private String format; // the full format directive from % through verb, "%.3d" @NotNull private String flags = ""; // the list of # + etc private boolean indexed; // whether an indexing expression appears: %[1]d private final int startPos; // index of the first character of the placeholder in the formatting string // the successive argument numbers that are consumed, adjusted to refer to actual arg in call private final List argNums = ContainerUtil.newArrayList(); // Keep track of the parser state private Placeholder.State state; // Used only during parse. private int argNum; // Which argument we're expecting to format now private int nBytes = 1; // number of bytes of the format string consumed FormatState(String format, int startPos, int argNum) { this.format = format; this.startPos = startPos; this.argNum = argNum; } @NotNull private Placeholder toPlaceholder() { return new Placeholder(state, startPos, format, flags, argNums, verb); } } @NotNull private static FormatState parsePrintfVerb(@NotNull String format, int startPos, int argNum) { FormatState state = new FormatState(format, startPos, argNum); parseFlags(state); if (!parseIndex(state)) return state; // There may be a width if (!parseNum(state)) return state; if (!parsePrecision(state)) return state; // Now a verb, possibly prefixed by an index (which we may already have) if (!parseIndex(state)) return state; if (state.nBytes == format.length()) { state.state = Placeholder.State.MISSING_VERB_AT_END; return state; } state.verb = PrintVerb.getByVerb(state.format.charAt(state.nBytes)); if (state.verb != null && state.verb != PrintVerb.Percent) state.argNums.add(state.argNum); state.nBytes++; state.format = state.format.substring(0, state.nBytes); state.state = Placeholder.State.OK; return state; } public static boolean hasPlaceholder(@Nullable String formatString) { return formatString != null && StringUtil.containsChar(formatString, '%'); } private static void parseFlags(@NotNull FormatState state) { String knownFlags = "#0+- "; StringBuilder flags = new StringBuilder(state.flags); while (state.nBytes < state.format.length()) { if (StringUtil.containsChar(knownFlags, state.format.charAt(state.nBytes))) { flags.append(state.format.charAt(state.nBytes)); } else { state.flags = flags.toString(); return; } state.nBytes++; } state.flags = flags.toString(); } private static void scanNum(@NotNull FormatState state) { while (state.nBytes < state.format.length()) { if (!StringUtil.isDecimalDigit(state.format.charAt(state.nBytes))) { return; } state.nBytes++; } } private static boolean parseIndex(@NotNull FormatState state) { if (state.nBytes == state.format.length() || state.format.charAt(state.nBytes) != '[') return true; state.indexed = true; state.nBytes++; int start = state.nBytes; scanNum(state); if (state.nBytes == state.format.length() || state.nBytes == start || state.format.charAt(state.nBytes) != ']') { state.state = Placeholder.State.ARGUMENT_INDEX_NOT_NUMERIC; return false; } int arg; try { arg = Integer.parseInt(state.format.substring(start, state.nBytes)); } catch (NumberFormatException ignored) { state.state = Placeholder.State.ARGUMENT_INDEX_NOT_NUMERIC; return false; } state.nBytes++; state.argNum = arg; return true; } private static boolean parseNum(@NotNull FormatState state) { if (state.nBytes < state.format.length() && state.format.charAt(state.nBytes) == '*') { state.nBytes++; state.argNums.add(state.argNum); state.argNum++; } else { scanNum(state); } return true; } private static boolean parsePrecision(@NotNull FormatState state) { if (state.nBytes < state.format.length() && state.format.charAt(state.nBytes) == '.') { state.flags += '.'; state.nBytes++; if (!parseIndex(state)) return false; if (!parseNum(state)) return false; } return true; } } ================================================ FILE: src/com/goide/inspections/GoPlaceholderCountInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.inspections.GoPlaceholderChecker.Placeholder; import com.goide.inspections.GoPlaceholderChecker.PrintVerb; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoPlaceholderCountInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { PsiReference psiReference = o.getExpression().getReference(); PsiElement resolved = psiReference != null ? psiReference.resolve() : null; if (!(resolved instanceof GoFunctionOrMethodDeclaration)) return; String functionName = StringUtil.toLowerCase(((GoFunctionOrMethodDeclaration)resolved).getName()); if (functionName == null) return; if (GoPlaceholderChecker.isFormattingFunction(functionName)) { checkPrintf(holder, o, (GoFunctionOrMethodDeclaration)resolved); } else if (GoPlaceholderChecker.isPrintingFunction(functionName)) { checkPrint(holder, o, (GoFunctionOrMethodDeclaration)resolved); } } }; } private static void checkPrint(@NotNull ProblemsHolder holder, @NotNull GoCallExpr callExpr, @NotNull GoFunctionOrMethodDeclaration declaration) { List arguments = callExpr.getArgumentList().getExpressionList(); GoExpression firstArg = ContainerUtil.getFirstItem(arguments); if (firstArg == null) return; if (GoTypeUtil.isString(firstArg.getGoType(null))) { String firstArgText = resolve(firstArg); if (GoPlaceholderChecker.hasPlaceholder(firstArgText)) { String message = "Possible formatting directive in #ref #loc"; holder.registerProblem(firstArg, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } } // TODO florin: Check first argument for os.Std* output // Ref code: https://github.com/golang/go/blob/79f7ccf2c3931745aeb97c5c985b6ac7b44befb4/src/cmd/vet/print.go#L617 String declarationName = declaration.getName(); boolean isLn = declarationName != null && declarationName.endsWith("ln"); for (GoExpression argument : arguments) { GoType goType = argument.getGoType(null); if (isLn && GoTypeUtil.isString(goType)) { String argText = resolve(argument); if (argText != null && argText.endsWith("\\n")) { String message = "Function already ends with new line #loc"; TextRange range = TextRange.from(argText.length() - 1, 2); // TODO florin: add quickfix to remove trailing \n // TODO florin: add quickfix to convert \n to a separate argument holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); } } else if (GoTypeUtil.isFunction(goType)) { String message = argument instanceof GoCallExpr ? "Final return type of #ref is a function not a function call #loc" : "Argument #ref is not a function call #loc"; // TODO florin: add quickfix to convert to function call if possible holder.registerProblem(argument, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } } private static void checkPrintf(@NotNull ProblemsHolder holder, @NotNull GoCallExpr callExpr, @NotNull GoFunctionOrMethodDeclaration declaration) { int placeholderPosition = GoPlaceholderChecker.getPlaceholderPosition(declaration); List arguments = callExpr.getArgumentList().getExpressionList(); if (arguments.isEmpty()) return; int callArgsNum = arguments.size(); if (placeholderPosition < 0 || callArgsNum <= placeholderPosition) return; GoExpression placeholder = arguments.get(placeholderPosition); if (!GoTypeUtil.isString(placeholder.getGoType(null))) { String message = "Value used for formatting text does not appear to be a string #loc"; holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } String placeholderText = resolve(placeholder); if (placeholderText == null) return; if (!GoPlaceholderChecker.hasPlaceholder(placeholderText) && callArgsNum > placeholderPosition) { String message = "Value used for formatting text does not appear to contain a placeholder #loc"; holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } callArgsNum--; List placeholders = GoPlaceholderChecker.parsePrintf(placeholderText); for (Placeholder fmtPlaceholder : placeholders) { if (!checkPrintfArgument(holder, placeholder, callExpr, arguments, callArgsNum, placeholderPosition, fmtPlaceholder)) return; } if (hasErrors(holder, placeholder, placeholders)) return; // TODO florin check to see if we are skipping any argument from the formatting string int maxArgsNum = computeMaxArgsNum(placeholders, placeholderPosition); if (GoPsiImplUtil.hasVariadic(callExpr.getArgumentList()) && maxArgsNum >= callArgsNum) { return; } if (maxArgsNum != callArgsNum) { int expect = maxArgsNum - placeholderPosition; int numArgs = callArgsNum - placeholderPosition; String message = String.format("Got %d placeholder(s) for %d arguments(s) #loc", expect, numArgs); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } // TODO florin: check if all arguments are strings and add quickfix to replace with Println and string concat } private static int computeMaxArgsNum(@NotNull List placeholders, int firstArg) { int maxArgsNum = 0; for (Placeholder placeholder : placeholders) { List arguments = placeholder.getArguments(); if (!arguments.isEmpty()) { int max = Collections.max(arguments); if (maxArgsNum < max) { maxArgsNum = max; } } } return maxArgsNum + firstArg; } private static boolean hasErrors(@NotNull ProblemsHolder holder, @NotNull GoExpression formatPlaceholder, @NotNull List placeholders) { for (Placeholder placeholder : placeholders) { Placeholder.State state = placeholder.getState(); if (state == Placeholder.State.MISSING_VERB_AT_END) { String message = "Missing verb at end of format string in #ref call #loc"; holder.registerProblem(formatPlaceholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return true; } if (state == Placeholder.State.ARGUMENT_INDEX_NOT_NUMERIC) { String message = "Illegal syntax for #ref argument index, expecting a number #loc"; holder.registerProblem(formatPlaceholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return true; } } return false; } private static boolean checkPrintfArgument(@NotNull ProblemsHolder holder, @NotNull GoExpression placeholder, @NotNull GoCallExpr callExpr, @NotNull List arguments, int callArgsNum, int firstArg, @NotNull Placeholder fmtPlaceholder) { PrintVerb v = fmtPlaceholder.getVerb(); if (v == null) { String message = "Unrecognized formatting verb #ref call #loc"; TextRange range = TextRange.from(fmtPlaceholder.getStartPos() + 1, fmtPlaceholder.getPlaceholder().length()); // TODO florin: add quickfix to suggest correct printf verbs (maybe take type into account when type info available?) holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); return false; } String flags = fmtPlaceholder.getFlags(); for (int i = 0; i < flags.length(); i++) { char flag = flags.charAt(i); if (v.getFlags().indexOf(flag) == -1) { String message = String.format("Unrecognized #ref flag for verb %s: %s call #loc", v.getVerb(), flag); TextRange range = TextRange.from(fmtPlaceholder.getStartPos() + 1, fmtPlaceholder.getPlaceholder().length()); // TODO florin: add quickfix to suggest correct printf verbs (maybe take type into account when type info available?) // TODO florin: cover with tests holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); return false; } } List args = fmtPlaceholder.getArguments(); // Verb is good. If len(state.argNums)>trueArgs, we have something like %.*s and all // but the final arg must be an integer. int trueArgs = v == PrintVerb.Percent ? 0 : 1; int nargs = args.size(); for (int i = 0; i < nargs - trueArgs; i++) { if (!checkArgumentIndex(holder, placeholder, callExpr, fmtPlaceholder, callArgsNum)) return false; // TODO florin: add argument matching when type comparison can be done // Ref code: https://github.com/golang/go/blob/79f7ccf2c3931745aeb97c5c985b6ac7b44befb4/src/cmd/vet/print.go#L484 } if (v == PrintVerb.Percent) return true; if (!checkArgumentIndex(holder, placeholder, callExpr, fmtPlaceholder, callArgsNum)) return false; int argNum = args.get(args.size() - 1); GoExpression expression = arguments.get(argNum + firstArg - 1); if (GoTypeUtil.isFunction(expression.getGoType(null)) && v != PrintVerb.p && v != PrintVerb.T) { String message = "Argument #ref is not a function call #loc"; if (expression instanceof GoCallExpr) { message = "Final return type of #ref is a function not a function call #loc"; } // TODO florin: add quickfix for this to transform it into a function call holder.registerProblem(expression, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return false; } // TODO florin: add argument matching when type comparison can be done // Ref code: https://github.com/golang/go/blob/79f7ccf2c3931745aeb97c5c985b6ac7b44befb4/src/cmd/vet/print.go#L502 return true; } private static boolean checkArgumentIndex(@NotNull ProblemsHolder holder, @NotNull GoExpression placeholder, @NotNull GoCallExpr callExpr, @NotNull Placeholder fmtPlaceholder, int callArgsNum) { int argNum = fmtPlaceholder.getPosition(); if (argNum < 0) return false; if (argNum == 0) { TextRange range = TextRange.create(fmtPlaceholder.getStartPos() + 3, fmtPlaceholder.getStartPos() + 4); // TODO florin: add quickfix to suggest placeholder value holder.registerProblem(placeholder, "Index value [0] is not allowed #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, range); return false; } if (argNum < callArgsNum) return true; if (GoPsiImplUtil.hasVariadic(callExpr.getArgumentList())) return false; if (argNum == callArgsNum) return true; // There are bad indexes in the format or there are fewer arguments than the format needs // This is the argument number relative to the format: Printf("%s", "hi") will give 1 for the "hi" int arg = fmtPlaceholder.getPosition(); String message = String.format("Got %d placeholder(s) for %d arguments(s)", arg, callArgsNum); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return false; } @Nullable private static String resolve(@NotNull GoExpression argument) { String argumentValue = getValue(argument); if (argumentValue != null) { return argumentValue; } PsiReference reference = argument.getReference(); PsiElement resolved = reference != null ? reference.resolve() : null; String value = null; if (resolved instanceof GoVarDefinition) { value = getValue(((GoVarDefinition)resolved).getValue()); } else if (resolved instanceof GoConstDefinition) { value = getValue(((GoConstDefinition)resolved).getValue()); } return value; } // todo: implement ConstEvaluator @Nullable private static String getValue(@Nullable GoExpression expression) { if (expression instanceof GoStringLiteral) { return ElementManipulators.getValueText(expression); } if (expression instanceof GoAddExpr) { StringBuilder result = new StringBuilder(); for (GoExpression expr : ((GoAddExpr)expression).getExpressionList()) { String value = getValue(expr); if (value == null) return null; result.append(value); } return StringUtil.nullize(result.toString()); } if (expression instanceof GoParenthesesExpr) { return getValue(((GoParenthesesExpr)expression).getExpression()); } return null; }} ================================================ FILE: src/com/goide/inspections/GoRangeIterationOnIllegalTypeInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoExpression; import com.goide.psi.GoRangeClause; import com.goide.psi.GoType; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoRangeIterationOnIllegalTypeInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitRangeClause(@NotNull GoRangeClause o) { super.visitRangeClause(o); GoExpression expression = o.getRangeExpression(); GoType type = expression != null ? expression.getGoType(null) : null; if (type != null && !GoTypeUtil.isIterable(type)) { holder.registerProblem(expression, "Cannot range over data (type " + GoPsiImplUtil.getText(type) + ")", ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; } } ================================================ FILE: src/com/goide/inspections/GoReceiverNamesInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoReceiver; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoRenameQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Set; public class GoReceiverNamesInspection extends GoInspectionBase { private static final Set genericNamesSet = ContainerUtil.newHashSet("me", "this", "self"); @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitReceiver(@NotNull GoReceiver o) { if (genericNamesSet.contains(o.getName())) { PsiElement identifier = o.getIdentifier(); if (identifier == null) return; holder.registerProblem(identifier, "Receiver has generic name", new GoRenameQuickFix(o)); } } }; } } ================================================ FILE: src/com/goide/inspections/GoRedeclareImportAsFunctionInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoRenameQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; public class GoRedeclareImportAsFunctionInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { String functionName = o.getName(); if (StringUtil.isNotEmpty(functionName) && !"_".equals(functionName) && o.getContainingFile().getImportMap().containsKey(functionName)) { holder.registerProblem(o.getIdentifier(), "import \"" + functionName + "\" redeclared in this block", new GoRenameQuickFix(o)); } } }; } } ================================================ FILE: src/com/goide/inspections/GoRedundantBlankArgInRangeInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.quickfix.GoDeleteRangeQuickFix; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class GoRedundantBlankArgInRangeInspection extends GoInspectionBase implements CleanupLocalInspectionTool { public final static String DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME = "Delete blank argument"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitRangeClause(@NotNull GoRangeClause o) { List leftExpressions = o.getLeftExpressionsList(); PsiElement range = o.getRange(); if (range == null) return; if (leftExpressions.size() == 2 && isBlankGoReferenceExpression(leftExpressions.get(1))) { if (isBlankGoReferenceExpression(leftExpressions.get(0))) { registerBlankArgumentProblem(holder, leftExpressions.get(0), range.getPrevSibling()); } else if (leftExpressions.get(0).getNextSibling() != null) { registerBlankArgumentProblem(holder, leftExpressions.get(0).getNextSibling(), leftExpressions.get(1)); } } else if (leftExpressions.size() == 1 && isBlankGoReferenceExpression(leftExpressions.get(0))) { registerBlankArgumentProblem(holder, leftExpressions.get(0), range.getPrevSibling()); } List leftDefinitions = o.getVarDefinitionList(); if (leftDefinitions.size() == 2 && isBlankGoVarDefinition(leftDefinitions.get(1))) { registerBlankArgumentProblem(holder, leftDefinitions.get(0).getNextSibling(), leftDefinitions.get(1)); } } }; } private static void registerBlankArgumentProblem(@NotNull ProblemsHolder holder, @NotNull PsiElement start, @NotNull PsiElement end) { GoDeleteRangeQuickFix fix = new GoDeleteRangeQuickFix(start, end, DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME); holder.registerProblem(holder.getManager().createProblemDescriptor(start, end, "Redundant _ expression", ProblemHighlightType.LIKE_UNUSED_SYMBOL, holder.isOnTheFly(), fix)); } private static boolean isBlankGoVarDefinition(@Nullable PsiElement o) { return o instanceof GoVarDefinition && o.textMatches("_"); } private static boolean isBlankGoReferenceExpression(@Nullable PsiElement o) { return o instanceof GoReferenceExpression && o.textMatches("_"); } } ================================================ FILE: src/com/goide/inspections/GoRedundantSecondIndexInSlicesInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.quickfix.GoDeleteQuickFix; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.Trinity; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoRedundantSecondIndexInSlicesInspection extends GoInspectionBase implements CleanupLocalInspectionTool { public final static String DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME = "Delete redundant index"; private static final GoDeleteQuickFix DELETE_REDUNDANT_INDEX_QUICK_FIX = new GoDeleteQuickFix(DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, GoCallExpr.class); @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitIndexOrSliceExpr(@NotNull GoIndexOrSliceExpr o) { GoExpression expression = o.getExpression(); PsiReference reference = expression != null ? expression.getReference() : null; PsiElement resolvedArrayReference = reference != null ? reference.resolve() : null; if (reference == null || resolvedArrayReference == null || !(expression instanceof GoReferenceExpression) || ((GoReferenceExpression)expression).getQualifier() != null) { return; } Trinity indexes = o.getIndices(); if (indexes.third == null && indexes.second instanceof GoCallExpr) { GoCallExpr call = (GoCallExpr)indexes.second; if (isLenFunctionCall(call)) { GoExpression argument = ContainerUtil.getFirstItem(call.getArgumentList().getExpressionList()); if (argument != null && argument.getReference() != null && resolvedArrayReference.equals(argument.getReference().resolve())) { holder.registerProblem(call, "Redundant index", ProblemHighlightType.LIKE_UNUSED_SYMBOL, DELETE_REDUNDANT_INDEX_QUICK_FIX); } } } } }; } private static boolean isLenFunctionCall(@NotNull GoCallExpr callExpr) { GoExpression functionReferenceExpression = callExpr.getExpression(); if (!(functionReferenceExpression instanceof GoReferenceExpression) || !functionReferenceExpression.textMatches("len")) { return false; } List callArguments = callExpr.getArgumentList().getExpressionList(); if (callArguments.size() != 1) { return false; } return GoPsiImplUtil.builtin(((GoReferenceExpression)functionReferenceExpression).resolve()); } } ================================================ FILE: src/com/goide/inspections/GoRedundantTypeDeclInCompositeLit.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.quickfix.GoDeleteAmpersandAndTypeInCompositeLitQuickFix; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoRedundantTypeDeclInCompositeLit extends GoInspectionBase implements CleanupLocalInspectionTool { public final static String DELETE_TYPE_DECLARATION_QUICK_FIX_NAME = "Delete redundant type declaration"; private static final GoDeleteAmpersandAndTypeInCompositeLitQuickFix QUICK_FIX = new GoDeleteAmpersandAndTypeInCompositeLitQuickFix(); @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCompositeLit(@NotNull GoCompositeLit o) { GoLiteralValue literalValue = o.getLiteralValue(); if (literalValue == null) return; GoType expectedType = getExpectedType(o); // TODO o.getType() instanceof GoStruct (struct or T[][]) if (expectedType != null) { for (GoElement element : literalValue.getElementList()) { GoValue elementValue = element.getValue(); if (elementValue != null) { GoExpression expr = elementValue.getExpression(); if (expectedType instanceof GoPointerType && expr instanceof GoUnaryExpr) { GoUnaryExpr unaryExpr = (GoUnaryExpr)expr; PsiElement bitAnd = unaryExpr.getBitAnd(); if (bitAnd != null && unaryExpr.getExpression() instanceof GoCompositeLit) { GoCompositeLit compositeLit = (GoCompositeLit)unaryExpr.getExpression(); if (isTypeReferencesEquals(((GoPointerType)expectedType).getType(), compositeLit)) { GoTypeReferenceExpression typeExpr = compositeLit.getTypeReferenceExpression(); if (typeExpr != null) { holder.registerProblem(holder.getManager().createProblemDescriptor(bitAnd, typeExpr, "Redundant type declaration", ProblemHighlightType.LIKE_UNUSED_SYMBOL, holder.isOnTheFly(), QUICK_FIX)); } } } } else if (expr instanceof GoCompositeLit && isTypeReferencesEquals(expectedType, (GoCompositeLit)expr)) { GoTypeReferenceExpression typeExpr = ((GoCompositeLit)expr).getTypeReferenceExpression(); if (typeExpr != null) { holder.registerProblem(typeExpr, "Redundant type declaration", ProblemHighlightType.LIKE_UNUSED_SYMBOL, QUICK_FIX); } } } } } } }; } @Nullable private static GoType getExpectedType(@NotNull GoCompositeLit o) { if (o.getType() instanceof GoArrayOrSliceType && ((GoArrayOrSliceType)o.getType()).getType() != null) { return ((GoArrayOrSliceType)o.getType()).getType(); } if (o.getType() instanceof GoMapType && ((GoMapType)o.getType()).getValueType() != null) { return ((GoMapType)o.getType()).getValueType(); } return null; } private static boolean isTypeReferencesEquals(@Nullable GoType pattern, @NotNull GoCompositeLit value) { if (pattern == null || !pattern.isValid() || !value.isValid()) { return false; } if (pattern.getTypeReferenceExpression() == null || value.getTypeReferenceExpression() == null) { return false; } if (pattern.getTypeReferenceExpression().resolve() != value.getTypeReferenceExpression().resolve()) { return false; } //TODO Complex type comparison return true; } } ================================================ FILE: src/com/goide/inspections/GoReservedWordUsedAsNameInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoTypeReference; import com.goide.quickfix.GoRenameQuickFix; import com.goide.sdk.GoSdkUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageViewTypeLocation; import org.jetbrains.annotations.NotNull; public class GoReservedWordUsedAsNameInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { GoFile builtinFile = GoSdkUtil.findBuiltinFile(session.getFile()); if (builtinFile == null) return DUMMY_VISITOR; return new GoVisitor() { @Override public void visitTypeSpec(@NotNull GoTypeSpec o) { super.visitTypeSpec(o); check(o, builtinFile, holder); } @Override public void visitConstDefinition(@NotNull GoConstDefinition o) { super.visitConstDefinition(o); check(o, builtinFile, holder); } @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { super.visitFunctionOrMethodDeclaration(o); check(o, builtinFile, holder); } @Override public void visitVarDefinition(@NotNull GoVarDefinition o) { super.visitVarDefinition(o); check(o, builtinFile, holder); } }; } private static void check(@NotNull GoNamedElement element, @NotNull GoFile builtinFile, @NotNull ProblemsHolder holder) { String name = element.getName(); if (name == null || GoTypeReference.DOC_ONLY_TYPES.contains(name)) return; for (GoTypeSpec builtinTypeDeclaration : builtinFile.getTypes()) { if (name.equals(builtinTypeDeclaration.getName())) { registerProblem(holder, element, builtinTypeDeclaration); return; } } ProgressManager.checkCanceled(); for (GoFunctionDeclaration builtinFunctionsDeclaration : builtinFile.getFunctions()) { if (name.equals(builtinFunctionsDeclaration.getName())) { registerProblem(holder, element, builtinFunctionsDeclaration); return; } } } private static void registerProblem(@NotNull ProblemsHolder holder, @NotNull GoNamedElement element, @NotNull GoNamedElement builtinElement) { PsiElement identifier = element.getIdentifier(); if (identifier == null) return; String elementDescription = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE); String builtinElementDescription = ElementDescriptionUtil.getElementDescription(builtinElement, UsageViewTypeLocation.INSTANCE); String message = StringUtil.capitalize(elementDescription) + " #ref collides with builtin " + builtinElementDescription; holder.registerProblem(identifier, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoRenameQuickFix(element)); } } ================================================ FILE: src/com/goide/inspections/GoSelfImportInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.NotNull; public class GoSelfImportInspection extends GoInspectionBase { @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (GoTestFinder.isTestFileWithTestPackage(file)) return; PsiDirectory directory = file.getContainingDirectory(); if (directory != null) { for (GoImportSpec importSpec : file.getImports()) { PsiDirectory resolve = importSpec.getImportString().resolve(); if (directory.equals(resolve)) { problemsHolder.registerProblem(importSpec, "Self import is not allowed", new GoDeleteImportQuickFix()); } } } } } ================================================ FILE: src/com/goide/inspections/GoSpellcheckingStrategy.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoLanguage; import com.intellij.psi.PsiElement; import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy; import org.jetbrains.annotations.NotNull; public class GoSpellcheckingStrategy extends SpellcheckingStrategy { @Override public boolean isMyContext(@NotNull PsiElement element) { return GoLanguage.INSTANCE.is(element.getLanguage()); } } ================================================ FILE: src/com/goide/inspections/GoStringAndByteTypeMismatchInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.goide.quickfix.GoConvertStringToByteQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.Trinity; import com.intellij.psi.tree.TokenSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; public class GoStringAndByteTypeMismatchInspection extends GoInspectionBase { private static final String TEXT_HINT = "Mismatched types: byte and string"; private static final GoConvertStringToByteQuickFix STRING_INDEX_IS_BYTE_QUICK_FIX = new GoConvertStringToByteQuickFix(); @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitConditionalExpr(@NotNull GoConditionalExpr o) { GoExpression left = o.getLeft(); GoExpression right = o.getRight(); GoIndexOrSliceExpr indexExpr = ContainerUtil.findInstance(Arrays.asList(left, right), GoIndexOrSliceExpr.class); GoStringLiteral stringLiteral = ContainerUtil.findInstance(Arrays.asList(left, right), GoStringLiteral.class); if (indexExpr == null || stringLiteral == null) { return; } if (isStringIndexExpression(indexExpr)) { LocalQuickFix[] fixes = GoPsiImplUtil.isSingleCharLiteral(stringLiteral) ? new LocalQuickFix[]{STRING_INDEX_IS_BYTE_QUICK_FIX} : LocalQuickFix.EMPTY_ARRAY; holder.registerProblem(o, TEXT_HINT, ProblemHighlightType.GENERIC_ERROR, fixes); } } }; } private static boolean isStringIndexExpression(@NotNull GoIndexOrSliceExpr expr) { GoExpression expression = expr.getExpression(); if (expression == null || !GoTypeUtil.isString(expression.getGoType(null))) { return false; } Trinity indices = expr.getIndices(); return indices.getSecond() == null && indices.getThird() == null && expr.getNode().getChildren(TokenSet.create(GoTypes.COLON)).length == 0; } } ================================================ FILE: src/com/goide/inspections/GoStructInitializationInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.util.GoUtil; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public class GoStructInitializationInspection extends GoInspectionBase { public static final String REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME = "Replace with named struct field"; public boolean reportLocalStructs; /** * @deprecated use reportLocalStructs */ @SuppressWarnings("WeakerAccess") public Boolean reportImportedStructs; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitLiteralValue(@NotNull GoLiteralValue o) { if (PsiTreeUtil.getParentOfType(o, GoReturnStatement.class, GoShortVarDeclaration.class, GoAssignmentStatement.class) == null) { return; } PsiElement parent = o.getParent(); GoType refType = GoPsiImplUtil.getLiteralType(parent, false); if (refType instanceof GoStructType) { processStructType(holder, o, (GoStructType)refType); } } }; } @Override public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel("Report for local type definitions as well", this, "reportLocalStructs"); } private void processStructType(@NotNull ProblemsHolder holder, @NotNull GoLiteralValue element, @NotNull GoStructType structType) { if (reportLocalStructs || !GoUtil.inSamePackage(structType.getContainingFile(), element.getContainingFile())) { processLiteralValue(holder, element, structType.getFieldDeclarationList()); } } private static void processLiteralValue(@NotNull ProblemsHolder holder, @NotNull GoLiteralValue o, @NotNull List fields) { List vals = o.getElementList(); for (int elemId = 0; elemId < vals.size(); elemId++) { ProgressManager.checkCanceled(); GoElement element = vals.get(elemId); if (element.getKey() == null && elemId < fields.size()) { String structFieldName = getFieldName(fields.get(elemId)); LocalQuickFix[] fixes = structFieldName != null ? new LocalQuickFix[]{new GoReplaceWithNamedStructFieldQuickFix(structFieldName)} : LocalQuickFix.EMPTY_ARRAY; holder.registerProblem(element, "Unnamed field initialization", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fixes); } } } @Nullable private static String getFieldName(@NotNull GoFieldDeclaration declaration) { List list = declaration.getFieldDefinitionList(); GoFieldDefinition fieldDefinition = ContainerUtil.getFirstItem(list); return fieldDefinition != null ? fieldDefinition.getIdentifier().getText() : null; } private static class GoReplaceWithNamedStructFieldQuickFix extends LocalQuickFixBase { private String myStructField; public GoReplaceWithNamedStructFieldQuickFix(@NotNull String structField) { super(REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME); myStructField = structField; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement startElement = descriptor.getStartElement(); if (startElement instanceof GoElement) { startElement.replace(GoElementFactory.createLiteralValueElement(project, myStructField, startElement.getText())); } } } @Override public void readSettings(@NotNull Element node) throws InvalidDataException { super.readSettings(node); if (reportImportedStructs != null) { reportLocalStructs = reportImportedStructs; } } @Override public void writeSettings(@NotNull Element node) throws WriteExternalException { reportImportedStructs = null; super.writeSettings(node); } } ================================================ FILE: src/com/goide/inspections/GoStructTagInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoFieldDeclaration; import com.goide.psi.GoStructType; import com.goide.psi.GoTag; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; /** * Implements , an * inspector that warns if a go StructTag is not well-formed according to Go language conventions. */ public class GoStructTagInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitStructType(@NotNull GoStructType o) { for (GoFieldDeclaration field : o.getFieldDeclarationList()) { GoTag tag = field.getTag(); if (tag == null) continue; if (!isValidTag(tag)) { holder.registerProblem(tag, "Bad syntax for struct tag value"); } } } }; } // Implementation based on validateStructTag from the go vet tool: // https://github.com/golang/tools/blob/master/cmd/vet/structtag.go. private static boolean isValidTag(@NotNull GoTag tag) { StringBuilder tagText = new StringBuilder(GoPsiImplUtil.unquote(tag.getText())); if (tagText.length() != tag.getText().length() - 2) { // We already have a parsing error in this case, so no need to add an additional warning. return true; } while (tagText.length() > 0) { int i = 0; // Skip leading spaces. while (i < tagText.length() && tagText.charAt(i) == ' ') { i++; } tagText.delete(0, i); if (tagText.length() == 0) return true; // Scan to colon. A space, a quote or a control character is a syntax error. // Strictly speaking, control chars include the range [0x7f, 0x9f], not just // [0x00, 0x1f], but in practice, we ignore the multi-byte control characters // as it is simpler to inspect the tag's bytes than the tag's runes. i = 0; while (i < tagText.length() && tagText.charAt(i) > ' ' && tagText.charAt(i) != ':' && tagText.charAt(i) != '"' && tagText.charAt(i) != 0x7f) { i++; } if (i == 0 || i + 1 > tagText.length() || tagText.charAt(i) != ':') return false; tagText.delete(0, i + 1); // Scan quoted string to find value. i = 1; while (i < tagText.length() && tagText.charAt(i) != '"') { if (tagText.charAt(i) == '\\') { i++; } i++; } if (i >= tagText.length()) return false; String unquotedValue = GoPsiImplUtil.unquote(tagText.substring(0, i + 1)); if (unquotedValue.length() != i - 1) { // The value was not correctly quoted (two quote chars were not removed by unquote). // TODO(sjr): this check is not equivalent to strconv.Unquote, so this inspector is // more lenient than the go vet tool. return false; } tagText.delete(0, i + 1); } return true; } } ================================================ FILE: src/com/goide/inspections/GoTestSignaturesInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoConstants; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestFunctionType; import com.goide.runconfig.testing.frameworks.gotest.GotestGenerateAction; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoTestSignaturesInspection extends GoInspectionBase { @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoTestFinder.isTestFile(file)) return; for (GoFunctionDeclaration function : file.getFunctions()) { GoTestFunctionType type = GoTestFunctionType.fromName(function.getName()); if (type == null) continue; GoSignature signature = function.getSignature(); if (signature == null) continue; List params = signature.getParameters().getParameterDeclarationList(); if (type == GoTestFunctionType.EXAMPLE) { if (!params.isEmpty() || signature.getResult() != null) { problemsHolder.registerProblem(function.getIdentifier(), "Wrong example signature", new GoTestSignaturesQuickFix(type)); } } else { GoParameterDeclaration param = ContainerUtil.getFirstItem(params); GoImportSpec testingImportSpec = file.getImportedPackagesMap().get(GoConstants.TESTING_PATH); String testingAlias = GoPsiImplUtil.getImportQualifierToUseInFile(testingImportSpec, GoConstants.TESTING_PATH); if (GoConstants.TESTING_PATH.equals(file.getImportPath(false))) { testingAlias = ""; } if (signature.getResult() != null || testingAlias == null || params.size() != 1 || param == null || !param.getType().textMatches(type.getQualifiedParamType(testingAlias))) { problemsHolder.registerProblem(function.getIdentifier(), "Wrong test signature", new GoTestSignaturesQuickFix(type)); } } } } private static class GoTestSignaturesQuickFix extends LocalQuickFixBase { private final GoTestFunctionType myType; public GoTestSignaturesQuickFix(GoTestFunctionType type) { super("Fix signature"); myType = type; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if (element == null) return; GoFunctionDeclaration function = ObjectUtils.tryCast(element.getParent(), GoFunctionDeclaration.class); GoSignature signature = function != null ? function.getSignature() : null; if (signature == null) return; GoFile file = ObjectUtils.tryCast(signature.getContainingFile(), GoFile.class); if (file == null) return; String testingQualifier = GotestGenerateAction.importTestingPackageIfNeeded(file); signature.replace(GoElementFactory.createFunctionSignatureFromText(project, myType.getSignature(testingQualifier))); } } } ================================================ FILE: src/com/goide/inspections/GoUnderscoreUsedAsValueInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoReferenceExpression; import com.goide.psi.GoVisitor; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; public class GoUnderscoreUsedAsValueInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitReferenceExpression(@NotNull GoReferenceExpression o) { super.visitReferenceExpression(o); if (o.getIdentifier().textMatches("_") && o.getReadWriteAccess() != ReadWriteAccessDetector.Access.Write) { holder.registerProblem(o, "Cannot use #ref as value #loc", ProblemHighlightType.ERROR); } } }; } } ================================================ FILE: src/com/goide/inspections/GoUnusedImportInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.codeInsight.imports.GoImportOptimizer; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.psi.GoRecursiveVisitor; import com.goide.psi.impl.GoElementFactory; import com.goide.quickfix.GoRenameQuickFix; import com.intellij.codeInspection.*; import com.intellij.find.FindManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; public class GoUnusedImportInspection extends GoInspectionBase { @Nullable private final static LocalQuickFix OPTIMIZE_QUICK_FIX = new LocalQuickFixBase("Optimize imports") { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element == null) { return; } PsiFile file = element.getContainingFile(); WriteCommandAction.runWriteCommandAction(project, new GoImportOptimizer().processFile(file)); } }; @Nullable private final static LocalQuickFix IMPORT_FOR_SIDE_EFFECTS_QUICK_FIX = new LocalQuickFixBase("Import for side-effects") { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (!(element instanceof GoImportSpec)) { return; } element.replace(GoElementFactory.createImportSpec(project, ((GoImportSpec)element).getPath(), "_")); } }; private static void resolveAllReferences(@NotNull GoFile file) { file.accept(new GoRecursiveVisitor() { @Override public void visitElement(@NotNull PsiElement o) { for (PsiReference reference : o.getReferences()) { reference.resolve(); } } }); } @Override protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { MultiMap importMap = file.getImportMap(); for (PsiElement importIdentifier : GoImportOptimizer.findRedundantImportIdentifiers(importMap)) { problemsHolder.registerProblem(importIdentifier, "Redundant alias", ProblemHighlightType.LIKE_UNUSED_SYMBOL, OPTIMIZE_QUICK_FIX); } Set duplicatedEntries = GoImportOptimizer.findDuplicatedEntries(importMap); for (GoImportSpec duplicatedImportSpec : duplicatedEntries) { problemsHolder.registerProblem(duplicatedImportSpec, "Redeclared import", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX); } for (Map.Entry> specs : importMap.entrySet()) { Iterator imports = specs.getValue().iterator(); GoImportSpec originalImport = imports.next(); if (originalImport.isDot() || originalImport.isForSideEffects()) { continue; } while (imports.hasNext()) { GoImportSpec redeclaredImport = imports.next(); if (!duplicatedEntries.contains(redeclaredImport)) { LocalQuickFix[] quickFixes = FindManager.getInstance(redeclaredImport.getProject()).canFindUsages(redeclaredImport) ? new LocalQuickFix[]{new GoRenameQuickFix(redeclaredImport)} : LocalQuickFix.EMPTY_ARRAY; problemsHolder.registerProblem(redeclaredImport, "Redeclared import", ProblemHighlightType.GENERIC_ERROR, quickFixes); } } } if (importMap.containsKey(".")) { if (!problemsHolder.isOnTheFly() || ApplicationManager.getApplication().isUnitTestMode()) resolveAllReferences(file); } MultiMap unusedImportsMap = GoImportOptimizer.filterUnusedImports(file, importMap); Set unusedImportSpecs = ContainerUtil.newHashSet(unusedImportsMap.values()); for (PsiElement importEntry : unusedImportSpecs) { GoImportSpec spec = GoImportOptimizer.getImportSpec(importEntry); if (spec != null && spec.getImportString().resolve() != null) { problemsHolder.registerProblem(spec, "Unused import", ProblemHighlightType.GENERIC_ERROR, OPTIMIZE_QUICK_FIX, IMPORT_FOR_SIDE_EFFECTS_QUICK_FIX); } } } } ================================================ FILE: src/com/goide/inspections/GoUsedAsValueInCondition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.GoAssignmentStatement; import com.goide.psi.GoIfStatement; import com.goide.psi.GoShortVarDeclaration; import com.goide.psi.GoVisitor; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; public class GoUsedAsValueInCondition extends GoInspectionBase { public static final String QUICK_FIX_NAME = "Convert to '==''"; @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitAssignmentStatement(@NotNull GoAssignmentStatement o) { if (o.getParent() != null && o.getParent() instanceof GoIfStatement && ((GoIfStatement)o.getParent()).getExpression() == null) { String left = GoPsiImplUtil.joinPsiElementText(o.getLeftHandExprList().getExpressionList()); String right = GoPsiImplUtil.joinPsiElementText(o.getExpressionList()); holder.registerProblem(o, left + " = " + right + " used as value", GENERIC_ERROR_OR_WARNING, new GoAssignmentToComparisonQuickFix()); } } @Override public void visitShortVarDeclaration(@NotNull GoShortVarDeclaration o) { PsiElement parent = o.getParent(); if (parent != null) { PsiElement gradParent = parent.getParent(); if (gradParent instanceof GoIfStatement && ((GoIfStatement)gradParent).getExpression() == null) { String left = GoPsiImplUtil.joinPsiElementText(o.getVarDefinitionList()); String right = GoPsiImplUtil.joinPsiElementText(o.getRightExpressionsList()); holder.registerProblem(o, left + " := " + right + " used as value", GENERIC_ERROR_OR_WARNING, new GoAssignmentToComparisonQuickFix()); } } } }; } private static class GoAssignmentToComparisonQuickFix extends LocalQuickFixBase { private GoAssignmentToComparisonQuickFix() { super(QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element instanceof GoAssignmentStatement) { String left = GoPsiImplUtil.joinPsiElementText(((GoAssignmentStatement)element).getLeftHandExprList().getExpressionList()); String right = GoPsiImplUtil.joinPsiElementText(((GoAssignmentStatement)element).getExpressionList()); element.replace(GoElementFactory.createExpression(project, left + " == " + right)); } else if (element instanceof GoShortVarDeclaration) { String left = GoPsiImplUtil.joinPsiElementText(((GoShortVarDeclaration)element).getVarDefinitionList()); String right = GoPsiImplUtil.joinPsiElementText(((GoShortVarDeclaration)element).getRightExpressionsList()); element.replace(GoElementFactory.createComparison(project, left + " == " + right)); } } } } ================================================ FILE: src/com/goide/inspections/GoVarDeclarationInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; import static com.goide.inspections.GoInspectionUtil.UNKNOWN_COUNT; import static com.goide.inspections.GoInspectionUtil.getExpressionResultCount; public class GoVarDeclarationInspection extends GoInspectionBase { @NotNull private static Pair, List> getPair(@NotNull GoVarSpec varDeclaration) { PsiElement assign = varDeclaration instanceof GoShortVarDeclaration ? ((GoShortVarDeclaration)varDeclaration).getVarAssign() : varDeclaration.getAssign(); if (assign == null) { return Pair.create(ContainerUtil.emptyList(), ContainerUtil.emptyList()); } if (varDeclaration instanceof GoRecvStatement) { return Pair.create(((GoRecvStatement)varDeclaration).getLeftExpressionsList(), varDeclaration.getRightExpressionsList()); } if (varDeclaration instanceof GoRangeClause) { return Pair.create(((GoRangeClause)varDeclaration).getLeftExpressionsList(), varDeclaration.getRightExpressionsList()); } return Pair.create(varDeclaration.getVarDefinitionList(), varDeclaration.getRightExpressionsList()); } @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitAssignmentStatement(@NotNull GoAssignmentStatement o) { validatePair(o, Pair.create(o.getLeftHandExprList().getExpressionList(), o.getExpressionList())); } @Override public void visitVarSpec(@NotNull GoVarSpec o) { validatePair(o, getPair(o)); } private void validatePair(@NotNull GoCompositeElement o, Pair, List> p) { List list = p.second; int idCount = p.first.size(); for (GoCompositeElement idElement : p.first) { if (idElement instanceof GoIndexOrSliceExpr) { GoType referenceType = GoPsiImplUtil.getIndexedExpressionReferenceType((GoIndexOrSliceExpr)idElement, null); if (GoTypeUtil.isString(referenceType)) { // https://golang.org/ref/spec#Index_expressions // For a of string type: a[x] may not be assigned to holder.registerProblem(idElement, "Cannot assign to #ref #loc"); } } } int expressionsSize = list.size(); if (expressionsSize == 0) { return; } if (idCount == expressionsSize) { checkExpressionShouldReturnOneResult(list, holder); return; } int exprCount = expressionsSize; if (idCount == 2) { if (o instanceof GoRangeClause) { // range clause can be assigned to two variables return; } if (expressionsSize == 1) { GoExpression expression = list.get(0); if (expression instanceof GoIndexOrSliceExpr) { GoType referenceType = GoPsiImplUtil.getIndexedExpressionReferenceType((GoIndexOrSliceExpr)expression, null); if (referenceType != null && referenceType.getUnderlyingType() instanceof GoMapType) { // index expressions on maps can be assigned to two variables return; } } } } if (expressionsSize == 1) { exprCount = getExpressionResultCount(list.get(0)); if (exprCount == UNKNOWN_COUNT || exprCount == idCount) return; } String msg = String.format("Assignment count mismatch: %d = %d", idCount, exprCount); holder.registerProblem(o, msg, ProblemHighlightType.GENERIC_ERROR); } }; } private static void checkExpressionShouldReturnOneResult(@NotNull List expressions, @NotNull ProblemsHolder result) { for (GoExpression expr : expressions) { int count = getExpressionResultCount(expr); if (count != UNKNOWN_COUNT && count != 1) { String text = expr.getText(); if (expr instanceof GoCallExpr) { text = ((GoCallExpr)expr).getExpression().getText(); } String msg = count == 0 ? text + "() doesn't return a value" : "Multiple-value " + text + "() in single-value context"; result.registerProblem(expr, msg, ProblemHighlightType.GENERIC_ERROR); } } } } ================================================ FILE: src/com/goide/inspections/WrongModuleTypeNotificationProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoFileType; import com.goide.GoModuleType; import com.goide.sdk.GoSdkService; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Set; public class WrongModuleTypeNotificationProvider extends EditorNotifications.Provider implements DumbAware { private static final Key KEY = Key.create("Wrong module type"); private static final String DONT_ASK_TO_CHANGE_MODULE_TYPE_KEY = "do.not.ask.to.change.module.type"; private final Project myProject; public WrongModuleTypeNotificationProvider(@NotNull Project project) { myProject = project; } @NotNull @Override public Key getKey() { return KEY; } @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) { if (file.getFileType() != GoFileType.INSTANCE) return null; Module module = ModuleUtilCore.findModuleForFile(file, myProject); return module == null || GoSdkService.getInstance(myProject).isGoModule(module) || getIgnoredModules(myProject).contains(module.getName()) ? null : createPanel(myProject, module); } @NotNull private static EditorNotificationPanel createPanel(@NotNull Project project, @NotNull Module module) { EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText("'" + module.getName() + "' is not Go Module, some code insight might not work here"); panel.createActionLabel("Change module type to Go and reload project", () -> { int message = Messages.showOkCancelDialog(project, "Updating module type requires project reload. Proceed?", "Update Module Type", "Reload project", "Cancel", null); if (message == Messages.YES) { module.setOption(Module.ELEMENT_TYPE, GoModuleType.getInstance().getId()); project.save(); EditorNotifications.getInstance(project).updateAllNotifications(); ProjectManager.getInstance().reloadProject(project); } }); panel.createActionLabel("Don't show again for this module", () -> { Set ignoredModules = getIgnoredModules(project); ignoredModules.add(module.getName()); PropertiesComponent.getInstance(project).setValue(DONT_ASK_TO_CHANGE_MODULE_TYPE_KEY, StringUtil.join(ignoredModules, ",")); EditorNotifications.getInstance(project).updateAllNotifications(); }); return panel; } @NotNull private static Set getIgnoredModules(@NotNull Project project) { String value = PropertiesComponent.getInstance(project).getValue(DONT_ASK_TO_CHANGE_MODULE_TYPE_KEY, ""); return ContainerUtil.newLinkedHashSet(StringUtil.split(value, ",")); } } ================================================ FILE: src/com/goide/inspections/WrongSdkConfigurationNotificationProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoFileType; import com.goide.GoLanguage; import com.goide.configuration.GoLibrariesConfigurableProvider; import com.goide.project.GoLibrariesService; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.intellij.ProjectTopics; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.ModuleRootAdapter; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class WrongSdkConfigurationNotificationProvider extends EditorNotifications.Provider implements DumbAware { private static final Key KEY = Key.create("Setup Go SDK"); private static final String DO_NOT_SHOW_NOTIFICATION_ABOUT_EMPTY_GOPATH = "DO_NOT_SHOW_NOTIFICATION_ABOUT_EMPTY_GOPATH"; private final Project myProject; public WrongSdkConfigurationNotificationProvider(@NotNull Project project, @NotNull EditorNotifications notifications) { myProject = project; MessageBusConnection connection = myProject.getMessageBus().connect(project); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { notifications.updateAllNotifications(); } }); connection.subscribe(GoLibrariesService.LIBRARIES_TOPIC, newRootUrls -> notifications.updateAllNotifications()); } @NotNull @Override public Key getKey() { return KEY; } @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor) { if (file.getFileType() != GoFileType.INSTANCE) return null; PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); if (psiFile == null) return null; if (psiFile.getLanguage() != GoLanguage.INSTANCE) return null; Module module = ModuleUtilCore.findModuleForPsiElement(psiFile); if (module == null) return null; String sdkHomePath = GoSdkService.getInstance(myProject).getSdkHomePath(module); if (StringUtil.isEmpty(sdkHomePath)) { return createMissingSdkPanel(myProject, module); } if (!PropertiesComponent.getInstance().getBoolean(DO_NOT_SHOW_NOTIFICATION_ABOUT_EMPTY_GOPATH, false)) { String goPath = GoSdkUtil.retrieveGoPath(myProject, module); if (StringUtil.isEmpty(goPath.trim())) { return createEmptyGoPathPanel(myProject); } } return null; } @NotNull private static EditorNotificationPanel createMissingSdkPanel(@NotNull Project project, @Nullable Module module) { EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(ProjectBundle.message("project.sdk.not.defined")); panel.createActionLabel(ProjectBundle.message("project.sdk.setup"), () -> GoSdkService.getInstance(project).chooseAndSetSdk(module)); return panel; } @NotNull private static EditorNotificationPanel createEmptyGoPathPanel(@NotNull Project project) { EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText("GOPATH is empty"); panel.createActionLabel("Configure Go Libraries", () -> GoLibrariesConfigurableProvider.showModulesConfigurable(project)); panel.createActionLabel("Do not show again", () -> { PropertiesComponent.getInstance().setValue(DO_NOT_SHOW_NOTIFICATION_ABOUT_EMPTY_GOPATH, true); EditorNotifications.getInstance(project).updateAllNotifications(); }); return panel; } } ================================================ FILE: src/com/goide/inspections/suppression/GoInspectionSuppressor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.suppression; import com.goide.psi.*; import com.intellij.codeInsight.daemon.impl.actions.AbstractBatchSuppressByNoInspectionCommentFix; import com.intellij.codeInspection.InspectionSuppressor; import com.intellij.codeInspection.SuppressQuickFix; import com.intellij.codeInspection.SuppressionUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.usageView.UsageViewTypeLocation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.regex.Matcher; public class GoInspectionSuppressor implements InspectionSuppressor { @Override public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String toolId) { GoTopLevelDeclaration topLevelDeclaration = PsiTreeUtil.getTopmostParentOfType(element, GoTopLevelDeclaration.class); if (topLevelDeclaration != null && isSuppressedInStatement(toolId, topLevelDeclaration)) { return true; } GoImportDeclaration importDeclaration = PsiTreeUtil.getNonStrictParentOfType(element, GoImportDeclaration.class); if (importDeclaration != null && importDeclaration.getPrevSibling() == null && isSuppressedInStatement(element, toolId, GoImportList.class)) { return true; } return isSuppressedInStatement(element, toolId, GoPackageClause.class, GoStatement.class, GoCommClause.class, GoCaseClause.class, GoTopLevelDeclaration.class, GoImportDeclaration.class); } @NotNull @Override public SuppressQuickFix[] getSuppressActions(PsiElement element, @NotNull String toolId) { return new SuppressQuickFix[]{ new GoSuppressInspectionFix("comm case", GoCommClause.class, false), new GoSuppressInspectionFix(toolId, "comm case", GoCommClause.class, false), new GoSuppressInspectionFix("case", GoCaseClause.class, false), new GoSuppressInspectionFix(toolId, "case", GoCaseClause.class, false), new GoSuppressInspectionFix("declaration", GoTopLevelDeclaration.class, true), new GoSuppressInspectionFix(toolId, "declaration", GoTopLevelDeclaration.class, true), new GoSuppressForStatementFix(), new GoSuppressForStatementFix(toolId), new GoSuppressInspectionFix("import", GoImportDeclaration.class, false), new GoSuppressInspectionFix(toolId, "import", GoImportDeclaration.class, false), new GoSuppressInspectionFix("package statement", GoPackageClause.class, false), new GoSuppressInspectionFix(toolId, "package statement", GoPackageClause.class, false), }; } private static class GoSuppressForStatementFix extends GoSuppressInspectionFix { public GoSuppressForStatementFix() { super("statement", GoStatement.class, false); } public GoSuppressForStatementFix(@NotNull String ID) { super(ID, "statement", GoStatement.class, false); } @Nullable @Override public PsiElement getContainer(PsiElement context) { GoStatement statement = PsiTreeUtil.getNonStrictParentOfType(context, GoStatement.class); if (statement != null && statement.getParent() instanceof GoCommCase) { return PsiTreeUtil.getParentOfType(statement, GoStatement.class); } return statement; } } public static class GoSuppressInspectionFix extends AbstractBatchSuppressByNoInspectionCommentFix { private final Class myContainerClass; private final String myBaseText; private final boolean myTopMost; public GoSuppressInspectionFix(@NotNull String elementDescription, Class containerClass, boolean topMost) { super(SuppressionUtil.ALL, true); myBaseText = "Suppress all inspections for "; setText(myBaseText + elementDescription); myContainerClass = containerClass; myTopMost = topMost; } public GoSuppressInspectionFix(@NotNull String ID, @NotNull String elementDescription, Class containerClass, boolean topMost) { super(ID, false); myBaseText = "Suppress for "; setText(myBaseText + elementDescription); myTopMost = topMost; myContainerClass = containerClass; } @Override @Nullable public PsiElement getContainer(PsiElement context) { PsiElement container; if (myTopMost) { container = PsiTreeUtil.getTopmostParentOfType(context, myContainerClass); if (container == null && myContainerClass.isInstance(context)) { container = context; } } else { container = PsiTreeUtil.getNonStrictParentOfType(context, myContainerClass); } if (container != null) { String description = ElementDescriptionUtil.getElementDescription(container, UsageViewTypeLocation.INSTANCE); if (StringUtil.isNotEmpty(description)) { setText(myBaseText + description); } } return container; } } private static boolean isSuppressedInStatement(@NotNull PsiElement place, @NotNull String toolId, @NotNull Class... statementClasses) { PsiElement statement = PsiTreeUtil.getNonStrictParentOfType(place, statementClasses); while (statement != null) { if (isSuppressedInStatement(toolId, statement)) { return true; } statement = PsiTreeUtil.getParentOfType(statement, statementClasses); } return false; } private static boolean isSuppressedInStatement(@NotNull String toolId, @Nullable PsiElement statement) { if (statement != null) { PsiElement prev = PsiTreeUtil.skipSiblingsBackward(statement, PsiWhiteSpace.class); if (prev instanceof PsiComment) { String text = prev.getText(); Matcher matcher = SuppressionUtil.SUPPRESS_IN_LINE_COMMENT_PATTERN.matcher(text); return matcher.matches() && SuppressionUtil.isInspectionToolIdMentioned(matcher.group(1), toolId); } } return false; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoAssignmentToConstantInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.inspections.GoInspectionBase; import com.goide.psi.GoConstDefinition; import com.goide.psi.GoReferenceExpression; import com.goide.psi.GoVisitor; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; public class GoAssignmentToConstantInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitReferenceExpression(@NotNull GoReferenceExpression o) { super.visitReferenceExpression(o); if (o.getReadWriteAccess() != ReadWriteAccessDetector.Access.Read) { PsiElement resolve = o.resolve(); if (resolve instanceof GoConstDefinition) { holder.registerProblem(o, "Cannot assign to constant", GENERIC_ERROR_OR_WARNING); } } } }; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceFunctionFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.GoConstants; import com.goide.GoDocumentationProvider; import com.goide.project.GoVendoringUtil; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.goide.refactor.GoRefactoringUtil; import com.goide.util.GoPathScopeHelper; import com.goide.util.GoUtil; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.ConstantNode; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; public class GoIntroduceFunctionFix extends LocalQuickFixAndIntentionActionOnPsiElement implements HighPriorityAction { private final String myName; private static final String FAMILY_NAME = "Create function"; public GoIntroduceFunctionFix(@NotNull PsiElement element, @NotNull String name) { super(element); myName = name; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (editor == null) { LOG.error("Cannot run quick fix without editor: " + getClass().getSimpleName(), AttachmentFactory.createAttachment(file.getVirtualFile())); return; } if (!(startElement instanceof GoCallExpr)) return; GoCallExpr call = (GoCallExpr)startElement; List args = call.getArgumentList().getExpressionList(); GoType resultType = ContainerUtil.getFirstItem(GoTypeUtil.getExpectedTypes(call)); PsiElement anchor = PsiTreeUtil.findPrevParent(file, call); Template template = TemplateManager.getInstance(project).createTemplate("", ""); template.addTextSegment("\nfunc " + myName); setupFunctionParameters(template, args, file); setupFunctionResult(template, resultType); template.addTextSegment(" {\n\t"); template.addEndVariable(); template.addTextSegment("\n}"); int offset = anchor.getTextRange().getEndOffset(); editor.getCaretModel().moveToOffset(offset); startTemplate(editor, template, project); } @NotNull private static String convertType(@NotNull PsiFile file, @Nullable GoType type, @NotNull Map importMap) { if (type == null) return GoConstants.INTERFACE_TYPE; Module module = ModuleUtilCore.findModuleForPsiElement(file); boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module); return GoDocumentationProvider.getTypePresentation(type, element -> { if (element instanceof GoTypeSpec) { GoTypeSpec spec = (GoTypeSpec)element; if (GoPsiImplUtil.builtin(spec)) return spec.getIdentifier().getText(); GoFile typeFile = spec.getContainingFile(); if (file.isEquivalentTo(typeFile) || GoUtil.inSamePackage(typeFile, file)) { return spec.getIdentifier().getText(); } if (!spec.isPublic()) { return GoConstants.INTERFACE_TYPE; } GoPathScopeHelper scopeHelper = GoPathScopeHelper.fromReferenceFile(file.getProject(), module, file.getVirtualFile()); boolean isAllowed = scopeHelper.couldBeReferenced(typeFile.getVirtualFile(), file.getVirtualFile()); if (!isAllowed) return GoConstants.INTERFACE_TYPE; String importPath = typeFile.getImportPath(vendoringEnabled); GoImportSpec importSpec = importMap.get(importPath); String packageName = StringUtil.notNullize(typeFile.getPackageName()); String qualifier = StringUtil.notNullize(GoPsiImplUtil.getImportQualifierToUseInFile(importSpec, packageName), packageName); // todo: add import package fix if getImportQualifierToUseInFile is null? return GoPsiImplUtil.getFqn(qualifier, spec.getIdentifier().getText()); } return GoConstants.INTERFACE_TYPE; }); } private static void setupFunctionResult(@NotNull Template template, @Nullable GoType type) { if (type instanceof GoTypeList) { template.addTextSegment(" ("); List list = ((GoTypeList)type).getTypeList(); for (int i = 0; i < list.size(); i++) { template.addVariable(new ConstantNode(list.get(i).getText()), true); if (i < list.size() - 1) template.addTextSegment(", "); } template.addTextSegment(")"); return; } if (type != null) { template.addTextSegment(" "); template.addVariable(new ConstantNode(type.getText()), true); } } private static void setupFunctionParameters(@NotNull Template template, @NotNull List args, PsiFile file) { Map importMap = ((GoFile)file).getImportedPackagesMap(); template.addTextSegment("("); for (int i = 0; i < args.size(); i++) { GoExpression e = args.get(i); template.addVariable(GoRefactoringUtil.createParameterNameSuggestedExpression(e), true); template.addTextSegment(" "); String type = convertType(file, e.getGoType(null), importMap); template.addVariable(new ConstantNode(type), true); if (i != args.size() - 1) template.addTextSegment(", "); } template.addTextSegment(")"); } private static void startTemplate(@NotNull Editor editor, @NotNull Template template, @NotNull Project project) { Runnable runnable = () -> { if (project.isDisposed() || editor.isDisposed()) return; CommandProcessor.getInstance().executeCommand(project, () -> TemplateManager.getInstance(project).startTemplate(editor, template, null), "Introduce function", null); }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable); } } @NotNull @Override public String getText() { return FAMILY_NAME + " " + myName; } @Nls @NotNull @Override public String getFamilyName() { return FAMILY_NAME; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceGlobalConstantFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public class GoIntroduceGlobalConstantFix extends GoUnresolvedFixBase { public GoIntroduceGlobalConstantFix(@NotNull PsiElement element, @NotNull String name) { super(element, name, "global constant", "go_lang_const_qf"); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceGlobalVariableFix.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public class GoIntroduceGlobalVariableFix extends GoUnresolvedFixBase { public GoIntroduceGlobalVariableFix(@NotNull PsiElement element, @NotNull String name) { super(element, name, "global variable", "go_lang_global_var_qf"); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceLocalConstantFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.refactor.GoRefactoringUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoIntroduceLocalConstantFix extends GoUnresolvedFixBase { public GoIntroduceLocalConstantFix(@NotNull PsiElement element, @NotNull String name) { super(element, name, "local constant", "go_lang_const_qf"); } @Nullable @Override protected PsiElement findAnchor(@NotNull PsiElement reference) { return GoRefactoringUtil.findLocalAnchor(GoRefactoringUtil.getLocalOccurrences(reference)); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceLocalVariableFix.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.refactor.GoRefactoringUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoIntroduceLocalVariableFix extends GoUnresolvedFixBase { public GoIntroduceLocalVariableFix(@NotNull PsiElement element, @NotNull String name) { super(element, name, "local variable", "go_lang_local_var_qf"); } @Nullable @Override protected PsiElement findAnchor(@NotNull PsiElement reference) { return GoRefactoringUtil.findLocalAnchor(GoRefactoringUtil.getLocalOccurrences(reference)); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoIntroduceTypeFix.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public class GoIntroduceTypeFix extends GoUnresolvedFixBase { public GoIntroduceTypeFix(@NotNull PsiElement element, @NotNull String name) { super(element, name, "type", "go_lang_type_qf"); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoReplaceAssignmentWithDeclarationQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.psi.GoAssignmentStatement; import com.goide.psi.GoExpression; import com.goide.psi.GoRangeClause; import com.goide.psi.GoRecvStatement; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalQuickFixOnPsiElement; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; public class GoReplaceAssignmentWithDeclarationQuickFix extends LocalQuickFixOnPsiElement { public static final String QUICK_FIX_NAME = "Replace with ':='"; public GoReplaceAssignmentWithDeclarationQuickFix(@NotNull PsiElement element) { super(element); } @NotNull @Override public String getText() { return QUICK_FIX_NAME; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (startElement instanceof GoAssignmentStatement) { GoAssignmentStatement statement = (GoAssignmentStatement)startElement; String leftSide = statement.getLeftHandExprList().getText(); String rightSide = GoPsiImplUtil.joinPsiElementText(statement.getExpressionList()); statement.replace(GoElementFactory.createShortVarDeclarationStatement(project, leftSide, rightSide)); } else if (startElement instanceof GoRangeClause) { GoRangeClause rangeClause = (GoRangeClause)startElement; String leftSide = GoPsiImplUtil.joinPsiElementText(rangeClause.getLeftExpressionsList()); GoExpression rangeExpression = rangeClause.getRangeExpression(); String rightSide = rangeExpression != null ? rangeExpression.getText() : ""; rangeClause.replace(GoElementFactory.createRangeClause(project, leftSide, rightSide)); } else if (startElement instanceof GoRecvStatement) { GoRecvStatement recvStatement = (GoRecvStatement)startElement; String leftSide = GoPsiImplUtil.joinPsiElementText(recvStatement.getLeftExpressionsList()); GoExpression recvExpression = recvStatement.getRecvExpression(); String rightSide = recvExpression != null ? recvExpression.getText() : ""; recvStatement.replace(GoElementFactory.createRecvStatement(project, leftSide, rightSide)); } } @Nls @NotNull @Override public String getFamilyName() { return QUICK_FIX_NAME; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnresolvedFixBase.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.psi.GoReferenceExpressionBase; import com.goide.refactor.GoRefactoringUtil; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.TemplateSettings; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoUnresolvedFixBase extends LocalQuickFixAndIntentionActionOnPsiElement { @NotNull private final String myName; @NotNull private final String myWhat; @NotNull private final String myTemplateId; public GoUnresolvedFixBase(@NotNull PsiElement element, @NotNull String name, @NotNull String what, @NotNull String templateId) { super(element); myName = name; myWhat = what; myTemplateId = templateId; } @NotNull @Override public String getText() { return "Create " + myWhat + " '" + myName + "'"; } @NotNull @Override public String getFamilyName() { return "Create " + myWhat; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (editor == null) { LOG.error("Cannot run quick fix without editor: " + getClass().getSimpleName(), AttachmentFactory.createAttachment(file.getVirtualFile())); return; } PsiElement reference = PsiTreeUtil.getNonStrictParentOfType(startElement, GoReferenceExpressionBase.class); PsiElement anchor = reference != null ? findAnchor(reference) : null; if (anchor == null) { LOG.error("Cannot find anchor for " + myWhat + " (GoUnresolvedFixBase), offset: " + editor.getCaretModel().getOffset(), AttachmentFactory.createAttachment(file.getVirtualFile())); return; } Template template = TemplateSettings.getInstance().getTemplateById(myTemplateId); if (template == null) { LOG.error("Cannot find anchor for " + myWhat + " (GoUnresolvedFixBase), offset: " + editor.getCaretModel().getOffset(), AttachmentFactory.createAttachment(file.getVirtualFile())); return; } int start = anchor.getTextRange().getStartOffset(); editor.getCaretModel().moveToOffset(start); template.setToReformat(true); TemplateManager.getInstance(project).startTemplate(editor, template, true, ContainerUtil.stringMap("NAME", myName), null); } @Nullable protected PsiElement findAnchor(@NotNull PsiElement reference) { PsiFile file = reference.getContainingFile(); return GoRefactoringUtil.findAnchor(GoRefactoringUtil.getOccurrences(reference, file), file); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnresolvedReferenceInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.GoTypes; import com.goide.codeInsight.imports.GoImportPackageQuickFix; import com.goide.inspections.GoInspectionBase; import com.goide.psi.*; import com.goide.psi.impl.GoReference; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveResult; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import static com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING; import static com.intellij.codeInspection.ProblemHighlightType.LIKE_UNKNOWN_SYMBOL; public class GoUnresolvedReferenceInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFieldName(@NotNull GoFieldName o) { super.visitFieldName(o); PsiElement resolve = o.resolve(); if (resolve == null) { PsiElement id = o.getIdentifier(); holder.registerProblem(id, "Unknown field #ref in struct literal #loc", LIKE_UNKNOWN_SYMBOL); } } @Override public void visitReferenceExpression(@NotNull GoReferenceExpression o) { super.visitReferenceExpression(o); GoReference reference = o.getReference(); GoReferenceExpression qualifier = o.getQualifier(); GoReference qualifierRef = qualifier != null ? qualifier.getReference() : null; PsiElement qualifierResolve = qualifierRef != null ? qualifierRef.resolve() : null; if (qualifier != null && qualifierResolve == null) return; ResolveResult[] results = reference.multiResolve(false); PsiElement id = o.getIdentifier(); String name = id.getText(); if (results.length > 1) { holder.registerProblem(id, "Ambiguous reference " + "'" + name + "'", GENERIC_ERROR_OR_WARNING); } else if (reference.resolve() == null) { LocalQuickFix[] fixes = LocalQuickFix.EMPTY_ARRAY; if (isProhibited(o, qualifier)) { fixes = createImportPackageFixes(o, reference, holder.isOnTheFly()); } else if (holder.isOnTheFly()) { boolean canBeLocal = PsiTreeUtil.getParentOfType(o, GoBlock.class) != null; List fixesList = ContainerUtil.newArrayList(new GoIntroduceGlobalVariableFix(id, name)); if (canBeLocal) { fixesList.add(new GoIntroduceLocalVariableFix(id, name)); } PsiElement parent = o.getParent(); if (o.getReadWriteAccess() == ReadWriteAccessDetector.Access.Read) { fixesList.add(new GoIntroduceGlobalConstantFix(id, name)); if (canBeLocal) { fixesList.add(new GoIntroduceLocalConstantFix(id, name)); } } else if (canBeLocal) { PsiElement grandParent = parent.getParent(); if (grandParent instanceof GoAssignmentStatement) { fixesList.add(new GoReplaceAssignmentWithDeclarationQuickFix(grandParent)); } else if (parent instanceof GoRangeClause || parent instanceof GoRecvStatement) { fixesList.add(new GoReplaceAssignmentWithDeclarationQuickFix(parent)); } } if (parent instanceof GoCallExpr && PsiTreeUtil.getParentOfType(o, GoConstDeclaration.class) == null) { fixesList.add(new GoIntroduceFunctionFix(parent, name)); } fixes = fixesList.toArray(new LocalQuickFix[fixesList.size()]); } holder.registerProblem(id, "Unresolved reference " + "'" + name + "'", LIKE_UNKNOWN_SYMBOL, fixes); } } @Override public void visitImportSpec(@NotNull GoImportSpec o) { if (o.isCImport()) return; GoImportString string = o.getImportString(); if (string.getTextLength() < 2) return; PsiReference[] references = string.getReferences(); for (PsiReference reference : references) { if (reference instanceof FileReference) { ResolveResult[] resolveResults = ((FileReference)reference).multiResolve(false); if (resolveResults.length == 0) { ProblemHighlightType type = reference.getRangeInElement().isEmpty() ? GENERIC_ERROR_OR_WARNING : LIKE_UNKNOWN_SYMBOL; holder.registerProblem(reference, ProblemsHolder.unresolvedReferenceMessage(reference), type); } } } } @Override public void visitLabelRef(@NotNull GoLabelRef o) { PsiReference reference = o.getReference(); String name = o.getText(); if (reference.resolve() == null) { holder.registerProblem(o, "Unresolved label " + "'" + name + "'", LIKE_UNKNOWN_SYMBOL); } } @Override public void visitTypeReferenceExpression(@NotNull GoTypeReferenceExpression o) { super.visitTypeReferenceExpression(o); PsiReference reference = o.getReference(); GoTypeReferenceExpression qualifier = o.getQualifier(); PsiElement qualifierResolve = qualifier != null ? qualifier.resolve() : null; if (qualifier != null && qualifierResolve == null) return; if (reference.resolve() == null) { PsiElement id = o.getIdentifier(); String name = id.getText(); boolean isProhibited = isProhibited(o, qualifier); LocalQuickFix[] fixes = LocalQuickFix.EMPTY_ARRAY; if (isProhibited) { fixes = createImportPackageFixes(o, reference, holder.isOnTheFly()); } else if (holder.isOnTheFly()) { fixes = new LocalQuickFix[]{new GoIntroduceTypeFix(id, name)}; } holder.registerProblem(id, "Unresolved type " + "'" + name + "'", LIKE_UNKNOWN_SYMBOL, fixes); } } }; } @NotNull private static LocalQuickFix[] createImportPackageFixes(@NotNull PsiElement target, @NotNull PsiReference reference, boolean onTheFly) { if (onTheFly) { GoImportPackageQuickFix importFix = new GoImportPackageQuickFix(reference); if (importFix.isAvailable(target.getProject(), target.getContainingFile(), target, target)) { return new LocalQuickFix[]{importFix}; } } else { List packagesToImport = GoImportPackageQuickFix.getImportPathVariantsToImport(reference.getCanonicalText(), target); if (!packagesToImport.isEmpty()) { Collection result = ContainerUtil.newArrayList(); for (String importPath : packagesToImport) { GoImportPackageQuickFix importFix = new GoImportPackageQuickFix(target, importPath); if (importFix.isAvailable(target.getProject(), target.getContainingFile(), target, target)) { result.add(importFix); } } return result.toArray(new LocalQuickFix[result.size()]); } } return LocalQuickFix.EMPTY_ARRAY; } private static boolean isProhibited(@NotNull GoCompositeElement o, @Nullable GoCompositeElement qualifier) { ASTNode next = FormatterUtil.getNextNonWhitespaceSibling(o.getNode()); boolean isDot = next != null && next.getElementType() == GoTypes.DOT; return isDot || qualifier != null; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedConstInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.inspections.GoInspectionBase; import com.goide.psi.GoConstDefinition; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoDeleteConstDefinitionQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.search.searches.ReferencesSearch; import org.jetbrains.annotations.NotNull; public class GoUnusedConstInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitConstDefinition(@NotNull GoConstDefinition o) { if (o.isBlank()) return; if (ReferencesSearch.search(o, o.getUseScope()).findFirst() == null) { String constName = o.getName(); holder.registerProblem(o, "Unused constant #ref #loc", ProblemHighlightType.LIKE_UNUSED_SYMBOL, new GoDeleteConstDefinitionQuickFix(constName)); } } }; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedExportedFunctionInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.intellij.openapi.util.text.StringUtil; public class GoUnusedExportedFunctionInspection extends GoUnusedFunctionInspection { @Override protected boolean canRun(String name) { return StringUtil.isCapitalized(name); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedFunctionInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.GoConstants; import com.goide.inspections.GoInspectionBase; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoDeleteQuickFix; import com.goide.quickfix.GoRenameToBlankQuickFix; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestFunctionType; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.search.searches.ReferencesSearch; import org.jetbrains.annotations.NotNull; public class GoUnusedFunctionInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { if (o.isBlank()) return; GoFile file = o.getContainingFile(); String name = o.getName(); if (!canRun(name)) return; if (GoConstants.MAIN.equals(file.getPackageName()) && GoConstants.MAIN.equals(name)) return; if (GoConstants.INIT.equals(name)) return; if (GoTestFinder.isTestFile(file) && GoTestFunctionType.fromName(name) != null) return; if (ReferencesSearch.search(o, o.getUseScope()).findFirst() == null) { PsiElement id = o.getIdentifier(); TextRange range = TextRange.from(id.getStartOffsetInParent(), id.getTextLength()); holder.registerProblem(o, "Unused function #ref #loc", ProblemHighlightType.LIKE_UNUSED_SYMBOL, range, new GoDeleteQuickFix("Delete function", GoFunctionDeclaration.class), new GoRenameToBlankQuickFix(o)); } } }; } protected boolean canRun(String name) { return !StringUtil.isCapitalized(name); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedGlobalVariableInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.psi.GoVarDeclaration; import com.goide.psi.GoVarDefinition; import com.goide.quickfix.GoDeleteVarDefinitionQuickFix; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoUnusedGlobalVariableInspection extends GoUnusedVariableInspection { @Override protected void reportError(@NotNull GoVarDefinition varDefinition, @NotNull ProblemsHolder holder) { holder.registerProblem(varDefinition, "Unused variable #ref #loc", ProblemHighlightType.LIKE_UNUSED_SYMBOL, new GoDeleteVarDefinitionQuickFix(varDefinition.getName())); } @Override protected boolean shouldValidate(@Nullable GoVarDeclaration varDeclaration) { return !super.shouldValidate(varDeclaration); } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedLabelInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.inspections.GoInspectionBase; import com.goide.psi.GoLabelDefinition; import com.goide.psi.GoLabeledStatement; import com.goide.psi.GoStatement; import com.goide.psi.GoVisitor; import com.goide.quickfix.GoRenameToBlankQuickFix; import com.intellij.codeInspection.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.search.searches.ReferencesSearch; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoUnusedLabelInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitLabelDefinition(@NotNull GoLabelDefinition o) { super.visitLabelDefinition(o); if (o.isBlank()) return; if (ReferencesSearch.search(o, o.getUseScope()).findFirst() == null) { String name = o.getName(); holder.registerProblem(o, "Unused label #ref #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoRenameToBlankQuickFix(o), new GoDeleteLabelStatementQuickFix(name)); } } }; } private static class GoDeleteLabelStatementQuickFix extends LocalQuickFixBase { public GoDeleteLabelStatementQuickFix(@Nullable String labelName) { super("Delete label " + (labelName != null ? "'" + labelName + "'" : ""), "Delete label"); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element.isValid() && element instanceof GoLabelDefinition) { PsiElement parent = element.getParent(); if (parent instanceof GoLabeledStatement) { GoStatement innerStatement = ((GoLabeledStatement)parent).getStatement(); if (innerStatement != null) { parent.replace(innerStatement); } } } } } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedParameterInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.inspections.GoInspectionBase; import com.goide.psi.*; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestFunctionType; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.progress.ProgressManager; import com.intellij.psi.PsiReference; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.util.Query; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoUnusedParameterInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitMethodDeclaration(@NotNull GoMethodDeclaration o) { super.visitMethodDeclaration(o); visitDeclaration(o, false); } @Override public void visitFunctionDeclaration(@NotNull GoFunctionDeclaration o) { super.visitFunctionDeclaration(o); if (GoTestFinder.isTestFile(o.getContainingFile()) && GoTestFunctionType.fromName(o.getName()) != null) { return; } visitDeclaration(o, true); } private void visitDeclaration(@NotNull GoFunctionOrMethodDeclaration o, boolean checkParameters) { GoSignature signature = o.getSignature(); if (signature == null) return; if (checkParameters) { GoParameters parameters = signature.getParameters(); visitParameterList(parameters.getParameterDeclarationList(), "parameter"); } GoResult result = signature.getResult(); GoParameters returnParameters = result != null ? result.getParameters() : null; if (returnParameters != null) { visitParameterList(returnParameters.getParameterDeclarationList(), "named return parameter"); } } private void visitParameterList(List parameters, String what) { for (GoParameterDeclaration parameterDeclaration : parameters) { for (GoParamDefinition parameter : parameterDeclaration.getParamDefinitionList()) { ProgressManager.checkCanceled(); if (parameter.isBlank()) continue; Query search = ReferencesSearch.search(parameter, parameter.getUseScope()); if (search.findFirst() != null) continue; holder.registerProblem(parameter, "Unused " + what + " #ref #loc", ProblemHighlightType.LIKE_UNUSED_SYMBOL); } } } }; } } ================================================ FILE: src/com/goide/inspections/unresolved/GoUnusedVariableInspection.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.unresolved; import com.goide.inspections.GoInspectionBase; import com.goide.psi.*; import com.goide.psi.impl.GoVarProcessor; import com.goide.quickfix.GoDeleteVarDefinitionQuickFix; import com.goide.quickfix.GoRenameToBlankQuickFix; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.openapi.progress.ProgressManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoUnusedVariableInspection extends GoInspectionBase { @NotNull @Override protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitVarDefinition(@NotNull GoVarDefinition o) { if (o.isBlank()) return; GoCompositeElement varSpec = PsiTreeUtil.getParentOfType(o, GoVarSpec.class, GoTypeSwitchGuard.class); GoVarDeclaration decl = PsiTreeUtil.getParentOfType(o, GoVarDeclaration.class); if (shouldValidate(decl) && (varSpec != null || decl != null)) { PsiReference reference = o.getReference(); PsiElement resolve = reference != null ? reference.resolve() : null; if (resolve != null) return; boolean foundReference = !ReferencesSearch.search(o, o.getUseScope()).forEach(reference1 -> { ProgressManager.checkCanceled(); PsiElement element = reference1.getElement(); if (element == null) return true; PsiElement parent = element.getParent(); if (parent instanceof GoLeftHandExprList) { PsiElement grandParent = parent.getParent(); if (grandParent instanceof GoAssignmentStatement && ((GoAssignmentStatement)grandParent).getAssignOp().getAssign() != null) { GoFunctionLit fn = PsiTreeUtil.getParentOfType(element, GoFunctionLit.class); if (fn == null || !PsiTreeUtil.isAncestor(GoVarProcessor.getScope(o), fn, true)) { return true; } } } if (parent instanceof GoShortVarDeclaration) { int op = ((GoShortVarDeclaration)parent).getVarAssign().getStartOffsetInParent(); if (element.getStartOffsetInParent() < op) { return true; } } return false; }); if (!foundReference) { reportError(o, holder); } } } }; } protected void reportError(@NotNull GoVarDefinition varDefinition, @NotNull ProblemsHolder holder) { holder.registerProblem(varDefinition, "Unused variable #ref #loc", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new GoRenameToBlankQuickFix(varDefinition), new GoDeleteVarDefinitionQuickFix(varDefinition.getName())); } protected boolean shouldValidate(@Nullable GoVarDeclaration varDeclaration) { return varDeclaration == null || !(varDeclaration.getParent() instanceof GoFile); } } ================================================ FILE: src/com/goide/intentions/GoAddFunctionBlockIntention.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.intentions; import com.goide.editor.smart.GoSmartEnterProcessor; import com.goide.psi.GoBlock; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; public class GoAddFunctionBlockIntention extends BaseElementAtCaretIntentionAction { public static final String NAME = "Add function body"; public GoAddFunctionBlockIntention() { setText(NAME); } @Nls @NotNull @Override public String getFamilyName() { return NAME; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { PsiElement parent = element.getParent(); return parent instanceof GoFunctionOrMethodDeclaration && ((GoFunctionOrMethodDeclaration)parent).getBlock() == null; } @Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { PsiElement parent = element.getParent(); if (parent instanceof GoFunctionOrMethodDeclaration) { GoBlock block = ((GoFunctionOrMethodDeclaration)parent).getBlock(); if (block == null) { GoBlock newBlock = ObjectUtils.tryCast(parent.add(GoElementFactory.createBlock(project)), GoBlock.class); if (newBlock != null) { PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); new GoSmartEnterProcessor.PlainEnterProcessor().doEnter(newBlock, newBlock.getContainingFile(), editor, false); } } } } } ================================================ FILE: src/com/goide/intentions/GoMoveToStructInitializationIntention.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.intentions; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; import static com.intellij.util.containers.ContainerUtil.*; public class GoMoveToStructInitializationIntention extends BaseElementAtCaretIntentionAction { public static final String NAME = "Move field assignment to struct initialization"; public GoMoveToStructInitializationIntention() { setText(NAME); } @Nls @NotNull @Override public String getFamilyName() { return NAME; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { return getData(element) != null; } @Nullable private static Data getData(@NotNull PsiElement element) { if (!element.isValid() || !element.isWritable()) return null; GoAssignmentStatement assignment = getValidAssignmentParent(element); GoReferenceExpression selectedFieldReference = assignment != null ? getFieldReferenceExpression(element, assignment) : null; GoCompositeLit compositeLit = selectedFieldReference != null ? getStructLiteralByReference(selectedFieldReference, assignment) : null; if (compositeLit == null) return null; List references = getUninitializedSingleFieldReferences(assignment, selectedFieldReference, compositeLit); return !references.isEmpty() ? new Data(assignment, compositeLit, references) : null; } @Nullable private static GoAssignmentStatement getValidAssignmentParent(@Nullable PsiElement element) { GoAssignmentStatement assignment = PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class); return assignment != null && assignment.isValid() && getLeftHandElements(assignment).size() == assignment.getExpressionList().size() ? assignment : null; } @Nullable private static GoReferenceExpression getFieldReferenceExpression(@NotNull PsiElement selectedElement, @NotNull GoAssignmentStatement assignment) { GoReferenceExpression selectedReferenceExpression = PsiTreeUtil.getTopmostParentOfType(selectedElement, GoReferenceExpression.class); if (isFieldReferenceExpression(selectedReferenceExpression)) { return !isAssignedInPreviousStatement(selectedReferenceExpression, assignment) ? selectedReferenceExpression : null; } List fieldReferenceExpressions = getFieldReferenceExpressions(assignment); if (exists(fieldReferenceExpressions, expression -> isAssignedInPreviousStatement(expression, assignment))) return null; Set resolvedFields = map2Set(fieldReferenceExpressions, GoMoveToStructInitializationIntention::resolveQualifier); return resolvedFields.size() == 1 ? getFirstItem(fieldReferenceExpressions) : null; } @NotNull private static List getFieldReferenceExpressions(@NotNull GoAssignmentStatement assignment) { return filter(map(getLeftHandElements(assignment), GoMoveToStructInitializationIntention::unwrapParensAndCast), GoMoveToStructInitializationIntention::isFieldReferenceExpression); } @Nullable private static GoReferenceExpression unwrapParensAndCast(@Nullable PsiElement e) { while (e instanceof GoParenthesesExpr) { e = ((GoParenthesesExpr)e).getExpression(); } return ObjectUtils.tryCast(e, GoReferenceExpression.class); } @Contract("null -> false") private static boolean isFieldReferenceExpression(@Nullable PsiElement element) { return element instanceof GoReferenceExpression && isFieldDefinition(((GoReferenceExpression)element).resolve()); } @Contract("null -> false") private static boolean isFieldDefinition(@Nullable PsiElement element) { return element instanceof GoFieldDefinition || element instanceof GoAnonymousFieldDefinition; } private static boolean isAssignedInPreviousStatement(@NotNull GoExpression referenceExpression, @NotNull GoAssignmentStatement assignment) { GoReferenceExpression rightExpression = unwrapParensAndCast(GoPsiImplUtil.getRightExpression(assignment, getTopmostExpression(referenceExpression))); PsiElement resolve = rightExpression != null ? rightExpression.resolve() : null; GoStatement previousElement = resolve != null ? PsiTreeUtil.getPrevSiblingOfType(assignment, GoStatement.class) : null; return previousElement != null && exists(getLeftHandElements(previousElement), e -> isResolvedTo(e, resolve)); } @NotNull private static GoExpression getTopmostExpression(@NotNull GoExpression expression) { return ObjectUtils.notNull(PsiTreeUtil.getTopmostParentOfType(expression, GoExpression.class), expression); } private static boolean isResolvedTo(@Nullable PsiElement e, @Nullable PsiElement resolve) { if (e instanceof GoVarDefinition) return resolve == e; GoReferenceExpression refExpression = unwrapParensAndCast(e); return refExpression != null && refExpression.resolve() == resolve; } @NotNull private static List getUninitializedSingleFieldReferences(@NotNull GoAssignmentStatement assignment, @NotNull GoReferenceExpression fieldReferenceExpression, @NotNull GoCompositeLit compositeLit) { PsiElement resolve = resolveQualifier(fieldReferenceExpression); List uninitializedFieldReferencesByQualifier = filter(getUninitializedFieldReferenceExpressions(assignment, compositeLit), e -> isResolvedTo(e.getQualifier(), resolve)); MultiMap resolved = groupBy(uninitializedFieldReferencesByQualifier, GoReferenceExpression::resolve); return map(filter(resolved.entrySet(), set -> set.getValue().size() == 1), set -> getFirstItem(set.getValue())); } @Nullable private static GoCompositeLit getStructLiteralByReference(@NotNull GoReferenceExpression fieldReferenceExpression, @NotNull GoAssignmentStatement assignment) { GoStatement previousStatement = PsiTreeUtil.getPrevSiblingOfType(assignment, GoStatement.class); if (previousStatement instanceof GoSimpleStatement) { return getStructLiteral(fieldReferenceExpression, (GoSimpleStatement)previousStatement); } if (previousStatement instanceof GoAssignmentStatement) { return getStructLiteral(fieldReferenceExpression, (GoAssignmentStatement)previousStatement); } return null; } @Nullable private static GoCompositeLit getStructLiteral(@NotNull GoReferenceExpression fieldReferenceExpression, @NotNull GoSimpleStatement structDeclaration) { GoShortVarDeclaration varDeclaration = structDeclaration.getShortVarDeclaration(); if (varDeclaration == null) return null; PsiElement resolve = resolveQualifier(fieldReferenceExpression); GoVarDefinition structVarDefinition = find(varDeclaration.getVarDefinitionList(), definition -> resolve == definition); return structVarDefinition != null ? ObjectUtils.tryCast(structVarDefinition.getValue(), GoCompositeLit.class) : null; } @Nullable private static PsiElement resolveQualifier(@NotNull GoReferenceExpression fieldReferenceExpression) { GoReferenceExpression qualifier = fieldReferenceExpression.getQualifier(); return qualifier != null ? qualifier.resolve() : null; } @Nullable private static GoCompositeLit getStructLiteral(@NotNull GoReferenceExpression fieldReferenceExpression, @NotNull GoAssignmentStatement structAssignment) { GoVarDefinition varDefinition = ObjectUtils.tryCast(resolveQualifier(fieldReferenceExpression), GoVarDefinition.class); PsiElement field = fieldReferenceExpression.resolve(); if (varDefinition == null || !isFieldDefinition(field) || !hasStructTypeWithField(varDefinition, (GoNamedElement)field)) { return null; } GoExpression structReferenceExpression = find(structAssignment.getLeftHandExprList().getExpressionList(), expression -> isResolvedTo(expression, varDefinition)); if (structReferenceExpression == null) return null; GoExpression compositeLit = GoPsiImplUtil.getRightExpression(structAssignment, structReferenceExpression); return ObjectUtils.tryCast(compositeLit, GoCompositeLit.class); } private static boolean hasStructTypeWithField(@NotNull GoVarDefinition structVarDefinition, @NotNull GoNamedElement field) { GoType type = structVarDefinition.getGoType(null); GoStructType structType = type != null ? ObjectUtils.tryCast(type.getUnderlyingType(), GoStructType.class) : null; return structType != null && PsiTreeUtil.isAncestor(structType, field, true); } private static boolean isFieldInitialization(@NotNull GoElement element, @NotNull PsiElement field) { GoKey key = element.getKey(); GoFieldName fieldName = key != null ? key.getFieldName() : null; return fieldName != null && fieldName.resolve() == field; } @NotNull private static List getUninitializedFieldReferenceExpressions(@NotNull GoAssignmentStatement assignment, @NotNull GoCompositeLit structLiteral) { return filter(getFieldReferenceExpressions(assignment), expression -> isUninitializedFieldReferenceExpression(expression, structLiteral) && !isAssignedInPreviousStatement(expression, assignment)); } @Contract("null, _-> false") private static boolean isUninitializedFieldReferenceExpression(@Nullable GoReferenceExpression fieldReferenceExpression, @NotNull GoCompositeLit structLiteral) { if (fieldReferenceExpression == null) return false; GoLiteralValue literalValue = structLiteral.getLiteralValue(); PsiElement resolve = fieldReferenceExpression.resolve(); return literalValue != null && isFieldDefinition(resolve) && !exists(literalValue.getElementList(), element -> isFieldInitialization(element, resolve)); } @NotNull private static List getLeftHandElements(@NotNull GoStatement statement) { if (statement instanceof GoSimpleStatement) { GoShortVarDeclaration varDeclaration = ((GoSimpleStatement)statement).getShortVarDeclaration(); return varDeclaration != null ? varDeclaration.getVarDefinitionList() : emptyList(); } if (statement instanceof GoAssignmentStatement) { return ((GoAssignmentStatement)statement).getLeftHandExprList().getExpressionList(); } return emptyList(); } @Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { Data data = getData(element); if (data == null) return; moveFieldReferenceExpressions(data); } private static void moveFieldReferenceExpressions(@NotNull Data data) { GoLiteralValue literalValue = data.getCompositeLit().getLiteralValue(); if (literalValue == null) return; for (GoReferenceExpression expression : data.getReferenceExpressions()) { GoExpression anchor = getTopmostExpression(expression); GoExpression fieldValue = GoPsiImplUtil.getRightExpression(data.getAssignment(), anchor); if (fieldValue == null) continue; GoPsiImplUtil.deleteExpressionFromAssignment(data.getAssignment(), anchor); addFieldDefinition(literalValue, expression.getIdentifier().getText(), fieldValue.getText()); } } private static void addFieldDefinition(@NotNull GoLiteralValue literalValue, @NotNull String name, @NotNull String value) { Project project = literalValue.getProject(); PsiElement newField = GoElementFactory.createLiteralValueElement(project, name, value); GoElement lastElement = getLastItem(literalValue.getElementList()); if (lastElement == null) { literalValue.addAfter(newField, literalValue.getLbrace()); } else { lastElement.add(GoElementFactory.createComma(project)); lastElement.add(newField); } } private static class Data { private final GoCompositeLit myCompositeLit; private final GoAssignmentStatement myAssignment; private final List myReferenceExpressions; public Data(@NotNull GoAssignmentStatement assignment, @NotNull GoCompositeLit compositeLit, @NotNull List referenceExpressions) { myCompositeLit = compositeLit; myAssignment = assignment; myReferenceExpressions = referenceExpressions; } public GoCompositeLit getCompositeLit() { return myCompositeLit; } public GoAssignmentStatement getAssignment() { return myAssignment; } public List getReferenceExpressions() { return myReferenceExpressions; } } } ================================================ FILE: src/com/goide/lexer/GoLexer.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.lexer; import com.goide.GoParserDefinition; import com.intellij.lexer.FlexAdapter; import com.intellij.lexer.MergingLexerAdapter; import com.intellij.psi.tree.TokenSet; public class GoLexer extends MergingLexerAdapter { public GoLexer() { super(new FlexAdapter(new _GoLexer()), TokenSet.orSet(GoParserDefinition.COMMENTS, GoParserDefinition.WHITESPACES)); } } ================================================ FILE: src/com/goide/lexer/gen_lexer.sh ================================================ java -jar ~/src/intellij-community/tools/lexer/jflex-1.7.0-SNAPSHOT.jar --skel ~/src/intellij-community/tools/lexer/idea-flex.skeleton --nobak go.flex -d ../../../../gen/com/goide/lexer/ ================================================ FILE: src/com/goide/lexer/go.flex ================================================ package com.goide.lexer; import com.intellij.lexer.FlexLexer; import com.intellij.psi.tree.IElementType; import com.goide.GoTypes; import static com.intellij.psi.TokenType.BAD_CHARACTER; import static com.goide.GoParserDefinition.*; %% %{ public _GoLexer() { this((java.io.Reader)null); } %} %class _GoLexer %implements FlexLexer, GoTypes %unicode %public %function advance %type IElementType NL = \R WS = [ \t\f] LINE_COMMENT = "//" [^\r\n]* MULTILINE_COMMENT = "/*" ( ([^"*"]|[\r\n])* ("*"+ [^"*""/"] )? )* ("*" | "*"+"/")? LETTER = [:letter:] | "_" DIGIT = [:digit:] HEX_DIGIT = [0-9A-Fa-f] INT_DIGIT = [0-9] OCT_DIGIT = [0-7] NUM_INT = "0" | ([1-9] {INT_DIGIT}*) NUM_HEX = ("0x" | "0X") {HEX_DIGIT}+ NUM_OCT = "0" {OCT_DIGIT}+ FLOAT_EXPONENT = [eE] [+-]? {DIGIT}+ NUM_FLOAT = ( ( ({DIGIT}+ "." {DIGIT}*) | ({DIGIT}* "." {DIGIT}+) ) {FLOAT_EXPONENT}?) | ({DIGIT}+ {FLOAT_EXPONENT}) IDENT = {LETTER} ({LETTER} | {DIGIT} )* STR = "\"" STRING = {STR} ( [^\"\\\n\r] | "\\" ("\\" | {STR} | {ESCAPES} | [0-8xuU] ) )* {STR}? ESCAPES = [abfnrtv] %state MAYBE_SEMICOLON %% { {WS} { return WS; } {NL}+ { return NLS; } {LINE_COMMENT} { return LINE_COMMENT; } {MULTILINE_COMMENT} { return MULTILINE_COMMENT; } {STRING} { yybegin(MAYBE_SEMICOLON); return STRING; } "'\\'" { yybegin(MAYBE_SEMICOLON); return BAD_CHARACTER; } "'" [^\\] "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'" \n "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'\\" [abfnrtv\\\'] "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'\\" {OCT_DIGIT} {3} "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'\\x" {HEX_DIGIT} {2} "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'\\u" {HEX_DIGIT} {4} "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "'\\U" {HEX_DIGIT} {8} "'"? { yybegin(MAYBE_SEMICOLON); return CHAR; } "`" [^`]* "`"? { yybegin(MAYBE_SEMICOLON); return RAW_STRING; } "..." { return TRIPLE_DOT; } "." { return DOT; } "|" { return BIT_OR; } "{" { return LBRACE; } "}" { yybegin(MAYBE_SEMICOLON); return RBRACE; } "[" { return LBRACK; } "]" { yybegin(MAYBE_SEMICOLON); return RBRACK; } "(" { return LPAREN; } ")" { yybegin(MAYBE_SEMICOLON); return RPAREN; } ":" { return COLON; } ";" { return SEMICOLON; } "," { return COMMA; } "==" { return EQ; } "=" { return ASSIGN; } "!=" { return NOT_EQ; } "!" { return NOT; } "++" { yybegin(MAYBE_SEMICOLON); return PLUS_PLUS; } "+=" { return PLUS_ASSIGN; } "+" { return PLUS; } "--" { yybegin(MAYBE_SEMICOLON); return MINUS_MINUS; } "-=" { return MINUS_ASSIGN; } "-" { return MINUS; } "||" { return COND_OR; } "|=" { return BIT_OR_ASSIGN; } "&^=" { return BIT_CLEAR_ASSIGN; } "&^" { return BIT_CLEAR; } "&&" { return COND_AND; } "&=" { return BIT_AND_ASSIGN; } "&" { return BIT_AND; } "<<=" { return SHIFT_LEFT_ASSIGN; } "<<" { return SHIFT_LEFT; } "<-" { return SEND_CHANNEL; } "<=" { return LESS_OR_EQUAL; } "<" { return LESS; } "^=" { return BIT_XOR_ASSIGN; } "^" { return BIT_XOR; } "*=" { return MUL_ASSIGN; } "*" { return MUL; } "/=" { return QUOTIENT_ASSIGN; } "/" { return QUOTIENT; } "%=" { return REMAINDER_ASSIGN; } "%" { return REMAINDER; } ">>=" { return SHIFT_RIGHT_ASSIGN; } ">>" { return SHIFT_RIGHT; } ">=" { return GREATER_OR_EQUAL; } ">" { return GREATER; } ":=" { return VAR_ASSIGN; } "break" { yybegin(MAYBE_SEMICOLON); return BREAK; } "fallthrough" { yybegin(MAYBE_SEMICOLON); return FALLTHROUGH; } "return" { yybegin(MAYBE_SEMICOLON); return RETURN ; } "continue" { yybegin(MAYBE_SEMICOLON); return CONTINUE ; } "default" { return DEFAULT; } "package" { return PACKAGE; } "func" { return FUNC; } "interface" { return INTERFACE; } "select" { return SELECT; } "case" { return CASE; } "defer" { return DEFER; } "go" { return GO; } "map" { return MAP; } "chan" { return CHAN; } "struct" { return STRUCT; } "else" { return ELSE; } "goto" { return GOTO; } "switch" { return SWITCH; } "const" { return CONST; } "if" { return IF ; } "for" { return FOR ; } "import" { return IMPORT ; } "range" { return RANGE; } "type" { return TYPE_; } "var" { return VAR; } {IDENT} { yybegin(MAYBE_SEMICOLON); return IDENTIFIER; } {NUM_FLOAT}"i" { yybegin(MAYBE_SEMICOLON); return FLOATI; } {NUM_FLOAT} { yybegin(MAYBE_SEMICOLON); return FLOAT; } {DIGIT}+"i" { yybegin(MAYBE_SEMICOLON); return DECIMALI; } {NUM_OCT} { yybegin(MAYBE_SEMICOLON); return OCT; } {NUM_HEX} { yybegin(MAYBE_SEMICOLON); return HEX; } {NUM_INT} { yybegin(MAYBE_SEMICOLON); return INT; } . { return BAD_CHARACTER; } } { {WS} { return WS; } {NL} { yybegin(YYINITIAL); yypushback(yytext().length()); return SEMICOLON_SYNTHETIC; } {LINE_COMMENT} { return LINE_COMMENT; } {MULTILINE_COMMENT} { return MULTILINE_COMMENT; } . { yybegin(YYINITIAL); yypushback(yytext().length()); } } ================================================ FILE: src/com/goide/marker/GoRecursiveCallMarkerProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.marker; import com.goide.psi.GoCallExpr; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeHighlighting.Pass; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.icons.AllIcons; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.util.Comparing; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.FunctionUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import java.util.Set; public class GoRecursiveCallMarkerProvider implements LineMarkerProvider { @Override public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement element) { return null; } @Override public void collectSlowLineMarkers(@NotNull List elements, @NotNull Collection result) { Set lines = ContainerUtil.newHashSet(); for (PsiElement element : elements) { if (element instanceof GoCallExpr) { PsiElement resolve = GoPsiImplUtil.resolveCall((GoCallExpr)element); if (resolve instanceof GoFunctionOrMethodDeclaration) { if (isRecursiveCall(element, (GoFunctionOrMethodDeclaration)resolve)) { PsiDocumentManager instance = PsiDocumentManager.getInstance(element.getProject()); Document document = instance.getDocument(element.getContainingFile()); int textOffset = element.getTextOffset(); if (document == null) continue; int lineNumber = document.getLineNumber(textOffset); if (!lines.contains(lineNumber)) { result.add(new RecursiveMethodCallMarkerInfo(element)); } lines.add(lineNumber); } } } } } private static boolean isRecursiveCall(PsiElement element, GoFunctionOrMethodDeclaration function) { return Comparing.equal(PsiTreeUtil.getParentOfType(element, GoFunctionOrMethodDeclaration.class), function); } private static class RecursiveMethodCallMarkerInfo extends LineMarkerInfo { private RecursiveMethodCallMarkerInfo(@NotNull PsiElement methodCall) { super(methodCall, methodCall.getTextRange(), AllIcons.Gutter.RecursiveMethod, Pass.UPDATE_OVERRIDDEN_MARKERS, FunctionUtil.constant("Recursive call"), null, GutterIconRenderer.Alignment.RIGHT ); } } } ================================================ FILE: src/com/goide/parser/GoParserUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.parser; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.intellij.lang.LighterASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.WhitespacesBinders; import com.intellij.lang.impl.PsiBuilderAdapter; import com.intellij.lang.parser.GeneratedParserUtilBase; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IndexingDataKeys; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.util.List; public class GoParserUtil extends GeneratedParserUtilBase { private static final Key> MODES_KEY = Key.create("MODES_KEY"); @NotNull private static TObjectIntHashMap getParsingModes(@NotNull PsiBuilder builder_) { TObjectIntHashMap flags = builder_.getUserDataUnprotected(MODES_KEY); if (flags == null) builder_.putUserDataUnprotected(MODES_KEY, flags = new TObjectIntHashMap<>()); return flags; } public static boolean consumeBlock(PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level) { PsiFile file = builder_.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY); VirtualFile data = file != null ? file.getUserData(IndexingDataKeys.VIRTUAL_FILE) : null; if (data == null) return false; int i = 0; PsiBuilder.Marker m = builder_.mark(); do { IElementType type = builder_.getTokenType(); if (type == GoTypes.TYPE_ && nextIdentifier(builder_)) { // don't count a.(type), only type m.rollbackTo(); return false; } i += type == GoTypes.LBRACE ? 1 : type == GoTypes.RBRACE ? -1 : 0; builder_.advanceLexer(); } while (i > 0 && !builder_.eof()); boolean result = i == 0; if (result) { m.drop(); } else { m.rollbackTo(); } return result; } private static boolean nextIdentifier(PsiBuilder builder_) { IElementType e; int i = 0; //noinspection StatementWithEmptyBody while ((e = builder_.rawLookup(++i)) == GoParserDefinition.WS || e == GoParserDefinition.NLS) { } return e == GoTypes.IDENTIFIER; } public static boolean emptyImportList(PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level) { PsiBuilder.Marker marker = getCurrentMarker(builder_ instanceof PsiBuilderAdapter ? ((PsiBuilderAdapter)builder_).getDelegate() : builder_); if (marker != null) { marker.setCustomEdgeTokenBinders(WhitespacesBinders.GREEDY_LEFT_BINDER, null); } return true; } public static boolean isModeOn(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode) { return getParsingModes(builder_).get(mode) > 0; } public static boolean withOn(PsiBuilder builder_, int level_, String mode, Parser parser) { return withImpl(builder_, level_, mode, true, parser, parser); } public static boolean withOff(PsiBuilder builder_, int level_, Parser parser, String... modes) { TObjectIntHashMap map = getParsingModes(builder_); TObjectIntHashMap prev = new TObjectIntHashMap<>(); for (String mode : modes) { int p = map.get(mode); if (p > 0) { map.put(mode, 0); prev.put(mode, p); } } boolean result = parser.parse(builder_, level_); prev.forEachEntry((mode, p) -> { map.put(mode, p); return true; }); return result; } private static boolean withImpl(PsiBuilder builder_, int level_, String mode, boolean onOff, Parser whenOn, Parser whenOff) { TObjectIntHashMap map = getParsingModes(builder_); int prev = map.get(mode); boolean change = ((prev & 1) == 0) == onOff; if (change) map.put(mode, prev << 1 | (onOff ? 1 : 0)); boolean result = (change ? whenOn : whenOff).parse(builder_, level_); if (change) map.put(mode, prev); return result; } public static boolean isModeOff(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode) { return getParsingModes(builder_).get(mode) == 0; } public static boolean prevIsType(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level) { LighterASTNode marker = builder_.getLatestDoneMarker(); IElementType type = marker != null ? marker.getTokenType() : null; return type == GoTypes.ARRAY_OR_SLICE_TYPE || type == GoTypes.MAP_TYPE || type == GoTypes.STRUCT_TYPE; } public static boolean keyOrValueExpression(@NotNull PsiBuilder builder_, int level) { PsiBuilder.Marker m = enter_section_(builder_); boolean r = GoParser.Expression(builder_, level + 1, -1); if (!r) r = GoParser.LiteralValue(builder_, level + 1); IElementType type = r && builder_.getTokenType() == GoTypes.COLON ? GoTypes.KEY : GoTypes.VALUE; exit_section_(builder_, m, type, r); return r; } public static boolean enterMode(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode) { TObjectIntHashMap flags = getParsingModes(builder_); if (!flags.increment(mode)) flags.put(mode, 1); return true; } private static boolean exitMode(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode, boolean safe) { TObjectIntHashMap flags = getParsingModes(builder_); int count = flags.get(mode); if (count == 1) flags.remove(mode); else if (count > 1) flags.put(mode, count - 1); else if (!safe) builder_.error("Could not exit inactive '" + mode + "' mode at offset " + builder_.getCurrentOffset()); return true; } public static boolean exitMode(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode) { return exitMode(builder_, level,mode, false); } public static boolean exitModeSafe(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level, String mode) { return exitMode(builder_, level,mode, true); } public static boolean isBuiltin(@NotNull PsiBuilder builder_, @SuppressWarnings("UnusedParameters") int level) { LighterASTNode marker = builder_.getLatestDoneMarker(); if (marker == null) return false; String text = String.valueOf(builder_.getOriginalText().subSequence(marker.getStartOffset(), marker.getEndOffset())).trim(); return "make".equals(text) || "new".equals(text); } @Nullable private static PsiBuilder.Marker getCurrentMarker(@NotNull PsiBuilder builder_) { try { for (Field field : builder_.getClass().getDeclaredFields()) { if ("MyList".equals(field.getType().getSimpleName())) { field.setAccessible(true); //noinspection unchecked return ContainerUtil.getLastItem((List)field.get(builder_)); } } } catch (Exception ignored) {} return null; } public static boolean nextTokenIsSmart(PsiBuilder builder, IElementType token) { return nextTokenIsFast(builder, token) || ErrorState.get(builder).completionState != null; } public static boolean nextTokenIsSmart(PsiBuilder builder, IElementType... tokens) { return nextTokenIsFast(builder, tokens) || ErrorState.get(builder).completionState != null; } } ================================================ FILE: src/com/goide/project/GoApplicationLibrariesService.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.GoLibrariesState; import com.goide.sdk.GoSdkUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import org.jetbrains.annotations.NotNull; @State( name = GoConstants.GO_LIBRARIES_SERVICE_NAME, storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/" + GoConstants.GO_LIBRARIES_CONFIG_FILE) ) public class GoApplicationLibrariesService extends GoLibrariesService { @NotNull @Override protected GoApplicationLibrariesState createState() { return new GoApplicationLibrariesState(); } public static GoApplicationLibrariesService getInstance() { return ServiceManager.getService(GoApplicationLibrariesService.class); } public boolean isUseGoPathFromSystemEnvironment() { return myState.isUseGoPathFromSystemEnvironment(); } public void setUseGoPathFromSystemEnvironment(boolean useGoPathFromSystemEnvironment) { if (myState.isUseGoPathFromSystemEnvironment() != useGoPathFromSystemEnvironment) { myState.setUseGoPathFromSystemEnvironment(useGoPathFromSystemEnvironment); if (!GoSdkUtil.getGoPathsRootsFromEnvironment().isEmpty()) { incModificationCount(); ApplicationManager.getApplication().getMessageBus().syncPublisher(LIBRARIES_TOPIC).librariesChanged(getLibraryRootUrls()); } } } public static class GoApplicationLibrariesState extends GoLibrariesState { private boolean myUseGoPathFromSystemEnvironment = true; public boolean isUseGoPathFromSystemEnvironment() { return myUseGoPathFromSystemEnvironment; } public void setUseGoPathFromSystemEnvironment(boolean useGoPathFromSystemEnvironment) { myUseGoPathFromSystemEnvironment = useGoPathFromSystemEnvironment; } } } ================================================ FILE: src/com/goide/project/GoBuildTargetSettings.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.util.ArrayUtil; import com.intellij.util.ThreeState; import com.intellij.util.xmlb.annotations.Tag; import org.jetbrains.annotations.NotNull; import java.util.Arrays; @Tag("buildTags") public class GoBuildTargetSettings extends SimpleModificationTracker { public static final String ANY_COMPILER = "Any"; public static final String DEFAULT = "default"; @NotNull public String os = DEFAULT; @NotNull public String arch = DEFAULT; @NotNull public ThreeState cgo = ThreeState.UNSURE; @NotNull public String compiler = ANY_COMPILER; @NotNull public String goVersion = DEFAULT; @NotNull public String[] customFlags = ArrayUtil.EMPTY_STRING_ARRAY; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GoBuildTargetSettings)) return false; GoBuildTargetSettings settings = (GoBuildTargetSettings)o; if (!os.equals(settings.os)) return false; if (!arch.equals(settings.arch)) return false; if (cgo != settings.cgo) return false; if (!compiler.equals(settings.compiler)) return false; if (!goVersion.equals(settings.goVersion)) return false; return Arrays.equals(customFlags, settings.customFlags); } @Override public int hashCode() { int result = os.hashCode(); result = 31 * result + arch.hashCode(); result = 31 * result + cgo.hashCode(); result = 31 * result + compiler.hashCode(); result = 31 * result + goVersion.hashCode(); result = 31 * result + Arrays.hashCode(customFlags); return result; } } ================================================ FILE: src/com/goide/project/GoExcludedPathsSettings.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @State( name = "GoExcludedPaths", storages = { @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/goExcludedPaths.xml", scheme = StorageScheme.DIRECTORY_BASED) } ) public class GoExcludedPathsSettings extends SimpleModificationTracker implements PersistentStateComponent { private String[] myExcludedPackages = ArrayUtil.EMPTY_STRING_ARRAY; public static GoExcludedPathsSettings getInstance(Project project) { return ServiceManager.getService(project, GoExcludedPathsSettings.class); } @Nullable @Override public GoExcludedPathsSettings getState() { return this; } @Override public void loadState(GoExcludedPathsSettings state) { XmlSerializerUtil.copyBean(state, this); } public String[] getExcludedPackages() { return myExcludedPackages; } public void setExcludedPackages(String... excludedPackages) { myExcludedPackages = excludedPackages; incModificationCount(); } public boolean isExcluded(@Nullable String importPath) { if (importPath == null) { return false; } for (String excludedPath : myExcludedPackages) { if (FileUtil.isAncestor(excludedPath, importPath, false)) return true; } return false; } public void excludePath(@NotNull String importPath) { setExcludedPackages(ArrayUtil.append(myExcludedPackages, importPath)); } } ================================================ FILE: src/com/goide/project/GoLibrariesService.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoLibrariesState; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ModificationTracker; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.Topic; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Set; public abstract class GoLibrariesService extends SimpleModificationTracker implements PersistentStateComponent { public static final Topic LIBRARIES_TOPIC = Topic.create("libraries changes", LibrariesListener.class); protected final T myState = createState(); @NotNull @Override public T getState() { return myState; } @Override public void loadState(T state) { XmlSerializerUtil.copyBean(state, myState); } @NotNull protected T createState() { //noinspection unchecked return (T)new GoLibrariesState(); } @NotNull public static Collection getUserDefinedLibraries(@NotNull Module module) { Set result = ContainerUtil.newLinkedHashSet(); result.addAll(goRootsFromUrls(GoModuleLibrariesService.getInstance(module).getLibraryRootUrls())); result.addAll(getUserDefinedLibraries(module.getProject())); return result; } @NotNull public static Collection getUserDefinedLibraries(@NotNull Project project) { Set result = ContainerUtil.newLinkedHashSet(); result.addAll(goRootsFromUrls(GoProjectLibrariesService.getInstance(project).getLibraryRootUrls())); result.addAll(getUserDefinedLibraries()); return result; } @NotNull public static Collection getUserDefinedLibraries() { return goRootsFromUrls(GoApplicationLibrariesService.getInstance().getLibraryRootUrls()); } @NotNull public static ModificationTracker[] getModificationTrackers(@NotNull Project project, @Nullable Module module) { return module != null ? new ModificationTracker[]{GoModuleLibrariesService.getInstance(module), GoProjectLibrariesService.getInstance(module.getProject()), GoApplicationLibrariesService.getInstance()} : new ModificationTracker[]{GoProjectLibrariesService.getInstance(project), GoApplicationLibrariesService.getInstance()}; } public void setLibraryRootUrls(@NotNull String... libraryRootUrls) { setLibraryRootUrls(Arrays.asList(libraryRootUrls)); } public void setLibraryRootUrls(@NotNull Collection libraryRootUrls) { if (!myState.getUrls().equals(libraryRootUrls)) { myState.setUrls(libraryRootUrls); incModificationCount(); ApplicationManager.getApplication().getMessageBus().syncPublisher(LIBRARIES_TOPIC).librariesChanged(libraryRootUrls); } } @NotNull public Collection getLibraryRootUrls() { return myState.getUrls(); } @NotNull private static Collection goRootsFromUrls(@NotNull Collection urls) { return ContainerUtil.mapNotNull(urls, url -> VirtualFileManager.getInstance().findFileByUrl(url)); } public interface LibrariesListener { void librariesChanged(@NotNull Collection newRootUrls); } } ================================================ FILE: src/com/goide/project/GoModuleLibrariesInitializer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.configuration.GoLibrariesConfigurableProvider; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.goide.util.GoUtil; import com.intellij.ProjectTopics; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleComponent; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.OrderEntryUtil; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vfs.*; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.search.FilenameIndex; import com.intellij.util.Alarm; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import javax.swing.event.HyperlinkEvent; import java.util.Collection; import java.util.List; import java.util.Set; public class GoModuleLibrariesInitializer implements ModuleComponent { private static final String GO_LIB_NAME = "GOPATH"; private static final String GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN = "go.libraries.notification.had.been.shown"; private static final String GO_VENDORING_NOTIFICATION_HAD_BEEN_SHOWN = "go.vendoring.notification.had.been.shown"; private static final int UPDATE_DELAY = 300; private static boolean isTestingMode; private final Alarm myAlarm; private final MessageBusConnection myConnection; private boolean myModuleInitialized; @NotNull private final Set myLastHandledGoPathSourcesRoots = ContainerUtil.newHashSet(); @NotNull private final Set myLastHandledExclusions = ContainerUtil.newHashSet(); @NotNull private final Set myWatchedRequests = ContainerUtil.newHashSet(); @NotNull private final Module myModule; @NotNull private final VirtualFileAdapter myFilesListener = new VirtualFileAdapter() { @Override public void fileCreated(@NotNull VirtualFileEvent event) { if (GoConstants.VENDOR.equals(event.getFileName()) && event.getFile().isDirectory()) { showVendoringNotification(); } } }; @TestOnly public static void setTestingMode(@NotNull Disposable disposable) { isTestingMode = true; Disposer.register(disposable, () -> { //noinspection AssignmentToStaticFieldFromInstanceMethod isTestingMode = false; }); } public GoModuleLibrariesInitializer(@NotNull Module module) { myModule = module; myAlarm = ApplicationManager.getApplication().isUnitTestMode() ? new Alarm() : new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myModule); myConnection = myModule.getMessageBus().connect(); } @Override public void moduleAdded() { if (!myModuleInitialized) { myConnection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { scheduleUpdate(); } }); myConnection.subscribe(GoLibrariesService.LIBRARIES_TOPIC, newRootUrls -> scheduleUpdate()); Project project = myModule.getProject(); StartupManager.getInstance(project).runWhenProjectIsInitialized(() -> { if (!project.isDisposed() && !myModule.isDisposed()) { for (PsiFileSystemItem vendor : FilenameIndex.getFilesByName(project, GoConstants.VENDOR, GoUtil.moduleScope(myModule), true)) { if (vendor.isDirectory()) { showVendoringNotification(); break; } } } }); VirtualFileManager.getInstance().addVirtualFileListener(myFilesListener); } scheduleUpdate(0); myModuleInitialized = true; } private void scheduleUpdate() { scheduleUpdate(UPDATE_DELAY); } private void scheduleUpdate(int delay) { myAlarm.cancelAllRequests(); UpdateRequest updateRequest = new UpdateRequest(); if (isTestingMode) { ApplicationManager.getApplication().invokeLater(updateRequest); } else { myAlarm.addRequest(updateRequest, delay); } } private void attachLibraries(@NotNull Collection libraryRoots, Set exclusions) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!libraryRoots.isEmpty()) { ApplicationManager.getApplication().runWriteAction(() -> { ModuleRootManager model = ModuleRootManager.getInstance(myModule); LibraryOrderEntry goLibraryEntry = OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName()); if (goLibraryEntry != null && goLibraryEntry.isValid()) { Library library = goLibraryEntry.getLibrary(); if (library != null && !((LibraryEx)library).isDisposed()) { fillLibrary(library, libraryRoots, exclusions); } } else { LibraryTable libraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject()); Library library = libraryTable.createLibrary(getLibraryName()); fillLibrary(library, libraryRoots, exclusions); ModuleRootModificationUtil.addDependency(myModule, library); } }); showNotification(myModule.getProject()); } else { removeLibraryIfNeeded(); } } public String getLibraryName() { return GO_LIB_NAME + " <" + myModule.getName() + ">"; } private static void fillLibrary(@NotNull Library library, @NotNull Collection libraryRoots, Set exclusions) { ApplicationManager.getApplication().assertWriteAccessAllowed(); Library.ModifiableModel libraryModel = library.getModifiableModel(); for (String root : libraryModel.getUrls(OrderRootType.CLASSES)) { libraryModel.removeRoot(root, OrderRootType.CLASSES); } for (String root : libraryModel.getUrls(OrderRootType.SOURCES)) { libraryModel.removeRoot(root, OrderRootType.SOURCES); } for (VirtualFile libraryRoot : libraryRoots) { libraryModel.addRoot(libraryRoot, OrderRootType.CLASSES); // in order to consider GOPATH as library and show it in Ext. Libraries libraryModel.addRoot(libraryRoot, OrderRootType.SOURCES); // in order to find usages inside GOPATH } for (VirtualFile root : exclusions) { ((LibraryEx.ModifiableModelEx)libraryModel).addExcludedRoot(root.getUrl()); } libraryModel.commit(); } private void removeLibraryIfNeeded() { ApplicationManager.getApplication().assertIsDispatchThread(); ModifiableModelsProvider modelsProvider = ModifiableModelsProvider.SERVICE.getInstance(); ModifiableRootModel model = modelsProvider.getModuleModifiableModel(myModule); LibraryOrderEntry goLibraryEntry = OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName()); if (goLibraryEntry != null) { ApplicationManager.getApplication().runWriteAction(() -> { Library library = goLibraryEntry.getLibrary(); if (library != null) { LibraryTable table = library.getTable(); if (table != null) { table.removeLibrary(library); model.removeOrderEntry(goLibraryEntry); modelsProvider.commitModuleModifiableModel(model); } } else { modelsProvider.disposeModuleModifiableModel(model); } }); } else { ApplicationManager.getApplication().runWriteAction(() -> modelsProvider.disposeModuleModifiableModel(model)); } } private static void showNotification(@NotNull Project project) { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); PropertiesComponent projectPropertiesComponent = PropertiesComponent.getInstance(project); boolean shownAlready; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (propertiesComponent) { shownAlready = propertiesComponent.getBoolean(GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, false) || projectPropertiesComponent.getBoolean(GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, false); if (!shownAlready) { propertiesComponent.setValue(GO_LIBRARIES_NOTIFICATION_HAD_BEEN_SHOWN, String.valueOf(true)); } } if (!shownAlready) { NotificationListener.Adapter notificationListener = new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED && "configure".equals(event.getDescription())) { GoLibrariesConfigurableProvider.showModulesConfigurable(project); } } }; Notification notification = GoConstants.GO_NOTIFICATION_GROUP.createNotification("GOPATH was detected", "We've detected some libraries from your GOPATH.\n" + "You may want to add extra libraries in Go Libraries configuration.", NotificationType.INFORMATION, notificationListener); Notifications.Bus.notify(notification, project); } } private void showVendoringNotification() { if (!myModuleInitialized || myModule.isDisposed()) { return; } Project project = myModule.getProject(); String version = GoSdkService.getInstance(project).getSdkVersion(myModule); if (!GoVendoringUtil.supportsVendoring(version) || GoVendoringUtil.supportsVendoringByDefault(version)) { return; } if (GoModuleSettings.getInstance(myModule).getVendoringEnabled() != ThreeState.UNSURE) { return; } PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project); boolean shownAlready; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (propertiesComponent) { shownAlready = propertiesComponent.getBoolean(GO_VENDORING_NOTIFICATION_HAD_BEEN_SHOWN, false); if (!shownAlready) { propertiesComponent.setValue(GO_VENDORING_NOTIFICATION_HAD_BEEN_SHOWN, String.valueOf(true)); } } if (!shownAlready) { NotificationListener.Adapter notificationListener = new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED && "configure".equals(event.getDescription())) { GoModuleSettings.showModulesConfigurable(project); } } }; Notification notification = GoConstants.GO_NOTIFICATION_GROUP.createNotification("Vendoring usage is detected", "

    vendor directory usually means that project uses Go Vendor Experiment.

    \n" + "

    Selected Go SDK version support vendoring but it's disabled by default.

    \n" + "

    You may want to explicitly enabled Go Vendor Experiment in the project settings.

    ", NotificationType.INFORMATION, notificationListener); Notifications.Bus.notify(notification, project); } } @Override public void initComponent() { } @Override public void disposeComponent() { Disposer.dispose(myConnection); Disposer.dispose(myAlarm); VirtualFileManager.getInstance().removeVirtualFileListener(myFilesListener); myLastHandledGoPathSourcesRoots.clear(); myLastHandledExclusions.clear(); LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests); myWatchedRequests.clear(); } @Override public void projectOpened() { } @Override public void projectClosed() { disposeComponent(); } @NotNull @Override public String getComponentName() { return getClass().getName(); } private class UpdateRequest implements Runnable { @Override public void run() { Project project = myModule.getProject(); if (GoSdkService.getInstance(project).isGoModule(myModule)) { synchronized (myLastHandledGoPathSourcesRoots) { Collection goPathSourcesRoots = GoSdkUtil.getGoPathSources(project, myModule); Set excludeRoots = ContainerUtil.newHashSet(ProjectRootManager.getInstance(project).getContentRoots()); ProgressIndicatorProvider.checkCanceled(); if (!myLastHandledGoPathSourcesRoots.equals(goPathSourcesRoots) || !myLastHandledExclusions.equals(excludeRoots)) { Collection includeRoots = gatherIncludeRoots(goPathSourcesRoots, excludeRoots); ApplicationManager.getApplication().invokeLater(() -> { if (!myModule.isDisposed() && GoSdkService.getInstance(project).isGoModule(myModule)) { attachLibraries(includeRoots, excludeRoots); } }); myLastHandledGoPathSourcesRoots.clear(); myLastHandledGoPathSourcesRoots.addAll(goPathSourcesRoots); myLastHandledExclusions.clear(); myLastHandledExclusions.addAll(excludeRoots); List paths = ContainerUtil.map(goPathSourcesRoots, VirtualFile::getPath); myWatchedRequests.clear(); myWatchedRequests.addAll(LocalFileSystem.getInstance().addRootsToWatch(paths, true)); } } } else { synchronized (myLastHandledGoPathSourcesRoots) { LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests); myLastHandledGoPathSourcesRoots.clear(); myLastHandledExclusions.clear(); ApplicationManager.getApplication().invokeLater(() -> { if (!myModule.isDisposed() && GoSdkService.getInstance(project).isGoModule(myModule)) { removeLibraryIfNeeded(); } }); } } } } @NotNull private static Collection gatherIncludeRoots(Collection goPathSourcesRoots, Set excludeRoots) { Collection includeRoots = ContainerUtil.newHashSet(); for (VirtualFile goPathSourcesDirectory : goPathSourcesRoots) { ProgressIndicatorProvider.checkCanceled(); boolean excludedRootIsAncestor = false; for (VirtualFile excludeRoot : excludeRoots) { ProgressIndicatorProvider.checkCanceled(); if (VfsUtilCore.isAncestor(excludeRoot, goPathSourcesDirectory, false)) { excludedRootIsAncestor = true; break; } } if (excludedRootIsAncestor) { continue; } for (VirtualFile file : goPathSourcesDirectory.getChildren()) { ProgressIndicatorProvider.checkCanceled(); if (file.isDirectory() && !excludeRoots.contains(file)) { includeRoots.add(file); } } } return includeRoots; } } ================================================ FILE: src/com/goide/project/GoModuleLibrariesService.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.GoLibrariesState; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleServiceManager; import org.jetbrains.annotations.NotNull; @State( name = GoConstants.GO_LIBRARIES_SERVICE_NAME, storages = @Storage(file = StoragePathMacros.MODULE_FILE) ) public class GoModuleLibrariesService extends GoLibrariesService { public static GoModuleLibrariesService getInstance(@NotNull Module module) { return ModuleServiceManager.getService(module, GoModuleLibrariesService.class); } } ================================================ FILE: src/com/goide/project/GoModuleSettings.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.configuration.GoConfigurableProvider; import com.goide.configuration.GoModuleSettingsConfigurable; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleServiceManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.util.ThreeState; import com.intellij.util.messages.Topic; import com.intellij.util.xmlb.XmlSerializerUtil; import com.intellij.util.xmlb.annotations.OptionTag; import com.intellij.util.xmlb.annotations.Property; import org.jetbrains.annotations.NotNull; @State(name = GoConstants.GO_MODULE_SESTTINGS_SERVICE_NAME, storages = @Storage(file = StoragePathMacros.MODULE_FILE)) public class GoModuleSettings implements PersistentStateComponent { public static final Topic TOPIC = Topic.create("build target changed", BuildTargetListener.class); @NotNull private final GoModuleSettingsState myState = new GoModuleSettingsState(); @NotNull private final Module myModule; public GoModuleSettings(@NotNull Module module) { myModule = module; } public static GoModuleSettings getInstance(@NotNull Module module) { return ModuleServiceManager.getService(module, GoModuleSettings.class); } @NotNull public ThreeState getVendoringEnabled() { return myState.vendoring; } public void setVendoringEnabled(@NotNull ThreeState vendoringEnabled) { if (vendoringEnabled != myState.vendoring) { cleanResolveCaches(); } myState.vendoring = vendoringEnabled; } @NotNull public GoBuildTargetSettings getBuildTargetSettings() { return myState.buildTargetSettings; } public void setBuildTargetSettings(@NotNull GoBuildTargetSettings buildTargetSettings) { if (!buildTargetSettings.equals(myState.buildTargetSettings)) { XmlSerializerUtil.copyBean(buildTargetSettings, myState.buildTargetSettings); if (!myModule.isDisposed()) { myModule.getProject().getMessageBus().syncPublisher(TOPIC).changed(myModule); } cleanResolveCaches(); myState.buildTargetSettings.incModificationCount(); } } private void cleanResolveCaches() { Project project = myModule.getProject(); if (!project.isDisposed()) { ResolveCache.getInstance(project).clearCache(true); DaemonCodeAnalyzer.getInstance(project).restart(); } } @NotNull @Override public GoModuleSettingsState getState() { return myState; } @Override public void loadState(GoModuleSettingsState state) { XmlSerializerUtil.copyBean(state, myState); } public interface BuildTargetListener { void changed(@NotNull Module module); } static class GoModuleSettingsState { @OptionTag @NotNull private ThreeState vendoring = ThreeState.UNSURE; @Property(surroundWithTag = false) @NotNull private GoBuildTargetSettings buildTargetSettings = new GoBuildTargetSettings(); } public static void showModulesConfigurable(@NotNull Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!project.isDisposed()) { ShowSettingsUtil.getInstance().editConfigurable(project, new GoConfigurableProvider.GoProjectSettingsConfigurable(project)); } } public static void showModulesConfigurable(@NotNull Module module) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!module.isDisposed()) { ShowSettingsUtil.getInstance().editConfigurable(module.getProject(), new GoModuleSettingsConfigurable(module, true)); } } } ================================================ FILE: src/com/goide/project/GoProjectLibrariesService.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.GoLibrariesState; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; @State( name = GoConstants.GO_LIBRARIES_SERVICE_NAME, storages = { @Storage(id = "default", file = StoragePathMacros.PROJECT_FILE), @Storage(id = "dir", file = StoragePathMacros.PROJECT_CONFIG_DIR + "/" + GoConstants.GO_LIBRARIES_CONFIG_FILE, scheme = StorageScheme.DIRECTORY_BASED) } ) public class GoProjectLibrariesService extends GoLibrariesService { public static GoProjectLibrariesService getInstance(@NotNull Project project) { return ServiceManager.getService(project, GoProjectLibrariesService.class); } } ================================================ FILE: src/com/goide/project/GoProjectStructureDetector.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.GoConstants; import com.goide.GoModuleType; import com.goide.sdk.GoSdkType; import com.intellij.ide.util.importProject.ModuleDescriptor; import com.intellij.ide.util.importProject.ProjectDescriptor; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.ProjectJdkForModuleStep; import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot; import com.intellij.ide.util.projectWizard.importSources.ProjectFromSourcesBuilder; import com.intellij.ide.util.projectWizard.importSources.ProjectStructureDetector; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; public class GoProjectStructureDetector extends ProjectStructureDetector { @NotNull @Override public DirectoryProcessingResult detectRoots(@NotNull File dir, @NotNull File[] children, @NotNull File base, @NotNull List result) { Pattern pattern = Pattern.compile(".*\\.go"); List filesByMask = FileUtil.findFilesByMask(pattern, base); if (!filesByMask.isEmpty()) { result.add(new DetectedProjectRoot(dir) { @NotNull @Override public String getRootTypeName() { return GoConstants.GO; } }); } return DirectoryProcessingResult.SKIP_CHILDREN; } @Override public void setupProjectStructure(@NotNull Collection roots, @NotNull ProjectDescriptor projectDescriptor, @NotNull ProjectFromSourcesBuilder builder) { if (!roots.isEmpty() && !builder.hasRootsFromOtherDetectors(this)) { if (projectDescriptor.getModules().isEmpty()) { projectDescriptor.setModules(roots.stream() .map(root -> new ModuleDescriptor(root.getDirectory(), GoModuleType.getInstance(), ContainerUtil.emptyList())).collect(Collectors.toList())); } } } @NotNull @Override public List createWizardSteps(@NotNull ProjectFromSourcesBuilder builder, ProjectDescriptor projectDescriptor, Icon stepIcon) { ProjectJdkForModuleStep projectJdkForModuleStep = new ProjectJdkForModuleStep(builder.getContext(), GoSdkType.getInstance()); return Collections.singletonList(projectJdkForModuleStep); } } ================================================ FILE: src/com/goide/project/GoVendoringUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project; import com.goide.sdk.GoSdkService; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ThreeState; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nullable; public class GoVendoringUtil { public static boolean supportsVendoringByDefault(@Nullable String sdkVersion) { if (sdkVersion == null || sdkVersion.length() < 3) { return false; } return StringUtil.parseDouble(sdkVersion.substring(0, 3), 0) >= 1.6; } public static boolean vendoringCanBeDisabled(@Nullable String sdkVersion) { if (sdkVersion == null || sdkVersion.length() < 3) { return true; } return StringUtil.parseDouble(sdkVersion.substring(0, 3), 0) < 1.7; } public static boolean supportsInternalPackages(@Nullable String sdkVersion) { if (sdkVersion == null || sdkVersion.length() < 3) { return false; } return StringUtil.parseDouble(sdkVersion.substring(0, 3), 0) >= 1.5; } public static boolean supportsSdkInternalPackages(@Nullable String sdkVersion) { if (sdkVersion == null || sdkVersion.length() < 3) { return false; } return StringUtil.parseDouble(sdkVersion.substring(0, 3), 0) >= 1.4; } public static boolean supportsVendoring(@Nullable String sdkVersion) { if (sdkVersion == null || sdkVersion.length() < 3) { return false; } return StringUtil.parseDouble(sdkVersion.substring(0, 3), 0) >= 1.4; } @Contract("null -> false") public static boolean isVendoringEnabled(@Nullable Module module) { if (module == null) { return false; } String version = GoSdkService.getInstance(module.getProject()).getSdkVersion(module); if (!vendoringCanBeDisabled(version)) { return true; } ThreeState vendorSupportEnabled = GoModuleSettings.getInstance(module).getVendoringEnabled(); if (vendorSupportEnabled == ThreeState.UNSURE) { return supportsVendoring(version) && supportsVendoringByDefault(version); } return vendorSupportEnabled.toBoolean(); } } ================================================ FILE: src/com/goide/project/migration/GoBuildTagsSettingsConverterProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project.migration; import com.goide.GoConstants; import com.goide.project.GoBuildTargetSettings; import com.intellij.conversion.*; import com.intellij.ide.impl.convert.JDomConvertingUtil; import com.intellij.util.xmlb.XmlSerializer; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.serialization.JDomSerializationUtil; import java.io.File; import java.util.Collection; import java.util.Collections; public class GoBuildTagsSettingsConverterProvider extends ConverterProvider { protected GoBuildTagsSettingsConverterProvider() { super("go-build-tags-settings"); } @NotNull @Override public String getConversionDescription() { return "Go project settings storing mechanism has been changed so project and its modules need to be updated"; } @NotNull @Override public ProjectConverter createConverter(@NotNull ConversionContext context) { return new ProjectConverter() { private GoBuildTargetSettings newSettings; @NotNull private File getGoBuildFlagsFile() {return new File(context.getSettingsBaseDir(), "goBuildFlags.xml");} @Nullable @Override public ConversionProcessor createProjectFileConverter() { return new ConversionProcessor() { @Override public boolean isConversionNeeded(@NotNull ProjectSettings settings) { Element oldSettings = JDomSerializationUtil.findComponent(settings.getRootElement(), "GoBuildFlags"); return oldSettings != null; } @Override public void process(@NotNull ProjectSettings settings) throws CannotConvertException { Element oldSettings = JDomSerializationUtil.findComponent(settings.getRootElement(), "GoBuildFlags"); if (oldSettings != null) { newSettings = XmlSerializer.deserialize(oldSettings, GoBuildTargetSettings.class); oldSettings.detach(); } } }; } @Override public Collection getAdditionalAffectedFiles() { return Collections.singletonList(getGoBuildFlagsFile()); } @Override public boolean isConversionNeeded() { return getGoBuildFlagsFile().exists(); } @Override public void preProcessingFinished() throws CannotConvertException { File oldSettingsFile = getGoBuildFlagsFile(); if (oldSettingsFile.exists()) { Element oldSettingsRoot = JDomConvertingUtil.loadDocument(oldSettingsFile).getRootElement(); Element buildFlagsSettings = JDomSerializationUtil.findComponent(oldSettingsRoot, "GoBuildFlags"); if (buildFlagsSettings != null) { newSettings = XmlSerializer.deserialize(buildFlagsSettings, GoBuildTargetSettings.class); buildFlagsSettings.detach(); //noinspection ResultOfMethodCallIgnored oldSettingsFile.delete(); } } } @Nullable @Override public ConversionProcessor createModuleFileConverter() { return new ConversionProcessor() { @Override public boolean isConversionNeeded(@NotNull ModuleSettings settings) { return getGoBuildFlagsFile().exists(); } @Override public void process(@NotNull ModuleSettings settings) throws CannotConvertException { Element rootElement = settings.getRootElement(); Element goComponent = JDomSerializationUtil.findOrCreateComponentElement(rootElement, GoConstants.GO_MODULE_SESTTINGS_SERVICE_NAME); Element buildTags = XmlSerializer.serialize(newSettings); Element existingBuildTags = goComponent.getChild(buildTags.getName()); if (existingBuildTags != null) { existingBuildTags.detach(); } goComponent.addContent(buildTags); } }; } }; } } ================================================ FILE: src/com/goide/project/migration/GoProjectModelConverterProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.project.migration; import com.goide.GoConstants; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoProjectLibrariesService; import com.goide.sdk.GoSdkType; import com.goide.sdk.GoSdkUtil; import com.intellij.conversion.*; import com.intellij.ide.impl.convert.JDomConvertingUtil; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.impl.ProjectRootManagerImpl; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.XmlSerializer; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.serialization.JDomSerializationUtil; import java.io.File; import java.io.IOException; import java.util.Collection; public class GoProjectModelConverterProvider extends ConverterProvider { private static final String PROJECT_ROOT_MANAGER = "ProjectRootManager"; protected GoProjectModelConverterProvider() { super("go-project-model"); } @NotNull @Override public String getConversionDescription() { return "Go project model has been changed so project and its modules need to be updated"; } @NotNull @Override public ProjectConverter createConverter(@NotNull ConversionContext context) { return new ProjectConverter() { private final Collection additionalCreatedFiles = ContainerUtil.newArrayList(); private final Collection additionalAffectedFiles = ContainerUtil.newArrayList(); @Nullable @Override public ConversionProcessor createProjectFileConverter() { return new ProjectFileConverter(); } @Nullable @Override public ConversionProcessor createModuleFileConverter() { return new ModuleFileConverter(); } @Nullable @Override public ConversionProcessor createRunConfigurationsConverter() { return new RunConfigurationsConverter(); } @Override public boolean isConversionNeeded() { Element component = getProjectRootManager(context); return component != null && isGoSdkType(component.getAttributeValue(ProjectRootManagerImpl.PROJECT_JDK_TYPE_ATTR)); } @Override public void preProcessingFinished() throws CannotConvertException { Element component = getProjectRootManager(context); if (component != null) { try { File miscFile = miscFile(context); updateSdkType(miscFile, component); additionalAffectedFiles.add(miscFile); File oldGoSettings = new File(context.getSettingsBaseDir(), "go_settings.xml"); if (oldGoSettings.exists()) { Element oldGoSettingsRoot = rootElement(oldGoSettings); if (isAttachProjectDirToLibraries(oldGoSettingsRoot)) { File librariesConfigFile = new File(context.getSettingsBaseDir(), GoConstants.GO_LIBRARIES_CONFIG_FILE); if (librariesConfigFile.exists()) { //noinspection ResultOfMethodCallIgnored librariesConfigFile.delete(); additionalAffectedFiles.add(librariesConfigFile); } else { additionalCreatedFiles.add(librariesConfigFile); } FileUtil.writeToFile(librariesConfigFile, "\n"); addProjectDirToLibraries(librariesConfigFile, rootElement(librariesConfigFile)); } } //noinspection ResultOfMethodCallIgnored oldGoSettings.delete(); } catch (IOException e) { throw new CannotConvertException("Cannot convert go project", e); } } convertSdks(); } @NotNull @Override public Collection getAdditionalAffectedFiles() { return additionalAffectedFiles; } @NotNull @Override public Collection getCreatedFiles() { return additionalCreatedFiles; } }; } @NotNull private static Element rootElement(@NotNull File file) throws CannotConvertException { return JDomConvertingUtil.loadDocument(file).getRootElement(); } private static class ProjectFileConverter extends ConversionProcessor { @Override public boolean isConversionNeeded(@NotNull ProjectSettings settings) { Element projectRootManager = getProjectRootManager(settings.getRootElement()); return projectRootManager != null && isGoSdkType(projectRootManager.getAttributeValue(ProjectRootManagerImpl.PROJECT_JDK_TYPE_ATTR)); } @Override public void process(@NotNull ProjectSettings settings) throws CannotConvertException { Element projectRootManager = getProjectRootManager(settings.getRootElement()); if (projectRootManager != null) { updateSdkType(settings.getFile(), projectRootManager); } if (isAttachProjectDirToLibraries(settings.getRootElement())) { addProjectDirToLibraries(settings.getFile(), settings.getRootElement()); } convertSdks(); } } private static class ModuleFileConverter extends ConversionProcessor { @Override public boolean isConversionNeeded(@NotNull ModuleSettings settings) { if ("GO_APP_ENGINE_MODULE".equals(settings.getModuleType())) return true; for (Element element : settings.getOrderEntries()) { if (isGoSdkType(element.getAttributeValue("jdkType"))) { return true; } } return false; } @Override public void process(@NotNull ModuleSettings settings) throws CannotConvertException { settings.setModuleType(GoConstants.MODULE_TYPE_ID); for (Element element : settings.getOrderEntries()) { if (isGoSdkType(element.getAttributeValue("jdkType"))) { element.setAttribute("jdkType", GoConstants.SDK_TYPE_ID); } } convertSdks(); } } private static Element getProjectRootManager(@NotNull ConversionContext context) { File miscFile = miscFile(context); try { if (miscFile.exists()) { return getProjectRootManager(rootElement(miscFile)); } } catch (CannotConvertException e) { return null; } return null; } @Nullable private static Element getProjectRootManager(@Nullable Element rootElement) { return rootElement != null ? JDomSerializationUtil.findComponent(rootElement, PROJECT_ROOT_MANAGER) : null; } private static void updateSdkType(@NotNull File file, @NotNull Element projectRootManager) throws CannotConvertException { projectRootManager.setAttribute(ProjectRootManagerImpl.PROJECT_JDK_TYPE_ATTR, GoConstants.SDK_TYPE_ID); saveFile(file, projectRootManager, "Cannot save sdk type changing"); } @NotNull private static File miscFile(@NotNull ConversionContext context) { return new File(context.getSettingsBaseDir(), "misc.xml"); } private static void addProjectDirToLibraries(@NotNull File file, @NotNull Element rootElement) throws CannotConvertException { GoProjectLibrariesService librariesService = new GoProjectLibrariesService(); librariesService.setLibraryRootUrls("file://$PROJECT_DIR$"); Element componentElement = JDomSerializationUtil.findOrCreateComponentElement(rootElement, GoConstants.GO_LIBRARIES_SERVICE_NAME); XmlSerializer.serializeInto(librariesService.getState(), componentElement); saveFile(file, rootElement, "Cannot save libraries settings"); } private static boolean isAttachProjectDirToLibraries(Element rootElement) { Element goProjectSettings = JDomSerializationUtil.findComponent(rootElement, "GoProjectSettings"); if (goProjectSettings != null) { for (Element option : goProjectSettings.getChildren("option")) { if ("prependGoPath".equals(option.getAttributeValue("name"))) { goProjectSettings.detach(); return "true".equalsIgnoreCase(option.getAttributeValue("value")); } } goProjectSettings.detach(); } return false; } private static boolean isGoSdkType(String sdkTypeName) { return "Google Go SDK".equals(sdkTypeName) || "Google Go App Engine SDK".equals(sdkTypeName); } private static void saveFile(@NotNull File file, @NotNull Element rootElement, String errorMessage) throws CannotConvertException { try { JDOMUtil.writeDocument(rootElement.getDocument(), file, SystemProperties.getLineSeparator()); } catch (IOException e) { throw new CannotConvertException(errorMessage, e); } } private static void convertSdks() { ProjectJdkTable sdkTable = ProjectJdkTable.getInstance(); Collection globalGoPathUrls = ContainerUtil.newLinkedHashSet(); Collection sdksToDelete = ContainerUtil.newArrayList(); Collection sdksToAdd = ContainerUtil.newArrayList(); GoSdkType sdkType = GoSdkType.getInstance(); for (Sdk sdk : sdkTable.getAllJdks()) { String sdkTypeName = sdk.getSdkType().getName(); if (isGoSdkType(sdkTypeName)) { sdksToDelete.add(sdk); String sdkHome = sdkType.adjustSelectedSdkHome(sdk.getHomePath()); if (sdkType.isValidSdkHome(sdkHome)) { ProjectJdkImpl newSdk = new ProjectJdkImpl(sdk.getName(), sdkType, sdkHome, sdkType.getVersionString(sdkHome)); sdkType.setupSdkPaths(newSdk); sdksToAdd.add(newSdk); for (String classesRoot : sdk.getRootProvider().getUrls(OrderRootType.CLASSES)) { if (!classesRoot.equals(sdk.getHomePath())) { globalGoPathUrls.add(classesRoot); } } } } } for (VirtualFile file : GoSdkUtil.getGoPathsRootsFromEnvironment()) { globalGoPathUrls.remove(file.getUrl()); } AccessToken l = WriteAction.start(); try { for (Sdk sdk : sdksToDelete) { sdkTable.removeJdk(sdk); } for (Sdk sdk : sdksToAdd) { sdkTable.addJdk(sdk); } globalGoPathUrls.addAll(GoApplicationLibrariesService.getInstance().getLibraryRootUrls()); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(globalGoPathUrls); } finally { l.finish(); } } private static class RunConfigurationsConverter extends ConversionProcessor { @Override public boolean isConversionNeeded(@NotNull RunManagerSettings settings) { for (Element element : settings.getRunConfigurations()) { String confType = element.getAttributeValue("type"); if ("GaeLocalAppEngineServer".equals(confType) || "GoTestConfiguration".equals(confType)) { return true; } } return false; } @Override public void process(@NotNull RunManagerSettings settings) throws CannotConvertException { for (Element element : settings.getRunConfigurations()) { String confType = element.getAttributeValue("type"); if ("GaeLocalAppEngineServer".equals(confType) || "GoTestConfiguration".equals(confType)) { element.detach(); } } } } } ================================================ FILE: src/com/goide/psi/GoCaseClause.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public interface GoCaseClause extends GoCompositeElement { @Nullable PsiElement getColon(); @NotNull List getStatementList(); @Nullable PsiElement getDefault(); } ================================================ FILE: src/com/goide/psi/GoCompositeElement.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.psi.PsiElement; public interface GoCompositeElement extends PsiElement { boolean shouldGoDeeper(); } ================================================ FILE: src/com/goide/psi/GoCompositeElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; public class GoCompositeElementType extends IElementType { public GoCompositeElementType(@NotNull String debug) { super(debug, GoLanguage.INSTANCE); } } ================================================ FILE: src/com/goide/psi/GoFile.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoConstants; import com.goide.GoFileType; import com.goide.GoLanguage; import com.goide.GoTypes; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoPackageUtil; import com.goide.sdk.GoSdkUtil; import com.goide.stubs.GoConstSpecStub; import com.goide.stubs.GoFileStub; import com.goide.stubs.GoVarSpecStub; import com.goide.stubs.types.*; import com.goide.util.GoUtil; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayFactory; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; public class GoFile extends PsiFileBase { public GoFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, GoLanguage.INSTANCE); } @Nullable public String getImportPath(boolean withVendoring) { return GoSdkUtil.getImportPath(getParent(), withVendoring); } @NotNull @Override public GlobalSearchScope getResolveScope() { return GoUtil.goPathResolveScope(this); } @NotNull @Override public SearchScope getUseScope() { return GoUtil.goPathUseScope(this, true); } @Nullable public GoPackageClause getPackage() { return CachedValuesManager.getCachedValue(this, () -> { GoFileStub stub = getStub(); if (stub != null) { StubElement packageClauseStub = stub.getPackageClauseStub(); return CachedValueProvider.Result.create(packageClauseStub != null ? packageClauseStub.getPsi() : null, this); } return CachedValueProvider.Result.create(findChildByClass(GoPackageClause.class), this); }); } @Nullable public GoImportList getImportList() { return findChildByClass(GoImportList.class); } @Nullable public String getBuildFlags() { GoFileStub stub = getStub(); if (stub != null) { return stub.getBuildFlags(); } // https://code.google.com/p/go/source/browse/src/pkg/go/build/build.go?r=2449e85a115014c3d9251f86d499e5808141e6bc#790 Collection buildFlags = ContainerUtil.newArrayList(); int buildFlagLength = GoConstants.BUILD_FLAG.length(); for (PsiComment comment : getCommentsToConsider(this)) { String commentText = StringUtil.trimStart(comment.getText(), "//").trim(); if (commentText.startsWith(GoConstants.BUILD_FLAG) && commentText.length() > buildFlagLength && StringUtil.isWhiteSpace(commentText.charAt(buildFlagLength))) { ContainerUtil.addIfNotNull(buildFlags, StringUtil.nullize(commentText.substring(buildFlagLength).trim(), true)); } } return !buildFlags.isEmpty() ? StringUtil.join(buildFlags, "|") : null; } @NotNull public List getFunctions() { return CachedValuesManager.getCachedValue(this, () -> { GoFileStub stub = getStub(); List functions = stub != null ? getChildrenByType(stub, GoTypes.FUNCTION_DECLARATION, GoFunctionDeclarationStubElementType.ARRAY_FACTORY) : GoPsiImplUtil.goTraverser().children(this).filter(GoFunctionDeclaration.class).toList(); return CachedValueProvider.Result.create(functions, this); }); } @NotNull public List getMethods() { return CachedValuesManager.getCachedValue(this, () -> { StubElement stub = getStub(); List calc = stub != null ? getChildrenByType(stub, GoTypes.METHOD_DECLARATION, GoMethodDeclarationStubElementType.ARRAY_FACTORY) : GoPsiImplUtil.goTraverser().children(this).filter(GoMethodDeclaration.class).toList(); return CachedValueProvider.Result.create(calc, this); }); } @NotNull public List getTypes() { return CachedValuesManager.getCachedValue(this, () -> { StubElement stub = getStub(); List types = stub != null ? getChildrenByType(stub, GoTypes.TYPE_SPEC, GoTypeSpecStubElementType.ARRAY_FACTORY) : calcTypes(); return CachedValueProvider.Result.create(types, this); }); } @NotNull public List getImports() { return CachedValuesManager.getCachedValue(this, () -> { StubElement stub = getStub(); List imports = stub != null ? getChildrenByType(stub, GoTypes.IMPORT_SPEC, GoImportSpecStubElementType.ARRAY_FACTORY) : calcImports(); return CachedValueProvider.Result.create(imports, this); }); } public GoImportSpec addImport(String path, String alias) { GoImportList importList = getImportList(); if (importList != null) { return importList.addImport(path, alias); } return null; } /** * @return map like { import path -> import spec } for file */ @NotNull public Map getImportedPackagesMap() { return CachedValuesManager.getCachedValue(this, () -> { Map map = ContainerUtil.newHashMap(); for (GoImportSpec spec : getImports()) { if (!spec.isForSideEffects()) { String importPath = spec.getPath(); if (StringUtil.isNotEmpty(importPath)) { map.put(importPath, spec); } } } return CachedValueProvider.Result.create(map, this); }); } /** * @return map like { local package name, maybe alias -> import spec } for file */ @NotNull public MultiMap getImportMap() { return CachedValuesManager.getCachedValue(this, () -> { MultiMap map = MultiMap.createLinked(); List dependencies = ContainerUtil.newArrayList(this); Module module = ModuleUtilCore.findModuleForPsiElement(this); for (GoImportSpec spec : getImports()) { String alias = spec.getAlias(); if (alias != null) { map.putValue(alias, spec); continue; } if (spec.isDot()) { map.putValue(".", spec); continue; } GoImportString string = spec.getImportString(); PsiDirectory dir = string.resolve(); // todo[zolotov]: implement package modification tracker ContainerUtil.addIfNotNull(dependencies, dir); Collection packagesInDirectory = GoPackageUtil.getAllPackagesInDirectory(dir, module, true); if (!packagesInDirectory.isEmpty()) { for (String packageNames : packagesInDirectory) { if (!StringUtil.isEmpty(packageNames)) { map.putValue(packageNames, spec); } } } else { String key = spec.getLocalPackageName(); if (!StringUtil.isEmpty(key)) { map.putValue(key, spec); } } } return CachedValueProvider.Result.create(map, ArrayUtil.toObjectArray(dependencies)); }); } @NotNull public List getVars() { return CachedValuesManager.getCachedValue(this, () -> { List result; StubElement stub = getStub(); if (stub != null) { result = ContainerUtil.newArrayList(); List varSpecs = getChildrenByType(stub, GoTypes.VAR_SPEC, GoVarSpecStubElementType.ARRAY_FACTORY); for (GoVarSpec spec : varSpecs) { GoVarSpecStub specStub = spec.getStub(); if (specStub == null) continue; result.addAll(getChildrenByType(specStub, GoTypes.VAR_DEFINITION, GoVarDefinitionStubElementType.ARRAY_FACTORY)); } } else { result = calcVars(); } return CachedValueProvider.Result.create(result, this); }); } @NotNull public List getConstants() { return CachedValuesManager.getCachedValue(this, () -> { StubElement stub = getStub(); List result; if (stub != null) { result = ContainerUtil.newArrayList(); List constSpecs = getChildrenByType(stub, GoTypes.CONST_SPEC, GoConstSpecStubElementType.ARRAY_FACTORY); for (GoConstSpec spec : constSpecs) { GoConstSpecStub specStub = spec.getStub(); if (specStub == null) continue; result.addAll(getChildrenByType(specStub, GoTypes.CONST_DEFINITION, GoConstDefinitionStubElementType.ARRAY_FACTORY)); } } else { result = calcConsts(); } return CachedValueProvider.Result.create(result, this); }); } @NotNull private List calcTypes() { return GoPsiImplUtil.goTraverser().children(this).filter(GoTypeDeclaration.class).flatten(GoTypeDeclaration::getTypeSpecList).toList(); } @NotNull private List calcImports() { GoImportList list = getImportList(); if (list == null) return ContainerUtil.emptyList(); List result = ContainerUtil.newArrayList(); for (GoImportDeclaration declaration : list.getImportDeclarationList()) { result.addAll(declaration.getImportSpecList()); } return result; } @NotNull private List calcVars() { return GoPsiImplUtil.goTraverser().children(this).filter(GoVarDeclaration.class) .flatten(GoVarDeclaration::getVarSpecList) .flatten(GoVarSpec::getVarDefinitionList).toList(); } @NotNull private List calcConsts() { return GoPsiImplUtil.goTraverser().children(this).filter(GoConstDeclaration.class) .flatten(GoConstDeclaration::getConstSpecList) .flatten(GoConstSpec::getConstDefinitionList).toList(); } @NotNull @Override public FileType getFileType() { return GoFileType.INSTANCE; } public boolean hasMainFunction() { // todo create a map for faster search List functions = getFunctions(); for (GoFunctionDeclaration function : functions) { if (GoConstants.MAIN.equals(function.getName())) { return true; } } return false; } @Nullable public String getPackageName() { return CachedValuesManager.getCachedValue(this, () -> { GoFileStub stub = getStub(); if (stub != null) { return CachedValueProvider.Result.create(stub.getPackageName(), this); } GoPackageClause packageClause = getPackage(); return CachedValueProvider.Result.create(packageClause != null ? packageClause.getName() : null, this); }); } public String getCanonicalPackageName() { String packageName = getPackageName(); if (StringUtil.isNotEmpty(packageName) && GoTestFinder.isTestFile(this)) { return StringUtil.trimEnd(packageName, GoConstants.TEST_SUFFIX); } return packageName; } @Nullable @Override public GoFileStub getStub() { //noinspection unchecked return (GoFileStub)super.getStub(); } public boolean hasCPathImport() { return getImportedPackagesMap().containsKey(GoConstants.C_PATH); } public void deleteImport(@NotNull GoImportSpec importSpec) { GoImportDeclaration importDeclaration = PsiTreeUtil.getParentOfType(importSpec, GoImportDeclaration.class); assert importDeclaration != null; PsiElement elementToDelete = importDeclaration.getImportSpecList().size() == 1 ? importDeclaration : importSpec; elementToDelete.delete(); } @NotNull private static List getChildrenByType(@NotNull StubElement stub, IElementType elementType, ArrayFactory f) { return Arrays.asList(stub.getChildrenByType(elementType, f)); } @NotNull private static Collection getCommentsToConsider(@NotNull GoFile file) { Collection commentsToConsider = ContainerUtil.newArrayList(); PsiElement child = file.getFirstChild(); int lastEmptyLineOffset = 0; while (child != null) { if (child instanceof PsiComment) { commentsToConsider.add((PsiComment)child); } else if (child instanceof PsiWhiteSpace) { if (StringUtil.countChars(child.getText(), '\n') > 1) { lastEmptyLineOffset = child.getTextRange().getStartOffset(); } } else { break; } child = child.getNextSibling(); } int finalLastEmptyLineOffset = lastEmptyLineOffset; return ContainerUtil.filter(commentsToConsider, comment -> comment.getTextRange().getStartOffset() < finalLastEmptyLineOffset); } } ================================================ FILE: src/com/goide/psi/GoFunctionOrMethodDeclaration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface GoFunctionOrMethodDeclaration extends GoTopLevelDeclaration, GoNamedSignatureOwner { @Nullable GoBlock getBlock(); @Override @Nullable GoSignature getSignature(); @NotNull PsiElement getFunc(); @Override @Nullable PsiElement getIdentifier(); } ================================================ FILE: src/com/goide/psi/GoNamedElement.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.navigation.NavigationItem; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNameIdentifierOwner; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface GoNamedElement extends GoCompositeElement, GoTypeOwner, PsiNameIdentifierOwner, NavigationItem { boolean isPublic(); @Nullable PsiElement getIdentifier(); @Nullable String getQualifiedName(); @Override @NotNull GoFile getContainingFile(); @Nullable GoType findSiblingType(); boolean isBlank(); } ================================================ FILE: src/com/goide/psi/GoNamedSignatureOwner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; public interface GoNamedSignatureOwner extends GoNamedElement, GoSignatureOwner { } ================================================ FILE: src/com/goide/psi/GoPsiTreeUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.StubBasedPsiElement; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoPsiTreeUtil extends PsiTreeUtil { @Nullable public static T getStubChildOfType(@Nullable PsiElement element, @NotNull Class aClass) { if (element == null) return null; StubElement stub = element instanceof StubBasedPsiElement ? ((StubBasedPsiElement)element).getStub() : null; if (stub == null) { return getChildOfType(element, aClass); } for (StubElement childStub : stub.getChildrenStubs()) { PsiElement child = childStub.getPsi(); if (aClass.isInstance(child)) { //noinspection unchecked return (T)child; } } return null; } @NotNull public static List getStubChildrenOfTypeAsList(@Nullable PsiElement element, @NotNull Class aClass) { if (element == null) return Collections.emptyList(); StubElement stub = element instanceof StubBasedPsiElement ? ((StubBasedPsiElement)element).getStub() : null; if (stub == null) { return getChildrenOfTypeAsList(element, aClass); } List result = new SmartList(); for (StubElement childStub : stub.getChildrenStubs()) { PsiElement child = childStub.getPsi(); if (aClass.isInstance(child)) { //noinspection unchecked result.add((T)child); } } return result; } @Nullable private static Couple getElementRange(@NotNull GoFile file, int startOffset, int endOffset) { PsiElement startElement = findNotWhiteSpaceElementAtOffset(file, startOffset, true); PsiElement endElement = findNotWhiteSpaceElementAtOffset(file, endOffset - 1, false); if (startElement == null || endElement == null) return null; ASTNode startNode = TreeUtil.findFirstLeaf(startElement.getNode()); ASTNode endNode = TreeUtil.findLastLeaf(endElement.getNode()); if (startNode == null || endNode == null) return null; startElement = startNode.getPsi(); endElement = endNode.getPsi(); if (startElement == null || endElement == null) return null; return Couple.of(startElement, endElement); } /** * Return element range which contains TextRange(start, end) of top level elements * common parent of elements is straight parent for each element */ @Nullable private static Couple getTopmostElementRange(@NotNull Couple elementRange) { if (elementRange.first == null || elementRange.second == null) return null; PsiElement commonParent = PsiTreeUtil.findCommonParent(elementRange.first, elementRange.second); if (commonParent == null) return null; if (commonParent.isEquivalentTo(elementRange.first) || commonParent.isEquivalentTo(elementRange.second)) { commonParent = commonParent.getParent(); } PsiElement startElement = PsiTreeUtil.findPrevParent(commonParent, elementRange.first); PsiElement endElement = PsiTreeUtil.findPrevParent(commonParent, elementRange.second); if (!startElement.getParent().isEquivalentTo(endElement.getParent())) return null; int start = elementRange.first.getTextRange().getStartOffset(); int end = elementRange.second.getTextRange().getEndOffset(); TextRange range = commonParent.getTextRange(); PsiElement[] children = commonParent.getChildren(); if (range.equalsToRange(start, end) || range.getStartOffset() == start && (children.length == 0 || children[0].getTextRange().getStartOffset() > start) || range.getEndOffset() == end && (children.length == 0 || children[children.length - 1].getTextRange().getEndOffset() < end)) { startElement = commonParent; endElement = commonParent; } if (startElement.isEquivalentTo(endElement)) { while (startElement.getTextRange().equals(startElement.getParent().getTextRange())) { startElement = startElement.getParent(); } return Couple.of(startElement, startElement); } return Couple.of(startElement, endElement); } @NotNull public static PsiElement[] getTopLevelElementsInRange(@NotNull GoFile file, int startOffset, int endOffset, @NotNull Class clazz) { Couple elementRange = getElementRange(file, startOffset, endOffset); if (elementRange == null) return PsiElement.EMPTY_ARRAY; Couple topmostElementRange = getTopmostElementRange(elementRange); if (topmostElementRange == null) return PsiElement.EMPTY_ARRAY; if (!clazz.isInstance(topmostElementRange.first) || !clazz.isInstance(topmostElementRange.second)) { return PsiElement.EMPTY_ARRAY; } List result = ContainerUtil.newSmartList(); PsiElement start = topmostElementRange.first; while (start != null && !start.isEquivalentTo(topmostElementRange.second)) { if (clazz.isInstance(start)) result.add(start); start = start.getNextSibling(); } result.add(topmostElementRange.second); return PsiUtilCore.toPsiElementArray(result); } @Nullable private static PsiElement findNotWhiteSpaceElementAtOffset(@NotNull GoFile file, int offset, boolean forward) { PsiElement element = file.findElementAt(offset); while (element instanceof PsiWhiteSpace) { element = file.findElementAt(forward ? element.getTextRange().getEndOffset() : element.getTextRange().getStartOffset() - 1); } return element; } } ================================================ FILE: src/com/goide/psi/GoRecursiveVisitor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoRecursiveVisitor extends GoVisitor { @Override public void visitCompositeElement(@NotNull GoCompositeElement o) { super.visitCompositeElement(o); for (PsiElement psiElement : o.getChildren()) { psiElement.accept(this); ProgressIndicatorProvider.checkCanceled(); } } @Override public void visitFile(@NotNull PsiFile file) { super.visitFile(file); for (PsiElement psiElement : file.getChildren()) { psiElement.accept(this); ProgressIndicatorProvider.checkCanceled(); } } } ================================================ FILE: src/com/goide/psi/GoReferenceExpressionBase.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface GoReferenceExpressionBase extends GoCompositeElement { @NotNull PsiElement getIdentifier(); @Nullable GoReferenceExpressionBase getQualifier(); } ================================================ FILE: src/com/goide/psi/GoSignatureOwner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import org.jetbrains.annotations.Nullable; public interface GoSignatureOwner extends GoCompositeElement { @Nullable GoSignature getSignature(); } ================================================ FILE: src/com/goide/psi/GoTokenType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; public class GoTokenType extends IElementType { public GoTokenType(@NotNull String debug) { super(debug, GoLanguage.INSTANCE); } } ================================================ FILE: src/com/goide/psi/GoTopLevelDeclaration.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; public interface GoTopLevelDeclaration extends GoCompositeElement { } ================================================ FILE: src/com/goide/psi/GoTypeOwner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.intellij.psi.ResolveState; import org.jetbrains.annotations.Nullable; public interface GoTypeOwner extends GoCompositeElement { @Nullable GoType getGoType(@Nullable ResolveState context); } ================================================ FILE: src/com/goide/psi/impl/GoCType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoCompositeElement; import org.jetbrains.annotations.NotNull; public class GoCType extends GoLightType { protected GoCType(@NotNull GoCompositeElement expression) { super(expression); } } ================================================ FILE: src/com/goide/psi/impl/GoCachedReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.util.GoUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReferenceBase; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoCachedReference extends PsiReferenceBase { protected GoCachedReference(@NotNull T element) { super(element, TextRange.from(0, element.getTextLength())); } private static final ResolveCache.AbstractResolver MY_RESOLVER = (r, b) -> r.resolveInner(); @Nullable protected abstract PsiElement resolveInner(); @Nullable @Override public final PsiElement resolve() { return myElement.isValid() ? ResolveCache.getInstance(myElement.getProject()).resolveWithCaching(this, MY_RESOLVER, false, false) : null; } public abstract boolean processResolveVariants(@NotNull GoScopeProcessor processor); @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { myElement.replace(GoElementFactory.createIdentifierFromText(myElement.getProject(), newElementName)); return myElement; } @Override public boolean isReferenceTo(PsiElement element) { return GoUtil.couldBeReferenceTo(element, myElement) && super.isReferenceTo(element); } @NotNull @Override public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } @Override public boolean equals(Object o) { return this == o || o instanceof GoCachedReference && getElement() == ((GoCachedReference)o).getElement(); } @Override public int hashCode() { return getElement().hashCode(); } } ================================================ FILE: src/com/goide/psi/impl/GoCompositeElementImpl.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoCompositeElementImpl extends ASTWrapperPsiElement implements GoCompositeElement { public GoCompositeElementImpl(@NotNull ASTNode node) { super(node); } @Override public String toString() { return getNode().getElementType().toString(); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { return processDeclarationsDefault(this, processor, state, lastParent, place); } public static boolean processDeclarationsDefault(@NotNull GoCompositeElement o, @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { if (o instanceof GoLeftHandExprList || o instanceof GoExpression) return true; if (!o.shouldGoDeeper()) return processor.execute(o, state); if (!processor.execute(o, state)) return false; if (( o instanceof GoSwitchStatement || o instanceof GoIfStatement || o instanceof GoForStatement || o instanceof GoCommClause || o instanceof GoBlock || o instanceof GoCaseClause ) && processor instanceof GoScopeProcessorBase) { if (!PsiTreeUtil.isAncestor(o, ((GoScopeProcessorBase)processor).myOrigin, false)) return true; } return o instanceof GoBlock ? processBlock((GoBlock)o, processor, state, lastParent, place) : ResolveUtil.processChildren(o, processor, state, lastParent, place); } private static boolean processBlock(@NotNull GoBlock o, @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) { return ResolveUtil.processChildrenFromTop(o, processor, state, lastParent, place) && processParameters(o, processor); } private static boolean processParameters(@NotNull GoBlock b, @NotNull PsiScopeProcessor processor) { if (processor instanceof GoScopeProcessorBase && b.getParent() instanceof GoSignatureOwner) { return GoPsiImplUtil.processSignatureOwner((GoSignatureOwner)b.getParent(), (GoScopeProcessorBase)processor); } return true; } @Override public boolean shouldGoDeeper() { return true; } } ================================================ FILE: src/com/goide/psi/impl/GoElementFactory.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoLanguage; import com.goide.psi.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.impl.PsiParserFacadeImpl; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @SuppressWarnings("ConstantConditions") public class GoElementFactory { private GoElementFactory() { } @NotNull private static GoFile createFileFromText(@NotNull Project project, @NotNull String text) { return (GoFile)PsiFileFactory.getInstance(project).createFileFromText("a.go", GoLanguage.INSTANCE, text); } @NotNull public static PsiElement createReturnStatement(@NotNull Project project) { GoFile file = createFileFromText(project, "package main\nfunc _() { return; }"); return PsiTreeUtil.findChildOfType(file, GoReturnStatement.class); } @NotNull public static PsiElement createSelectStatement(@NotNull Project project) { GoFile file = createFileFromText(project, "package main\nfunc _() { select {\n} }"); return PsiTreeUtil.findChildOfType(file, GoSelectStatement.class); } @NotNull public static PsiElement createIdentifierFromText(@NotNull Project project, String text) { GoFile file = createFileFromText(project, "package " + text); return file.getPackage().getIdentifier(); } @NotNull public static GoIfStatement createIfStatement(@NotNull Project project, @NotNull String condition, @NotNull String thenBranch, @Nullable String elseBranch) { String elseText = elseBranch != null ? " else {\n" + elseBranch + "\n}" : ""; GoFile file = createFileFromText(project, "package a; func _() {\n" + "if " + condition + " {\n" + thenBranch + "\n" + "}" + elseText + "\n" + "}"); return PsiTreeUtil.findChildOfType(file, GoIfStatement.class); } @NotNull public static GoImportDeclaration createEmptyImportDeclaration(@NotNull Project project) { return PsiTreeUtil.findChildOfType(createFileFromText(project, "package main\nimport (\n\n)"), GoImportDeclaration.class); } @NotNull public static GoImportDeclaration createImportDeclaration(@NotNull Project project, @NotNull String importString, @Nullable String alias, boolean withParens) { importString = GoPsiImplUtil.isQuotedImportString(importString) ? importString : StringUtil.wrapWithDoubleQuote(importString); alias = alias != null ? alias + " " : ""; GoFile file = createFileFromText(project, withParens ? "package main\nimport (\n" + alias + importString + "\n)" : "package main\nimport " + alias + importString); return PsiTreeUtil.findChildOfType(file, GoImportDeclaration.class); } @NotNull public static GoImportSpec createImportSpec(@NotNull Project project, @NotNull String importString, @Nullable String alias) { GoImportDeclaration importDeclaration = createImportDeclaration(project, importString, alias, true); return ContainerUtil.getFirstItem(importDeclaration.getImportSpecList()); } @NotNull public static GoImportString createImportString(@NotNull Project project, @NotNull String importString) { GoImportSpec importSpec = createImportSpec(project, importString, null); return importSpec.getImportString(); } @NotNull public static PsiElement createNewLine(@NotNull Project project) { return PsiParserFacadeImpl.SERVICE.getInstance(project).createWhiteSpaceFromText("\n"); } @NotNull public static PsiElement createComma(@NotNull Project project) { return createFileFromText(project, "package foo; var a,b = 1,2").getVars().get(0).getNextSibling(); } @NotNull public static GoPackageClause createPackageClause(@NotNull Project project, @NotNull String name) { return createFileFromText(project, "package " + name).getPackage(); } @NotNull public static GoBlock createBlock(@NotNull Project project) { GoFunctionDeclaration function = ContainerUtil.getFirstItem(createFileFromText(project, "package a; func t() {\n}").getFunctions()); assert function != null : "Impossible situation! Parser is broken."; return function.getBlock(); } @NotNull public static GoStringLiteral createStringLiteral(@NotNull Project project, @NotNull String stringLiteral) { GoFile f = createFileFromText(project, "package a; var b = " + stringLiteral); return PsiTreeUtil.getNextSiblingOfType(ContainerUtil.getFirstItem(f.getVars()), GoStringLiteral.class); } @NotNull public static GoSignature createFunctionSignatureFromText(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; func t(" + text + ") {\n}"); return ContainerUtil.getFirstItem(file.getFunctions()).getSignature(); } @NotNull public static GoStatement createShortVarDeclarationStatement(@NotNull Project project, @NotNull String name, @NotNull GoExpression initializer) { GoFile file = createFileFromText(project, "package a; func a() {\n " + name + " := " + initializer.getText() + "}"); return PsiTreeUtil.findChildOfType(file, GoSimpleStatement.class); } @NotNull public static GoStatement createShortVarDeclarationStatement(@NotNull Project project, @NotNull String leftSide, @NotNull String rightSide) { GoFile file = createFileFromText(project, "package a; func a() {\n " + leftSide + " := " + rightSide + "}"); return PsiTreeUtil.findChildOfType(file, GoSimpleStatement.class); } @NotNull public static GoRangeClause createRangeClause(@NotNull Project project, @NotNull String leftSide, @NotNull String rightSide) { GoFile file = createFileFromText(project, "package a; func a() {\n for " + leftSide + " := range " + rightSide + "{\n}\n}"); return PsiTreeUtil.findChildOfType(file, GoRangeClause.class); } @NotNull public static GoRangeClause createRangeClauseAssignment(@NotNull Project project, @NotNull String leftSide, @NotNull String rightSide) { GoFile file = createFileFromText(project, "package a; func a() {\n for " + leftSide + " = range " + rightSide + "{\n}\n}"); return PsiTreeUtil.findChildOfType(file, GoRangeClause.class); } @NotNull public static GoRecvStatement createRecvStatement(@NotNull Project project, @NotNull String leftSide, @NotNull String rightSide) { GoFile file = createFileFromText(project, "package a; func a() {\n select { case " + leftSide + " := " + rightSide + ":\n}\n}"); return PsiTreeUtil.findChildOfType(file, GoRecvStatement.class); } @NotNull public static GoRecvStatement createRecvStatementAssignment(@NotNull Project project, @NotNull String left, @NotNull String right) { GoFile file = createFileFromText(project, "package a; func a() {\n select { case " + left + " = " + right + ":\n}\n}"); return PsiTreeUtil.findChildOfType(file, GoRecvStatement.class); } public static GoAssignmentStatement createAssignmentStatement(@NotNull Project project, @NotNull String left, @NotNull String right) { GoFile file = createFileFromText(project, "package a; func a() {\n " + left + " = " + right + "}"); return PsiTreeUtil.findChildOfType(file, GoAssignmentStatement.class); } @NotNull public static GoDeferStatement createDeferStatement(@NotNull Project project, @NotNull String expressionText) { GoFile file = createFileFromText(project, "package a; func a() {\n defer " + expressionText + "}"); return PsiTreeUtil.findChildOfType(file, GoDeferStatement.class); } @NotNull public static GoGoStatement createGoStatement(@NotNull Project project, @NotNull String expressionText) { GoFile file = createFileFromText(project, "package a; func a() {\n go " + expressionText + "}"); return PsiTreeUtil.findChildOfType(file, GoGoStatement.class); } @NotNull public static GoForStatement createForStatement(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; func a() {\n for {\n" + text + "\n}\n}"); return PsiTreeUtil.findChildOfType(file, GoForStatement.class); } @NotNull public static GoExpression createExpression(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; func a() {\n a := " + text + "}"); return PsiTreeUtil.findChildOfType(file, GoExpression.class); } @NotNull public static GoReferenceExpression createReferenceExpression(@NotNull Project project, @NotNull String name) { GoFile file = createFileFromText(project, "package a; var a = " + name); return PsiTreeUtil.findChildOfType(file, GoReferenceExpression.class); } @NotNull public static GoSimpleStatement createComparison(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; func a() {\n " + text + "}"); return PsiTreeUtil.findChildOfType(file, GoSimpleStatement.class); } @NotNull public static GoConstDeclaration createConstDeclaration(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; const " + text); return PsiTreeUtil.findChildOfType(file, GoConstDeclaration.class); } @NotNull public static GoConstSpec createConstSpec(@NotNull Project project, @NotNull String name, @Nullable String type, @Nullable String value) { GoConstDeclaration constDeclaration = createConstDeclaration(project, prepareVarOrConstDeclarationText(name, type, value)); return ContainerUtil.getFirstItem(constDeclaration.getConstSpecList()); } @NotNull public static GoVarDeclaration createVarDeclaration(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; var " + text); return PsiTreeUtil.findChildOfType(file, GoVarDeclaration.class); } @NotNull public static GoVarSpec createVarSpec(@NotNull Project project, @NotNull String name, @Nullable String type, @Nullable String value) { GoVarDeclaration varDeclaration = createVarDeclaration(project, prepareVarOrConstDeclarationText(name, type, value)); return ContainerUtil.getFirstItem(varDeclaration.getVarSpecList()); } @NotNull private static String prepareVarOrConstDeclarationText(@NotNull String name, @Nullable String type, @Nullable String value) { type = StringUtil.trim(type); value = StringUtil.trim(value); type = StringUtil.isNotEmpty(type) ? " " + type : ""; value = StringUtil.isNotEmpty(value) ? " = " + value : ""; return name + type + value; } public static GoTypeList createTypeList(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; func _() (" + text + "){}"); return PsiTreeUtil.findChildOfType(file, GoTypeList.class); } public static GoType createType(@NotNull Project project, @NotNull String text) { GoFile file = createFileFromText(project, "package a; var a " + text); return PsiTreeUtil.findChildOfType(file, GoType.class); } public static PsiElement createLiteralValueElement(@NotNull Project project, @NotNull String key, @NotNull String value) { GoFile file = createFileFromText(project, "package a; var _ = struct { a string } { " + key + ": " + value + " }"); return PsiTreeUtil.findChildOfType(file, GoElement.class); } @NotNull public static GoTypeDeclaration createTypeDeclaration(@NotNull Project project, @NotNull String name, @NotNull GoType type) { GoFile file = createFileFromText(project, "package a; type " + name + " " + type.getText()); return PsiTreeUtil.findChildOfType(file, GoTypeDeclaration.class); } } ================================================ FILE: src/com/goide/psi/impl/GoExpressionUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Trinity; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoExpressionUtil { public static boolean identical(@Nullable GoExpression left, @Nullable GoExpression right) { if (left == right) return true; if (left == null || right == null) return false; GoExpression l = unwrap(left); GoExpression r = unwrap(right); if (l == null || r == null) return false; if (!l.getClass().equals(r.getClass())) return false; if (l instanceof GoBinaryExpr) { GoBinaryExpr lBin = (GoBinaryExpr)l; GoBinaryExpr rBin = (GoBinaryExpr)r; return isOperatorEquals(lBin.getOperator(), rBin.getOperator()) && isChildrenExprEquals(lBin, rBin); } if (l instanceof GoUnaryExpr) { GoUnaryExpr lUnary = (GoUnaryExpr)l; GoUnaryExpr rUnary = (GoUnaryExpr)r; return isOperatorEquals(lUnary.getOperator(), rUnary.getOperator()) && identical(lUnary.getExpression(), rUnary.getExpression()); } if (l instanceof GoReferenceExpression) { PsiElement resolve = ((GoReferenceExpression)l).resolve(); return resolve != null && resolve.isEquivalentTo(((GoReferenceExpression)r).resolve()); } if (l instanceof GoIndexOrSliceExpr) { GoIndexOrSliceExpr lSlice = (GoIndexOrSliceExpr)l; GoIndexOrSliceExpr rSlice = (GoIndexOrSliceExpr)r; return identical(lSlice.getExpression(), rSlice.getExpression()) && isIndicesIdentical(lSlice.getIndices(), rSlice.getIndices()); } if (l instanceof GoStringLiteral) { return Comparing.equal(((GoStringLiteral)l).getDecodedText(), ((GoStringLiteral)r).getDecodedText()); } if (l instanceof GoLiteralTypeExpr) { GoLiteralTypeExpr lLit = (GoLiteralTypeExpr)l; GoLiteralTypeExpr rLit = (GoLiteralTypeExpr)r; GoTypeReferenceExpression lExpr = lLit.getTypeReferenceExpression(); GoTypeReferenceExpression rExpr = rLit.getTypeReferenceExpression(); PsiElement lResolve = lExpr != null ? lExpr.resolve() : null; return lResolve != null && rExpr != null && lResolve.equals(rExpr.resolve()); //todo: add || GoTypeUtil.identical(lLit.getType(), rLit.getType) } if (l instanceof GoLiteral) { return l.textMatches(r); } if (l instanceof GoBuiltinCallExpr || l instanceof GoCallExpr) { return false; } if (l instanceof GoCompositeLit) { GoCompositeLit lLit = (GoCompositeLit)l; GoCompositeLit rLit = (GoCompositeLit)r; return identical(lLit.getLiteralValue(), rLit.getLiteralValue()); // todo: add && GoTypeUtil.identical } if (l instanceof GoTypeAssertionExpr) { GoTypeAssertionExpr lAssertion = (GoTypeAssertionExpr)l; GoTypeAssertionExpr rAssertion = (GoTypeAssertionExpr)r; return identical(lAssertion.getExpression(), rAssertion.getExpression()); //todo: add && GoTypeUtil.identical(lAssertion.getType(), rAssertion.getType()) } String lText = l.getText(); return lText != null && lText.equals(r.getText()); } private static boolean isIndicesIdentical(@NotNull Trinity l, @NotNull Trinity r) { return identical(l.first, r.first) && identical(l.second, r.second) && identical(l.third, r.third); } private static boolean identical(@Nullable GoLiteralValue l, @Nullable GoLiteralValue r) { if (l == null || r == null) return false; return l.textMatches(r); //todo: fill } private static boolean isOperatorEquals(@Nullable PsiElement l, @Nullable PsiElement r) { if (l == null || r == null) return false; ASTNode lNode = l.getNode(); ASTNode rNode = r.getNode(); return lNode instanceof LeafElement && lNode.getElementType().equals(rNode.getElementType()); } private static boolean isOrderImportant(@NotNull GoBinaryExpr o) { if (o instanceof GoConversionExpr || o instanceof GoSelectorExpr) return true; if (o instanceof GoMulExpr) { GoMulExpr m = (GoMulExpr)o; return m.getRemainder() != null || m.getQuotient() != null || m.getShiftLeft() != null || m.getShiftRight() != null; } if (o instanceof GoConditionalExpr) { GoConditionalExpr c = (GoConditionalExpr)o; return c.getEq() == null && c.getNotEq() == null; } return false; } private static boolean isChildrenExprEquals(@NotNull GoBinaryExpr left, @NotNull GoBinaryExpr right) { GoExpression l1 = left.getLeft(); GoExpression l2 = left.getRight(); GoExpression r1 = right.getLeft(); GoExpression r2 = right.getRight(); boolean order = isOrderImportant(left); return identical(l1, r1) && identical(l2, r2) || !order && identical(l1, r2) && identical(l2, r1); } @Nullable private static GoExpression unwrap(@Nullable GoExpression o) { if (o instanceof GoParenthesesExpr) return unwrap(((GoParenthesesExpr)o).getExpression()); if (o instanceof GoUnaryExpr && ((GoUnaryExpr)o).getPlus() != null) return unwrap(((GoUnaryExpr)o).getExpression()); return o; } } ================================================ FILE: src/com/goide/psi/impl/GoFieldNameReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.ResolveState; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFieldNameReference extends GoCachedReference { public GoFieldNameReference(@NotNull GoReferenceExpressionBase element) { super(element); } @Override public boolean processResolveVariants(@NotNull GoScopeProcessor processor) { GoScopeProcessor fieldProcessor = processor instanceof GoFieldProcessor ? processor : new GoFieldProcessor(myElement) { @Override public boolean execute(@NotNull PsiElement e, @NotNull ResolveState state) { return super.execute(e, state) && processor.execute(e, state); } }; GoKey key = PsiTreeUtil.getParentOfType(myElement, GoKey.class); GoValue value = PsiTreeUtil.getParentOfType(myElement, GoValue.class); if (key == null && (value == null || PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class) != null)) return true; GoType type = GoPsiImplUtil.getLiteralType(myElement, true); if (!processStructType(fieldProcessor, type)) return false; return !(type instanceof GoPointerType && !processStructType(fieldProcessor, ((GoPointerType)type).getType())); } private boolean processStructType(@NotNull GoScopeProcessor fieldProcessor, @Nullable GoType type) { return !(type instanceof GoStructType && !type.processDeclarations(fieldProcessor, ResolveState.initial(), null, myElement)); } public boolean inStructTypeKey() { return GoPsiImplUtil.getParentGoValue(myElement) == null && GoPsiImplUtil.getLiteralType(myElement, false) instanceof GoStructType; } @Nullable @Override public PsiElement resolveInner() { GoScopeProcessorBase p = new GoFieldProcessor(myElement); processResolveVariants(p); return p.getResult(); } private static class GoFieldProcessor extends GoScopeProcessorBase { private final Module myModule; public GoFieldProcessor(@NotNull PsiElement element) { super(element); PsiFile containingFile = myOrigin.getContainingFile(); myModule = containingFile != null ? ModuleUtilCore.findModuleForPsiElement(containingFile.getOriginalFile()) : null; } @Override protected boolean crossOff(@NotNull PsiElement e) { if (!(e instanceof GoFieldDefinition) && !(e instanceof GoAnonymousFieldDefinition)) return true; GoNamedElement named = (GoNamedElement)e; PsiFile myFile = myOrigin.getContainingFile(); PsiFile file = e.getContainingFile(); if (!(myFile instanceof GoFile) || !GoPsiImplUtil.allowed(file, myFile, myModule)) return true; boolean localResolve = GoReference.isLocalResolve(myFile, file); return !e.isValid() || !(named.isPublic() || localResolve); } } } ================================================ FILE: src/com/goide/psi/impl/GoFunctionOrMethodDeclarationImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoType; import com.goide.stubs.GoFunctionOrMethodDeclarationStub; import com.intellij.lang.ASTNode; import com.intellij.psi.ResolveState; import com.intellij.psi.stubs.IStubElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; abstract public class GoFunctionOrMethodDeclarationImpl> extends GoNamedElementImpl implements GoFunctionOrMethodDeclaration { public GoFunctionOrMethodDeclarationImpl(@NotNull T stub, @NotNull IStubElementType nodeType) { super(stub, nodeType); } public GoFunctionOrMethodDeclarationImpl(@NotNull ASTNode node) { super(node); } @Override @Nullable public GoType getGoTypeInner(@Nullable ResolveState context) { return GoPsiImplUtil.getGoTypeInner(this, context); } } ================================================ FILE: src/com/goide/psi/impl/GoLabelReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class GoLabelReference extends GoCachedReference { private final GoScopeProcessorBase myProcessor = new GoScopeProcessorBase(myElement) { @Override protected boolean crossOff(@NotNull PsiElement e) { return !(e instanceof GoLabelDefinition) || ((GoLabelDefinition)e).isBlank(); } }; public GoLabelReference(@NotNull GoLabelRef element) { super(element); } @NotNull private Collection getLabelDefinitions() { GoFunctionLit functionLit = PsiTreeUtil.getParentOfType(myElement, GoFunctionLit.class); PsiElement blockToSearch = functionLit != null ? functionLit.getBlock() : PsiTreeUtil.getTopmostParentOfType(myElement, GoBlock.class); return PsiTreeUtil.findChildrenOfType(blockToSearch, GoLabelDefinition.class); } @Nullable @Override protected PsiElement resolveInner() { return !processResolveVariants(myProcessor) ? myProcessor.getResult() : null; } @Override public boolean processResolveVariants(@NotNull GoScopeProcessor processor) { GoBreakStatement breakStatement = PsiTreeUtil.getParentOfType(myElement, GoBreakStatement.class); if (breakStatement != null) { return processDefinitionsForBreakReference(breakStatement, processor); } return processAllDefinitions(processor); } private boolean processAllDefinitions(@NotNull GoScopeProcessor processor) { Collection defs = getLabelDefinitions(); for (GoLabelDefinition def : defs) { if (!processor.execute(def, ResolveState.initial())) { return false; } } return true; } private static boolean processDefinitionsForBreakReference(@NotNull GoBreakStatement breakStatement, @NotNull GoScopeProcessor processor) { PsiElement breakStatementOwner = GoPsiImplUtil.getBreakStatementOwner(breakStatement); while (breakStatementOwner != null) { PsiElement parent = breakStatementOwner.getParent(); if (parent instanceof GoLabeledStatement) { if (!processor.execute(((GoLabeledStatement)parent).getLabelDefinition(), ResolveState.initial())) { return false; } } breakStatementOwner = GoPsiImplUtil.getBreakStatementOwner(breakStatementOwner); } return true; } } ================================================ FILE: src/com/goide/psi/impl/GoLightType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.goide.stubs.GoTypeStub; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.light.LightElement; import com.intellij.psi.stubs.IStubElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public abstract class GoLightType extends LightElement implements GoType { @NotNull protected final E myElement; protected GoLightType(@NotNull E e) { super(e.getManager(), e.getLanguage()); myElement = e; setNavigationElement(e); } @Nullable @Override public GoTypeReferenceExpression getTypeReferenceExpression() { return null; } @Override public boolean shouldGoDeeper() { return false; } @Override public String toString() { return getClass().getSimpleName() + "{" + myElement + "}"; } @Override public IStubElementType getElementType() { return null; } @Override public GoTypeStub getStub() { return null; } @NotNull @Override public GoType getUnderlyingType() { return GoPsiImplUtil.getUnderlyingType(this); } static class LightPointerType extends GoLightType implements GoPointerType { protected LightPointerType(@NotNull GoType o) { super(o); } @Override public String getText() { return "*" + myElement.getText(); } @Nullable @Override public GoType getType() { return myElement; } @NotNull @Override public PsiElement getMul() { return myElement; // todo: mock it? } } static class LightTypeList extends GoLightType implements GoTypeList { @NotNull private final List myTypes; public LightTypeList(@NotNull GoCompositeElement o, @NotNull List types) { super(o); myTypes = types; } @NotNull @Override public List getTypeList() { return myTypes; } @Override public String toString() { return "MyGoTypeList{myTypes=" + myTypes + '}'; } @Override public String getText() { return StringUtil.join(getTypeList(), PsiElement::getText, ", "); } } static class LightFunctionType extends GoLightType implements GoFunctionType { public LightFunctionType(@NotNull GoSignatureOwner o) { super(o); } @Nullable @Override public GoSignature getSignature() { return myElement.getSignature(); } @NotNull @Override public PsiElement getFunc() { return myElement instanceof GoFunctionOrMethodDeclaration ? ((GoFunctionOrMethodDeclaration)myElement).getFunc() : myElement; } @Override public String getText() { GoSignature signature = myElement.getSignature(); return "func " + (signature != null ? signature.getText() : ""); } } static class LightArrayType extends GoLightType implements GoArrayOrSliceType { protected LightArrayType(GoType type) { super(type); } @Override public String getText() { return "[]" + myElement.getText(); } @Nullable @Override public GoExpression getExpression() { return null; } @Nullable @Override public GoType getType() { return myElement; } @NotNull @Override public PsiElement getLbrack() { //noinspection ConstantConditions return null; // todo: mock? } @Nullable @Override public PsiElement getRbrack() { return null; } @Nullable @Override public PsiElement getTripleDot() { return null; } } } ================================================ FILE: src/com/goide/psi/impl/GoNamedElementImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoIcons; import com.goide.project.GoVendoringUtil; import com.goide.psi.*; import com.goide.sdk.GoPackageUtil; import com.goide.stubs.GoNamedStub; import com.goide.util.GoUtil; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.impl.ElementBase; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.RowIcon; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public abstract class GoNamedElementImpl> extends GoStubbedElementImpl implements GoCompositeElement, GoNamedElement { public GoNamedElementImpl(@NotNull T stub, @NotNull IStubElementType nodeType) { super(stub, nodeType); } public GoNamedElementImpl(@NotNull ASTNode node) { super(node); } @Override public boolean isPublic() { if (GoPsiImplUtil.builtin(this)) return true; T stub = getStub(); return stub != null ? stub.isPublic() : StringUtil.isCapitalized(getName()); } @Nullable @Override public PsiElement getNameIdentifier() { return getIdentifier(); } @Nullable @Override public String getName() { T stub = getStub(); if (stub != null) { return stub.getName(); } PsiElement identifier = getIdentifier(); return identifier != null ? identifier.getText() : null; } @Nullable @Override public String getQualifiedName() { String name = getName(); if (name == null) return null; String packageName = getContainingFile().getPackageName(); return GoPsiImplUtil.getFqn(packageName, name); } @Override public int getTextOffset() { PsiElement identifier = getIdentifier(); return identifier != null ? identifier.getTextOffset() : super.getTextOffset(); } @NotNull @Override public PsiElement setName(@NonNls @NotNull String newName) throws IncorrectOperationException { PsiElement identifier = getIdentifier(); if (identifier != null) { identifier.replace(GoElementFactory.createIdentifierFromText(getProject(), newName)); } return this; } @Nullable @Override public GoType getGoType(@Nullable ResolveState context) { if (context != null) return getGoTypeInner(context); return CachedValuesManager.getCachedValue(this, () -> CachedValueProvider.Result .create(getGoTypeInner(GoPsiImplUtil.createContextOnElement(this)), PsiModificationTracker.MODIFICATION_COUNT)); } @Nullable protected GoType getGoTypeInner(@Nullable ResolveState context) { return findSiblingType(); } @Nullable @Override public GoType findSiblingType() { T stub = getStub(); if (stub != null) { return GoPsiTreeUtil.getStubChildOfType(getParentByStub(), GoType.class); } return PsiTreeUtil.getNextSiblingOfType(this, GoType.class); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return GoCompositeElementImpl.processDeclarationsDefault(this, processor, state, lastParent, place); } @Override public ItemPresentation getPresentation() { String text = UsageViewUtil.createNodeText(this); if (text != null) { boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(ModuleUtilCore.findModuleForPsiElement(getContainingFile())); return new ItemPresentation() { @Nullable @Override public String getPresentableText() { return getName(); } @Nullable @Override public String getLocationString() { GoFile file = getContainingFile(); String fileName = file.getName(); String importPath = ObjectUtils.chooseNotNull(file.getImportPath(vendoringEnabled), file.getPackageName()); return "in " + (importPath != null ? importPath + "/" + fileName : fileName); } @Nullable @Override public Icon getIcon(boolean b) { return GoNamedElementImpl.this.getIcon(Iconable.ICON_FLAG_VISIBILITY); } }; } return super.getPresentation(); } @Nullable @Override public Icon getIcon(int flags) { Icon icon = null; if (this instanceof GoMethodDeclaration) icon = GoIcons.METHOD; else if (this instanceof GoFunctionDeclaration) icon = GoIcons.FUNCTION; else if (this instanceof GoTypeSpec) icon = GoIcons.TYPE; else if (this instanceof GoVarDefinition) icon = GoIcons.VARIABLE; else if (this instanceof GoConstDefinition) icon = GoIcons.CONSTANT; else if (this instanceof GoFieldDefinition) icon = GoIcons.FIELD; else if (this instanceof GoMethodSpec) icon = GoIcons.METHOD; else if (this instanceof GoAnonymousFieldDefinition) icon = GoIcons.FIELD; else if (this instanceof GoParamDefinition) icon = GoIcons.PARAMETER; else if (this instanceof GoLabelDefinition) icon = GoIcons.LABEL; if (icon != null) { if ((flags & Iconable.ICON_FLAG_VISIBILITY) != 0) { RowIcon rowIcon = ElementBase.createLayeredIcon(this, icon, flags); rowIcon.setIcon(isPublic() ? PlatformIcons.PUBLIC_ICON : PlatformIcons.PRIVATE_ICON, 1); return rowIcon; } return icon; } return super.getIcon(flags); } @NotNull @Override public GlobalSearchScope getResolveScope() { return isPublic() ? GoUtil.goPathResolveScope(this) : GoPackageUtil.packageScope(getContainingFile()); } @NotNull @Override public SearchScope getUseScope() { if (this instanceof GoVarDefinition || this instanceof GoConstDefinition || this instanceof GoLabelDefinition) { GoBlock block = PsiTreeUtil.getParentOfType(this, GoBlock.class); if (block != null) return new LocalSearchScope(block); } if (!isPublic()) { return GoPackageUtil.packageScope(getContainingFile()); } GoSpecType parentType = PsiTreeUtil.getStubOrPsiParentOfType(this, GoSpecType.class); if (parentType != null) { GoTypeSpec typeSpec = GoPsiImplUtil.getTypeSpecSafe(parentType); if (typeSpec != null && !StringUtil.isCapitalized(typeSpec.getName())) { return GoPackageUtil.packageScope(getContainingFile()); } } return GoUtil.goPathUseScope(this, !(this instanceof GoMethodDeclaration)); } @Override public boolean isBlank() { return StringUtil.equals(getName(), "_"); } @Override public boolean shouldGoDeeper() { return true; } } ================================================ FILE: src/com/goide/psi/impl/GoPsiImplUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoConstants; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.psi.impl.imports.GoImportReferenceSet; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoPackageUtil; import com.goide.sdk.GoSdkUtil; import com.goide.stubs.*; import com.goide.stubs.index.GoIdFilter; import com.goide.stubs.index.GoMethodIndex; import com.goide.util.GoStringLiteralEscaper; import com.goide.util.GoUtil; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.lang.ASTNode; import com.intellij.lang.parser.GeneratedParserUtilBase; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceOwner; import com.intellij.psi.impl.source.resolve.reference.impl.providers.PsiFileReference; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.goide.psi.impl.GoLightType.*; import static com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access.*; import static com.intellij.openapi.util.Conditions.equalTo; public class GoPsiImplUtil { private static final Logger LOG = Logger.getInstance(GoPsiImplUtil.class); private static final Key> CONTEXT = Key.create("CONTEXT"); @NotNull public static SyntaxTraverser goTraverser() { return SyntaxTraverser.psiTraverser().forceDisregardTypes(equalTo(GeneratedParserUtilBase.DUMMY_BLOCK)); } public static boolean builtin(@Nullable PsiElement resolve) { return resolve != null && isBuiltinFile(resolve.getContainingFile()); } public static boolean isConversionExpression(@Nullable GoExpression expression) { if (expression instanceof GoConversionExpr) { return true; } GoReferenceExpression referenceExpression = null; if (expression instanceof GoCallExpr) { referenceExpression = ObjectUtils.tryCast(((GoCallExpr)expression).getExpression(), GoReferenceExpression.class); } else if (expression instanceof GoBuiltinCallExpr) { referenceExpression = ((GoBuiltinCallExpr)expression).getReferenceExpression(); } return referenceExpression != null && referenceExpression.resolve() instanceof GoTypeSpec; } public static boolean isPanic(@NotNull GoCallExpr o) { return stdLibCall(o, "panic"); } public static boolean isRecover(@NotNull GoCallExpr o) { return stdLibCall(o, "recover"); } private static boolean stdLibCall(@NotNull GoCallExpr o, @NotNull String name) { GoExpression e = o.getExpression(); if (e.textMatches(name) && e instanceof GoReferenceExpression) { PsiReference reference = e.getReference(); PsiElement resolve = reference != null ? reference.resolve() : null; if (!(resolve instanceof GoFunctionDeclaration)) return false; return isBuiltinFile(resolve.getContainingFile()); } return false; } public static boolean isBuiltinFile(@Nullable PsiFile file) { return file instanceof GoFile && GoConstants.BUILTIN_PACKAGE_NAME.equals(((GoFile)file).getPackageName()) && GoConstants.BUILTIN_PACKAGE_NAME.equals(((GoFile)file).getImportPath(false)) && GoConstants.BUILTIN_FILE_NAME.equals(file.getName()); } @Nullable public static GoTopLevelDeclaration getTopLevelDeclaration(@Nullable PsiElement startElement) { GoTopLevelDeclaration declaration = PsiTreeUtil.getTopmostParentOfType(startElement, GoTopLevelDeclaration.class); if (declaration == null || !(declaration.getParent() instanceof GoFile)) return null; return declaration; } public static int getArity(@Nullable GoSignature s) { return s == null ? -1 : s.getParameters().getParameterDeclarationList().size(); } @Nullable public static PsiElement getContextElement(@Nullable ResolveState state) { SmartPsiElementPointer context = state != null ? state.get(CONTEXT) : null; return context != null ? context.getElement() : null; } @NotNull public static ResolveState createContextOnElement(@NotNull PsiElement element) { return ResolveState.initial().put(CONTEXT, SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element)); } @Nullable public static GoTypeReferenceExpression getQualifier(@NotNull GoTypeReferenceExpression o) { return PsiTreeUtil.getChildOfType(o, GoTypeReferenceExpression.class); } @Nullable public static PsiDirectory resolve(@NotNull GoImportString importString) { PsiReference[] references = importString.getReferences(); for (PsiReference reference : references) { if (reference instanceof FileReferenceOwner) { PsiFileReference lastFileReference = ((FileReferenceOwner)reference).getLastFileReference(); PsiElement result = lastFileReference != null ? lastFileReference.resolve() : null; return result instanceof PsiDirectory ? (PsiDirectory)result : null; } } return null; } @NotNull public static PsiReference getReference(@NotNull GoTypeReferenceExpression o) { return new GoTypeReference(o); } @NotNull public static PsiReference getReference(@NotNull GoLabelRef o) { return new GoLabelReference(o); } @Nullable public static PsiReference getReference(@NotNull GoVarDefinition o) { GoShortVarDeclaration shortDeclaration = PsiTreeUtil.getParentOfType(o, GoShortVarDeclaration.class); boolean createRef = PsiTreeUtil.getParentOfType(shortDeclaration, GoBlock.class, GoForStatement.class, GoIfStatement.class, GoSwitchStatement.class, GoSelectStatement.class) instanceof GoBlock; return createRef ? new GoVarReference(o) : null; } @NotNull public static GoReference getReference(@NotNull GoReferenceExpression o) { return new GoReference(o); } @NotNull public static PsiReference getReference(@NotNull GoFieldName o) { GoFieldNameReference field = new GoFieldNameReference(o); GoReference ordinal = new GoReference(o); return new PsiMultiReference(new PsiReference[]{field, ordinal}, o) { @Override public PsiElement resolve() { PsiElement resolve = field.resolve(); return resolve != null ? resolve : field.inStructTypeKey() ? null : ordinal.resolve(); } @Override public boolean isReferenceTo(PsiElement element) { return GoUtil.couldBeReferenceTo(element, getElement()) && getElement().getManager().areElementsEquivalent(resolve(), element); } }; } @Nullable public static GoReferenceExpression getQualifier(@SuppressWarnings("UnusedParameters") @NotNull GoFieldName o) { return null; } @NotNull public static PsiReference[] getReferences(@NotNull GoImportString o) { if (o.getTextLength() < 2) return PsiReference.EMPTY_ARRAY; return new GoImportReferenceSet(o).getAllReferences(); } @Nullable public static GoReferenceExpression getQualifier(@NotNull GoReferenceExpression o) { return PsiTreeUtil.getChildOfType(o, GoReferenceExpression.class); } public static boolean processDeclarations(@NotNull GoCompositeElement o, @NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { boolean isAncestor = PsiTreeUtil.isAncestor(o, place, false); if (o instanceof GoVarSpec) { return isAncestor || GoCompositeElementImpl.processDeclarationsDefault(o, processor, state, lastParent, place); } if (isAncestor) return GoCompositeElementImpl.processDeclarationsDefault(o, processor, state, lastParent, place); if (o instanceof GoBlock || o instanceof GoIfStatement || o instanceof GoForStatement || o instanceof GoCommClause || o instanceof GoFunctionLit || o instanceof GoTypeCaseClause || o instanceof GoExprCaseClause) { return processor.execute(o, state); } return GoCompositeElementImpl.processDeclarationsDefault(o, processor, state, lastParent, place); } @Nullable public static GoType getGoTypeInner(@NotNull GoReceiver o, @SuppressWarnings("UnusedParameters") @Nullable ResolveState context) { return o.getType(); } @Nullable public static PsiElement getIdentifier(@SuppressWarnings("UnusedParameters") @NotNull GoAnonymousFieldDefinition o) { GoTypeReferenceExpression expression = o.getTypeReferenceExpression(); return expression != null ? expression.getIdentifier() : null; } @Nullable public static String getName(@NotNull GoPackageClause packageClause) { GoPackageClauseStub stub = packageClause.getStub(); if (stub != null) return stub.getName(); PsiElement packageIdentifier = packageClause.getIdentifier(); return packageIdentifier != null ? packageIdentifier.getText().trim() : null; } @Nullable public static String getName(@NotNull GoAnonymousFieldDefinition o) { PsiElement identifier = o.getIdentifier(); return identifier != null ? identifier.getText() : null; } @Nullable public static GoTypeReferenceExpression getTypeReferenceExpression(@NotNull GoAnonymousFieldDefinition o) { return getTypeRefExpression(o.getType()); } @Nullable public static GoType getGoTypeInner(@NotNull GoAnonymousFieldDefinition o, @SuppressWarnings("UnusedParameters") @Nullable ResolveState context) { return o.getType(); } @Nullable public static String getName(@NotNull GoMethodSpec o) { GoNamedStub stub = o.getStub(); if (stub != null) { return stub.getName(); } PsiElement identifier = o.getIdentifier(); if (identifier != null) return identifier.getText(); GoTypeReferenceExpression typeRef = o.getTypeReferenceExpression(); return typeRef != null ? typeRef.getIdentifier().getText() : null; } @Nullable public static GoType getReceiverType(@NotNull GoMethodDeclaration o) { GoReceiver receiver = o.getReceiver(); return receiver == null ? null : receiver.getType(); } // todo: merge with {@link this#getTypeRefExpression} @Nullable public static GoTypeReferenceExpression getTypeReference(@Nullable GoType o) { if (o instanceof GoPointerType) { return PsiTreeUtil.findChildOfAnyType(o, GoTypeReferenceExpression.class); } return o != null ? o.getTypeReferenceExpression() : null; } // todo: merge with {@link this#getTypeReference} @Nullable public static GoTypeReferenceExpression getTypeRefExpression(@Nullable GoType type) { GoType unwrap = unwrapPointerIfNeeded(type); return unwrap != null ? unwrap.getTypeReferenceExpression() : null; } @Nullable public static GoType getGoTypeInner(@NotNull GoConstDefinition o, @Nullable ResolveState context) { GoType fromSpec = findTypeInConstSpec(o); if (fromSpec != null) return fromSpec; // todo: stubs return RecursionManager.doPreventingRecursion(o, true, (NullableComputable)() -> { GoConstSpec prev = PsiTreeUtil.getPrevSiblingOfType(o.getParent(), GoConstSpec.class); while (prev != null) { GoType type = prev.getType(); if (type != null) return type; GoExpression expr = ContainerUtil.getFirstItem(prev.getExpressionList()); // not sure about first if (expr != null) return expr.getGoType(context); prev = PsiTreeUtil.getPrevSiblingOfType(prev, GoConstSpec.class); } return null; }); } @Nullable private static GoType findTypeInConstSpec(@NotNull GoConstDefinition o) { GoConstDefinitionStub stub = o.getStub(); PsiElement parent = PsiTreeUtil.getStubOrPsiParent(o); if (!(parent instanceof GoConstSpec)) return null; GoConstSpec spec = (GoConstSpec)parent; GoType commonType = spec.getType(); if (commonType != null) return commonType; List varList = spec.getConstDefinitionList(); int i = Math.max(varList.indexOf(o), 0); if (stub != null) return null; GoConstSpecStub specStub = spec.getStub(); List es = specStub != null ? specStub.getExpressionList() : spec.getExpressionList(); // todo: move to constant spec if (es.size() <= i) return null; return es.get(i).getGoType(null); } @Nullable private static GoType unwrapParType(@NotNull GoExpression o, @Nullable ResolveState c) { GoType inner = getGoTypeInner(o, c); return inner instanceof GoParType ? ((GoParType)inner).getActualType() : inner; } @Nullable public static GoType getGoType(@NotNull GoExpression o, @Nullable ResolveState context) { return RecursionManager.doPreventingRecursion(o, true, () -> { if (context != null) return unwrapParType(o, context); return CachedValuesManager.getCachedValue(o, () -> CachedValueProvider.Result .create(unwrapParType(o, createContextOnElement(o)), PsiModificationTracker.MODIFICATION_COUNT)); }); } @Nullable private static GoType getGoTypeInner(@NotNull GoExpression o, @Nullable ResolveState context) { if (o instanceof GoUnaryExpr) { GoUnaryExpr u = (GoUnaryExpr)o; GoExpression e = u.getExpression(); if (e == null) return null; GoType type = e.getGoType(context); GoType base = type == null || type.getTypeReferenceExpression() == null ? type : type.getUnderlyingType(); if (u.getBitAnd() != null) return type != null ? new LightPointerType(type) : null; if (u.getSendChannel() != null) return base instanceof GoChannelType ? ((GoChannelType)base).getType() : type; if (u.getMul() != null) return base instanceof GoPointerType ? ((GoPointerType)base).getType() : type; return type; } if (o instanceof GoAddExpr) { return ((GoAddExpr)o).getLeft().getGoType(context); } if (o instanceof GoMulExpr) { GoExpression left = ((GoMulExpr)o).getLeft(); if (!(left instanceof GoLiteral)) return left.getGoType(context); GoExpression right = ((GoBinaryExpr)o).getRight(); if (right != null) return right.getGoType(context); } else if (o instanceof GoCompositeLit) { GoType type = ((GoCompositeLit)o).getType(); if (type != null) return type; GoTypeReferenceExpression expression = ((GoCompositeLit)o).getTypeReferenceExpression(); return expression != null ? expression.resolveType() : null; } else if (o instanceof GoFunctionLit) { return new LightFunctionType((GoFunctionLit)o); } else if (o instanceof GoBuiltinCallExpr) { String text = ((GoBuiltinCallExpr)o).getReferenceExpression().getText(); boolean isNew = "new".equals(text); boolean isMake = "make".equals(text); if (isNew || isMake) { GoBuiltinArgumentList args = ((GoBuiltinCallExpr)o).getBuiltinArgumentList(); GoType type = args != null ? args.getType() : null; return isNew ? type == null ? null : new LightPointerType(type) : type; } } else if (o instanceof GoCallExpr) { GoExpression e = ((GoCallExpr)o).getExpression(); if (e instanceof GoReferenceExpression) { // todo: unify Type processing PsiReference ref = e.getReference(); PsiElement resolve = ref != null ? ref.resolve() : null; if (((GoReferenceExpression)e).getQualifier() == null && "append".equals(((GoReferenceExpression)e).getIdentifier().getText())) { if (resolve instanceof GoFunctionDeclaration && isBuiltinFile(resolve.getContainingFile())) { List l = ((GoCallExpr)o).getArgumentList().getExpressionList(); GoExpression f = ContainerUtil.getFirstItem(l); return f == null ? null : getGoType(f, context); } } else if (resolve == e) { // C.call() return new GoCType(e); } } GoType type = ((GoCallExpr)o).getExpression().getGoType(context); if (type instanceof GoFunctionType) { return funcType(type); } GoType byRef = type != null && type.getTypeReferenceExpression() != null ? type.getUnderlyingType() : null; if (byRef instanceof GoFunctionType) { return funcType(byRef); } return type; } else if (o instanceof GoReferenceExpression) { PsiReference reference = o.getReference(); PsiElement resolve = reference != null ? reference.resolve() : null; if (resolve instanceof GoTypeOwner) return typeOrParameterType((GoTypeOwner)resolve, context); } else if (o instanceof GoParenthesesExpr) { GoExpression expression = ((GoParenthesesExpr)o).getExpression(); return expression != null ? expression.getGoType(context) : null; } else if (o instanceof GoSelectorExpr) { GoExpression item = ContainerUtil.getLastItem(((GoSelectorExpr)o).getExpressionList()); return item != null ? item.getGoType(context) : null; } else if (o instanceof GoIndexOrSliceExpr) { GoType referenceType = getIndexedExpressionReferenceType((GoIndexOrSliceExpr)o, context); if (o.getNode().findChildByType(GoTypes.COLON) != null) return referenceType; // means slice expression, todo: extract if needed GoType type = referenceType != null ? referenceType.getUnderlyingType() : null; if (type instanceof GoMapType) { List list = ((GoMapType)type).getTypeList(); if (list.size() == 2) { return list.get(1); } } else if (type instanceof GoArrayOrSliceType) { return ((GoArrayOrSliceType)type).getType(); } else if (GoTypeUtil.isString(type)) { return getBuiltinType("byte", o); } } else if (o instanceof GoTypeAssertionExpr) { return ((GoTypeAssertionExpr)o).getType(); } else if (o instanceof GoConversionExpr) { return ((GoConversionExpr)o).getType(); } else if (o instanceof GoStringLiteral) { return getBuiltinType("string", o); } else if (o instanceof GoLiteral) { GoLiteral l = (GoLiteral)o; if (l.getChar() != null) return getBuiltinType("rune", o); if (l.getInt() != null || l.getHex() != null || ((GoLiteral)o).getOct() != null) return getBuiltinType("int", o); if (l.getFloat() != null) return getBuiltinType("float64", o); if (l.getFloati() != null) return getBuiltinType("complex64", o); if (l.getDecimali() != null) return getBuiltinType("complex128", o); } else if (o instanceof GoConditionalExpr) { return getBuiltinType("bool", o); } return null; } @Nullable public static GoType getIndexedExpressionReferenceType(@NotNull GoIndexOrSliceExpr o, @Nullable ResolveState context) { GoExpression first = ContainerUtil.getFirstItem(o.getExpressionList()); // todo: calculate type for indexed expressions only // https://golang.org/ref/spec#Index_expressions – a[x] is shorthand for (*a)[x] return unwrapPointerIfNeeded(first != null ? first.getGoType(context) : null); } @Nullable public static GoType unwrapPointerIfNeeded(@Nullable GoType type) { return type instanceof GoPointerType ? ((GoPointerType)type).getType() : type; } @Nullable public static GoType getBuiltinType(@NotNull String name, @NotNull PsiElement context) { GoFile builtin = GoSdkUtil.findBuiltinFile(context); if (builtin != null) { GoTypeSpec spec = ContainerUtil.find(builtin.getTypes(), spec1 -> name.equals(spec1.getName())); if (spec != null) { return spec.getSpecType().getType(); // todo } } return null; } @Nullable private static GoType typeFromRefOrType(@Nullable GoType t) { if (t == null) return null; GoTypeReferenceExpression tr = t.getTypeReferenceExpression(); return tr != null ? tr.resolveType() : t; } @Nullable public static GoType typeOrParameterType(@NotNull GoTypeOwner resolve, @Nullable ResolveState context) { GoType type = resolve.getGoType(context); if (resolve instanceof GoParamDefinition && ((GoParamDefinition)resolve).isVariadic()) { return type == null ? null : new LightArrayType(type); } if (resolve instanceof GoSignatureOwner) { return new LightFunctionType((GoSignatureOwner)resolve); } return type; } @Nullable public static PsiElement resolve(@NotNull GoReferenceExpression o) { // todo: replace with default method in GoReferenceExpressionBase return o.getReference().resolve(); } @Nullable public static PsiElement resolve(@NotNull GoTypeReferenceExpression o) { // todo: replace with default method in GoReferenceExpressionBase return o.getReference().resolve(); } @Nullable public static PsiElement resolve(@NotNull GoFieldName o) { // todo: replace with default method in GoReferenceExpressionBase return o.getReference().resolve(); } @Nullable public static GoType getLiteralType(@Nullable PsiElement context, boolean considerLiteralValue) { GoCompositeLit lit = PsiTreeUtil.getNonStrictParentOfType(context, GoCompositeLit.class); if (lit == null) { return null; } GoType type = lit.getType(); if (type == null) { GoTypeReferenceExpression ref = lit.getTypeReferenceExpression(); GoType resolve = ref != null ? ref.resolveType() : null; type = resolve != null ? resolve.getUnderlyingType() : null; } if (!considerLiteralValue) { return type; } GoValue parentGoValue = getParentGoValue(context); PsiElement literalValue = PsiTreeUtil.getParentOfType(context, GoLiteralValue.class); while (literalValue != null) { if (literalValue == lit) break; if (literalValue instanceof GoLiteralValue) { type = calcLiteralType(parentGoValue, type); } literalValue = literalValue.getParent(); } return type; } @Nullable public static GoValue getParentGoValue(@NotNull PsiElement element) { PsiElement place = element; while ((place = PsiTreeUtil.getParentOfType(place, GoLiteralValue.class)) != null) { if (place.getParent() instanceof GoValue) { return (GoValue)place.getParent(); } } return null; } // todo: rethink and unify this algorithm @Nullable private static GoType calcLiteralType(@Nullable GoValue parentGoValue, @Nullable GoType type) { if (type == null) return null; type = findLiteralType(parentGoValue, type); if (type instanceof GoParType) { type = ((GoParType)type).getActualType(); } if (type != null && type.getTypeReferenceExpression() != null) { type = type.getUnderlyingType(); } if (type instanceof GoPointerType) { GoType inner = ((GoPointerType)type).getType(); if (inner != null && inner.getTypeReferenceExpression() != null) { type = inner.getUnderlyingType(); } } return type instanceof GoSpecType ? ((GoSpecType)type).getType() : type; } private static GoType findLiteralType(@Nullable GoValue parentGoValue, @Nullable GoType type) { boolean inValue = parentGoValue != null; if (inValue && type instanceof GoArrayOrSliceType) { type = ((GoArrayOrSliceType)type).getType(); } else if (type instanceof GoMapType) { type = inValue ? ((GoMapType)type).getValueType() : ((GoMapType)type).getKeyType(); } else if (inValue && type instanceof GoSpecType) { GoType inner = ((GoSpecType)type).getType(); if (inner instanceof GoArrayOrSliceType) { type = ((GoArrayOrSliceType)inner).getType(); } else if (inner instanceof GoStructType) { GoKey key = PsiTreeUtil.getPrevSiblingOfType(parentGoValue, GoKey.class); GoFieldName field = key != null ? key.getFieldName() : null; PsiElement resolve = field != null ? field.resolve() : null; if (resolve instanceof GoFieldDefinition) { type = PsiTreeUtil.getNextSiblingOfType(resolve, GoType.class); } } } return type; } @Nullable public static GoType resolveType(@NotNull GoTypeReferenceExpression expression) { PsiElement resolve = expression.resolve(); if (resolve instanceof GoTypeSpec) return ((GoTypeSpec)resolve).getSpecType(); // hacky C resolve return resolve == expression ? new GoCType(expression) : null; } public static boolean isVariadic(@NotNull GoParamDefinition o) { PsiElement parent = o.getParent(); return parent instanceof GoParameterDeclaration && ((GoParameterDeclaration)parent).isVariadic(); } public static boolean isVariadic(@NotNull GoParameterDeclaration o) { GoParameterDeclarationStub stub = o.getStub(); return stub != null ? stub.isVariadic() : o.getTripleDot() != null; } public static boolean hasVariadic(@NotNull GoArgumentList argumentList) { return argumentList.getTripleDot() != null; } @Nullable public static GoType getGoTypeInner(@NotNull GoTypeSpec o, @SuppressWarnings("UnusedParameters") @Nullable ResolveState context) { return o.getSpecType(); } @Nullable public static GoType getGoTypeInner(@NotNull GoVarDefinition o, @Nullable ResolveState context) { // see http://golang.org/ref/spec#RangeClause PsiElement parent = PsiTreeUtil.getStubOrPsiParent(o); if (parent instanceof GoRangeClause) { return processRangeClause(o, (GoRangeClause)parent, context); } if (parent instanceof GoVarSpec) { return findTypeInVarSpec(o, context); } GoCompositeLit literal = PsiTreeUtil.getNextSiblingOfType(o, GoCompositeLit.class); if (literal != null) { return literal.getType(); } GoType siblingType = o.findSiblingType(); if (siblingType != null) return siblingType; if (parent instanceof GoTypeSwitchGuard) { GoTypeSwitchStatement switchStatement = ObjectUtils.tryCast(parent.getParent(), GoTypeSwitchStatement.class); if (switchStatement != null) { GoTypeCaseClause typeCase = getTypeCaseClause(getContextElement(context), switchStatement); if (typeCase != null) { return typeCase.getDefault() != null ? ((GoTypeSwitchGuard)parent).getExpression().getGoType(context) : typeCase.getType(); } return ((GoTypeSwitchGuard)parent).getExpression().getGoType(null); } } return null; } public static boolean isVoid(@NotNull GoResult result) { GoType type = result.getType(); if (type != null) return false; GoParameters parameters = result.getParameters(); return parameters == null || parameters.getParameterDeclarationList().isEmpty(); } @Nullable private static GoTypeCaseClause getTypeCaseClause(@Nullable PsiElement context, @NotNull GoTypeSwitchStatement switchStatement) { return SyntaxTraverser.psiApi().parents(context).takeWhile(Conditions.notEqualTo(switchStatement)) .filter(GoTypeCaseClause.class).last(); } @Nullable private static GoType findTypeInVarSpec(@NotNull GoVarDefinition o, @Nullable ResolveState context) { GoVarSpec parent = (GoVarSpec)PsiTreeUtil.getStubOrPsiParent(o); if (parent == null) return null; GoType commonType = parent.getType(); if (commonType != null) return commonType; List varList = parent.getVarDefinitionList(); int i = varList.indexOf(o); i = i == -1 ? 0 : i; List exprs = parent.getRightExpressionsList(); if (exprs.size() == 1 && exprs.get(0) instanceof GoCallExpr) { GoExpression call = exprs.get(0); GoType fromCall = call.getGoType(context); boolean canDecouple = varList.size() > 1; GoType underlyingType = canDecouple && fromCall instanceof GoSpecType ? ((GoSpecType)fromCall).getType() : fromCall; GoType byRef = typeFromRefOrType(underlyingType); GoType type = funcType(canDecouple && byRef instanceof GoSpecType ? ((GoSpecType)byRef).getType() : byRef); if (type == null) return fromCall; if (type instanceof GoTypeList) { if (((GoTypeList)type).getTypeList().size() > i) { return ((GoTypeList)type).getTypeList().get(i); } } return type; } if (exprs.size() <= i) return null; return exprs.get(i).getGoType(context); } @Nullable private static GoType funcType(@Nullable GoType type) { if (type instanceof GoFunctionType) { GoSignature signature = ((GoFunctionType)type).getSignature(); GoResult result = signature != null ? signature.getResult() : null; if (result != null) { GoType rt = result.getType(); if (rt != null) return rt; GoParameters parameters = result.getParameters(); if (parameters != null) { List list = parameters.getParameterDeclarationList(); List types = ContainerUtil.newArrayListWithCapacity(list.size()); for (GoParameterDeclaration declaration : list) { GoType declarationType = declaration.getType(); for (GoParamDefinition ignored : declaration.getParamDefinitionList()) { types.add(declarationType); } } if (!types.isEmpty()) { return types.size() == 1 ? types.get(0) : new LightTypeList(parameters, types); } } } return null; } return type; } /** * https://golang.org/ref/spec#RangeClause */ @Nullable private static GoType processRangeClause(@NotNull GoVarDefinition o, @NotNull GoRangeClause parent, @Nullable ResolveState context) { GoExpression rangeExpression = parent.getRangeExpression(); if (rangeExpression != null) { List varList = parent.getVarDefinitionList(); GoType type = unwrapIfNeeded(rangeExpression.getGoType(context)); if (type instanceof GoChannelType) return ((GoChannelType)type).getType(); int i = varList.indexOf(o); i = i == -1 ? 0 : i; if (type instanceof GoArrayOrSliceType && i == 1) return ((GoArrayOrSliceType)type).getType(); if (type instanceof GoMapType) { List list = ((GoMapType)type).getTypeList(); if (i == 0) return ContainerUtil.getFirstItem(list); if (i == 1) return ContainerUtil.getLastItem(list); } if (GoTypeUtil.isString(type)) { return getBuiltinType("int32", o); } } return null; } @Nullable private static GoType unwrapIfNeeded(@Nullable GoType type) { type = unwrapPointerIfNeeded(type); return type != null ? type.getUnderlyingType() : null; } @NotNull public static GoType getActualType(@NotNull GoParType o) { return ObjectUtils.notNull(SyntaxTraverser.psiTraverser(o).filter(Conditions.notInstanceOf(GoParType.class)) .filter(GoType.class).first(), o.getType()); } @NotNull public static String getText(@Nullable GoType o) { if (o == null) return ""; if (o instanceof GoPointerType && ((GoPointerType)o).getType() instanceof GoSpecType) { return "*" + getText(((GoPointerType)o).getType()); } if (o instanceof GoSpecType) { String fqn = getFqn(getTypeSpecSafe(o)); if (fqn != null) { return fqn; } } else if (o instanceof GoStructType) { return ((GoStructType)o).getFieldDeclarationList().isEmpty() ? "struct{}" : "struct {...}"; } else if (o instanceof GoInterfaceType) { return ((GoInterfaceType)o).getMethodSpecList().isEmpty() ? "interface{}" : "interface {...}"; } String text = o.getText(); if (text == null) return ""; return text.replaceAll("\\s+", " "); } @Nullable private static String getFqn(@Nullable GoTypeSpec typeSpec) { if (typeSpec == null) return null; String name = typeSpec.getName(); GoFile file = typeSpec.getContainingFile(); String packageName = file.getPackageName(); if (name != null) { return !isBuiltinFile(file) ? getFqn(packageName, name) : name; } return null; } public static String getFqn(@Nullable String packageName, @NotNull String elementName) { return StringUtil.isNotEmpty(packageName) ? packageName + "." + elementName : elementName; } @NotNull public static List getMethods(@NotNull GoInterfaceType o) { return ContainerUtil.filter(o.getMethodSpecList(), spec -> spec.getIdentifier() != null); } @NotNull public static List getBaseTypesReferences(@NotNull GoInterfaceType o) { List refs = ContainerUtil.newArrayList(); o.accept(new GoRecursiveVisitor() { @Override public void visitMethodSpec(@NotNull GoMethodSpec o) { ContainerUtil.addIfNotNull(refs, o.getTypeReferenceExpression()); } }); return refs; } @NotNull public static List getMethods(@NotNull GoTypeSpec o) { return CachedValuesManager.getCachedValue(o, () -> { // todo[zolotov]: implement package modification tracker return CachedValueProvider.Result.create(calcMethods(o), PsiModificationTracker.MODIFICATION_COUNT); }); } public static boolean allowed(@NotNull PsiFile declarationFile, @Nullable PsiFile referenceFile, @Nullable Module contextModule) { if (!(declarationFile instanceof GoFile)) { return false; } VirtualFile referenceVirtualFile = referenceFile != null ? referenceFile.getOriginalFile().getVirtualFile() : null; if (!allowed(declarationFile.getVirtualFile(), referenceVirtualFile)) { return false; } if (GoConstants.DOCUMENTATION.equals(((GoFile)declarationFile).getPackageName())) { return false; } return GoUtil.matchedForModuleBuildTarget(declarationFile, contextModule); } public static boolean allowed(@Nullable VirtualFile declarationFile, @Nullable VirtualFile referenceFile) { if (declarationFile == null) { return true; } if (GoUtil.fileToIgnore(declarationFile.getName())) { return false; } // it's not a test or context file is also test from the same package return referenceFile == null || !GoTestFinder.isTestFile(declarationFile) || GoTestFinder.isTestFile(referenceFile) && Comparing.equal(referenceFile.getParent(), declarationFile.getParent()); } static boolean processNamedElements(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @NotNull Collection elements, boolean localResolve) { //noinspection unchecked return processNamedElements(processor, state, elements, Condition.TRUE, localResolve, false); } static boolean processNamedElements(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @NotNull Collection elements, boolean localResolve, boolean checkContainingFile) { //noinspection unchecked return processNamedElements(processor, state, elements, Condition.TRUE, localResolve, checkContainingFile); } static boolean processNamedElements(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @NotNull Collection elements, @NotNull Condition condition, boolean localResolve, boolean checkContainingFile) { PsiFile contextFile = checkContainingFile ? GoReference.getContextFile(state) : null; Module module = contextFile != null ? ModuleUtilCore.findModuleForPsiElement(contextFile) : null; for (GoNamedElement definition : elements) { if (!condition.value(definition)) continue; if (!definition.isValid() || checkContainingFile && !allowed(definition.getContainingFile(), contextFile, module)) continue; if ((localResolve || definition.isPublic()) && !processor.execute(definition, state)) return false; } return true; } public static boolean processSignatureOwner(@NotNull GoSignatureOwner o, @NotNull GoScopeProcessorBase processor) { GoSignature signature = o.getSignature(); if (signature == null) return true; if (!processParameters(processor, signature.getParameters())) return false; GoResult result = signature.getResult(); GoParameters resultParameters = result != null ? result.getParameters() : null; return resultParameters == null || processParameters(processor, resultParameters); } private static boolean processParameters(@NotNull GoScopeProcessorBase processor, @NotNull GoParameters parameters) { for (GoParameterDeclaration declaration : parameters.getParameterDeclarationList()) { if (!processNamedElements(processor, ResolveState.initial(), declaration.getParamDefinitionList(), true)) return false; } return true; } @NotNull public static String joinPsiElementText(List items) { return StringUtil.join(items, PsiElement::getText, ", "); } @Nullable public static PsiElement getBreakStatementOwner(@NotNull PsiElement breakStatement) { GoCompositeElement owner = PsiTreeUtil.getParentOfType(breakStatement, GoSwitchStatement.class, GoForStatement.class, GoSelectStatement.class, GoFunctionLit.class); return owner instanceof GoFunctionLit ? null : owner; } @NotNull private static List calcMethods(@NotNull GoTypeSpec o) { PsiFile file = o.getContainingFile().getOriginalFile(); if (file instanceof GoFile) { String packageName = ((GoFile)file).getPackageName(); String typeName = o.getName(); if (StringUtil.isEmpty(packageName) || StringUtil.isEmpty(typeName)) return Collections.emptyList(); String key = packageName + "." + typeName; Project project = ((GoFile)file).getProject(); GlobalSearchScope scope = GoPackageUtil.packageScope((GoFile)file); Collection declarations = GoMethodIndex.find(key, project, scope, GoIdFilter.getFilesFilter(scope)); return ContainerUtil.newArrayList(declarations); } return Collections.emptyList(); } @NotNull public static GoType getUnderlyingType(@NotNull GoType o) { GoType type = RecursionManager.doPreventingRecursion(o, true, () -> getTypeInner(o)); return ObjectUtils.notNull(type, o); } @NotNull private static GoType getTypeInner(@NotNull GoType o) { if (o instanceof GoArrayOrSliceType | o instanceof GoStructType | o instanceof GoPointerType | o instanceof GoFunctionType | o instanceof GoInterfaceType | o instanceof GoMapType | o instanceof GoChannelType) { return o; } if (o instanceof GoParType) return ((GoParType)o).getActualType(); if (o instanceof GoSpecType) { GoType type = ((GoSpecType)o).getType(); return type != null ? type.getUnderlyingType() : o; } if (builtin(o)) return o; GoTypeReferenceExpression e = o.getTypeReferenceExpression(); GoType byRef = e == null ? null : e.resolveType(); if (byRef != null) { return byRef.getUnderlyingType(); } return o; } @Nullable public static GoType getGoTypeInner(@NotNull GoSignatureOwner o, @SuppressWarnings("UnusedParameters") @Nullable ResolveState context) { GoSignature signature = o.getSignature(); GoResult result = signature != null ? signature.getResult() : null; if (result != null) { GoType type = result.getType(); if (type instanceof GoTypeList && ((GoTypeList)type).getTypeList().size() == 1) { return ((GoTypeList)type).getTypeList().get(0); } if (type != null) return type; GoParameters parameters = result.getParameters(); if (parameters != null) { GoType parametersType = parameters.getType(); if (parametersType != null) return parametersType; List composite = ContainerUtil.newArrayList(); for (GoParameterDeclaration p : parameters.getParameterDeclarationList()) { for (GoParamDefinition definition : p.getParamDefinitionList()) { composite.add(definition.getGoType(context)); } } if (composite.size() == 1) return composite.get(0); return new LightTypeList(parameters, composite); } } return null; } @NotNull public static GoImportSpec addImport(@NotNull GoImportList importList, @NotNull String packagePath, @Nullable String alias) { Project project = importList.getProject(); GoImportDeclaration newDeclaration = GoElementFactory.createImportDeclaration(project, packagePath, alias, false); List existingImports = importList.getImportDeclarationList(); for (int i = existingImports.size() - 1; i >= 0; i--) { GoImportDeclaration existingImport = existingImports.get(i); List importSpecList = existingImport.getImportSpecList(); if (importSpecList.isEmpty()) { continue; } if (existingImport.getRparen() == null && importSpecList.get(0).isCImport()) { continue; } return existingImport.addImportSpec(packagePath, alias); } return addImportDeclaration(importList, newDeclaration); } @NotNull private static GoImportSpec addImportDeclaration(@NotNull GoImportList importList, @NotNull GoImportDeclaration newImportDeclaration) { GoImportDeclaration lastImport = ContainerUtil.getLastItem(importList.getImportDeclarationList()); GoImportDeclaration importDeclaration = (GoImportDeclaration)importList.addAfter(newImportDeclaration, lastImport); PsiElement importListNextSibling = importList.getNextSibling(); if (!(importListNextSibling instanceof PsiWhiteSpace)) { importList.addAfter(GoElementFactory.createNewLine(importList.getProject()), importDeclaration); if (importListNextSibling != null) { // double new line if there is something valuable after import list importList.addAfter(GoElementFactory.createNewLine(importList.getProject()), importDeclaration); } } importList.addBefore(GoElementFactory.createNewLine(importList.getProject()), importDeclaration); GoImportSpec result = ContainerUtil.getFirstItem(importDeclaration.getImportSpecList()); assert result != null; return result; } @NotNull public static GoImportSpec addImportSpec(@NotNull GoImportDeclaration declaration, @NotNull String packagePath, @Nullable String alias) { PsiElement rParen = declaration.getRparen(); if (rParen == null) { GoImportDeclaration newDeclaration = GoElementFactory.createEmptyImportDeclaration(declaration.getProject()); for (GoImportSpec spec : declaration.getImportSpecList()) { newDeclaration.addImportSpec(spec.getPath(), spec.getAlias()); } declaration = (GoImportDeclaration)declaration.replace(newDeclaration); LOG.assertTrue(declaration.getRparen() != null); return declaration.addImportSpec(packagePath, alias); } declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), rParen); GoImportSpec newImportSpace = GoElementFactory.createImportSpec(declaration.getProject(), packagePath, alias); GoImportSpec spec = (GoImportSpec)declaration.addBefore(newImportSpace, rParen); declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), rParen); return spec; } public static String getLocalPackageName(@NotNull String importPath) { String fileName = !StringUtil.endsWithChar(importPath, '/') && !StringUtil.endsWithChar(importPath, '\\') ? PathUtil.getFileName(importPath) : ""; StringBuilder name = null; for (int i = 0; i < fileName.length(); i++) { char c = fileName.charAt(i); if (!(Character.isLetter(c) || c == '_' || i != 0 && Character.isDigit(c))) { if (name == null) { name = new StringBuilder(fileName.length()); name.append(fileName, 0, i); } name.append('_'); } else if (name != null) { name.append(c); } } return name == null ? fileName : name.toString(); } public static String getLocalPackageName(@NotNull GoImportSpec importSpec) { return getLocalPackageName(importSpec.getPath()); } public static boolean isCImport(@NotNull GoImportSpec importSpec) { return GoConstants.C_PATH.equals(importSpec.getPath()); } public static boolean isDot(@NotNull GoImportSpec importSpec) { GoImportSpecStub stub = importSpec.getStub(); return stub != null ? stub.isDot() : importSpec.getDot() != null; } @NotNull public static String getPath(@NotNull GoImportSpec importSpec) { GoImportSpecStub stub = importSpec.getStub(); return stub != null ? stub.getPath() : importSpec.getImportString().getPath(); } public static String getName(@NotNull GoImportSpec importSpec) { return getAlias(importSpec); } public static String getAlias(@NotNull GoImportSpec importSpec) { GoImportSpecStub stub = importSpec.getStub(); if (stub != null) { return stub.getAlias(); } PsiElement identifier = importSpec.getIdentifier(); if (identifier != null) { return identifier.getText(); } return importSpec.isDot() ? "." : null; } @Nullable public static String getImportQualifierToUseInFile(@Nullable GoImportSpec importSpec, @Nullable String defaultValue) { if (importSpec == null || importSpec.isForSideEffects()) { return null; } if (importSpec.isDot()) { return ""; } String alias = importSpec.getAlias(); if (alias != null) { return alias; } return defaultValue != null ? defaultValue : importSpec.getLocalPackageName(); } public static boolean shouldGoDeeper(@SuppressWarnings("UnusedParameters") GoImportSpec o) { return false; } public static boolean shouldGoDeeper(@SuppressWarnings("UnusedParameters") GoTypeSpec o) { return false; } public static boolean shouldGoDeeper(@NotNull GoType o) { return o instanceof GoInterfaceType || o instanceof GoStructType; } public static boolean isForSideEffects(@NotNull GoImportSpec o) { return "_".equals(o.getAlias()); } @NotNull public static String getPath(@NotNull GoImportString o) { return o.getStringLiteral().getDecodedText(); } @NotNull public static String unquote(@Nullable String s) { if (StringUtil.isEmpty(s)) return ""; char quote = s.charAt(0); int startOffset = isQuote(quote) ? 1 : 0; int endOffset = s.length(); if (s.length() > 1) { char lastChar = s.charAt(s.length() - 1); if (isQuote(quote) && lastChar == quote) { endOffset = s.length() - 1; } if (!isQuote(quote) && isQuote(lastChar)) { endOffset = s.length() - 1; } } return s.substring(startOffset, endOffset); } @NotNull public static TextRange getPathTextRange(@NotNull GoImportString importString) { String text = importString.getText(); return !text.isEmpty() && isQuote(text.charAt(0)) ? TextRange.create(1, text.length() - 1) : TextRange.EMPTY_RANGE; } public static boolean isQuotedImportString(@NotNull String s) { return s.length() > 1 && isQuote(s.charAt(0)) && s.charAt(0) == s.charAt(s.length() - 1); } private static boolean isQuote(char ch) { return ch == '"' || ch == '\'' || ch == '`'; } public static boolean isValidHost(@NotNull GoStringLiteral o) { return PsiTreeUtil.getParentOfType(o, GoImportString.class) == null; } @NotNull public static GoStringLiteralImpl updateText(@NotNull GoStringLiteral o, @NotNull String text) { if (text.length() > 2) { if (o.getString() != null) { StringBuilder outChars = new StringBuilder(); GoStringLiteralEscaper.escapeString(text.substring(1, text.length() - 1), outChars); outChars.insert(0, '"'); outChars.append('"'); text = outChars.toString(); } } ASTNode valueNode = o.getNode().getFirstChildNode(); assert valueNode instanceof LeafElement; ((LeafElement)valueNode).replaceWithText(text); return (GoStringLiteralImpl)o; } @NotNull public static GoStringLiteralEscaper createLiteralTextEscaper(@NotNull GoStringLiteral o) { return new GoStringLiteralEscaper(o); } public static boolean prevDot(@Nullable PsiElement e) { PsiElement prev = e == null ? null : PsiTreeUtil.prevVisibleLeaf(e); return prev instanceof LeafElement && ((LeafElement)prev).getElementType() == GoTypes.DOT; } @Nullable public static GoSignatureOwner resolveCall(@Nullable GoExpression call) { return ObjectUtils.tryCast(resolveCallRaw(call), GoSignatureOwner.class); } public static PsiElement resolveCallRaw(@Nullable GoExpression call) { if (!(call instanceof GoCallExpr)) return null; GoExpression e = ((GoCallExpr)call).getExpression(); if (e instanceof GoSelectorExpr) { GoExpression right = ((GoSelectorExpr)e).getRight(); PsiReference reference = right instanceof GoReferenceExpression ? right.getReference() : null; return reference != null ? reference.resolve() : null; } if (e instanceof GoCallExpr) { GoSignatureOwner resolve = resolveCall(e); if (resolve != null) { GoSignature signature = resolve.getSignature(); GoResult result = signature != null ? signature.getResult() : null; return result != null ? result.getType() : null; } return null; } if (e instanceof GoFunctionLit) { return e; } GoReferenceExpression r = e instanceof GoReferenceExpression ? (GoReferenceExpression)e : PsiTreeUtil.getChildOfType(e, GoReferenceExpression.class); PsiReference reference = (r != null ? r : e).getReference(); return reference != null ? reference.resolve() : null; } public static boolean isUnaryBitAndExpression(@Nullable PsiElement parent) { PsiElement grandParent = parent != null ? parent.getParent() : null; return grandParent instanceof GoUnaryExpr && ((GoUnaryExpr)grandParent).getBitAnd() != null; } @NotNull public static GoVarSpec addSpec(@NotNull GoVarDeclaration declaration, @NotNull String name, @Nullable String type, @Nullable String value, @Nullable GoVarSpec specAnchor) { Project project = declaration.getProject(); GoVarSpec newSpec = GoElementFactory.createVarSpec(project, name, type, value); PsiElement rParen = declaration.getRparen(); if (rParen == null) { GoVarSpec item = ContainerUtil.getFirstItem(declaration.getVarSpecList()); assert item != null; boolean updateAnchor = specAnchor == item; declaration = (GoVarDeclaration)declaration.replace(GoElementFactory.createVarDeclaration(project, "(" + item.getText() + ")")); rParen = declaration.getRparen(); if (updateAnchor) { specAnchor = ContainerUtil.getFirstItem(declaration.getVarSpecList()); } } assert rParen != null; PsiElement anchor = ObjectUtils.notNull(specAnchor, rParen); if (!hasNewLineBefore(anchor)) { declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), anchor); } GoVarSpec spec = (GoVarSpec)declaration.addBefore(newSpec, anchor); declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), anchor); return spec; } @NotNull public static GoConstSpec addSpec(@NotNull GoConstDeclaration declaration, @NotNull String name, @Nullable String type, @Nullable String value, @Nullable GoConstSpec specAnchor) { Project project = declaration.getProject(); GoConstSpec newSpec = GoElementFactory.createConstSpec(project, name, type, value); PsiElement rParen = declaration.getRparen(); if (rParen == null) { GoConstSpec item = ContainerUtil.getFirstItem(declaration.getConstSpecList()); assert item != null; boolean updateAnchor = specAnchor == item; declaration = (GoConstDeclaration)declaration.replace(GoElementFactory.createConstDeclaration(project, "(" + item.getText() + ")")); rParen = declaration.getRparen(); if (updateAnchor) { specAnchor = ContainerUtil.getFirstItem(declaration.getConstSpecList()); } } assert rParen != null; PsiElement anchor = ObjectUtils.notNull(specAnchor, rParen); if (!hasNewLineBefore(anchor)) { declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), anchor); } GoConstSpec spec = (GoConstSpec)declaration.addBefore(newSpec, anchor); declaration.addBefore(GoElementFactory.createNewLine(declaration.getProject()), anchor); return spec; } public static void deleteSpec(@NotNull GoVarDeclaration declaration, @NotNull GoVarSpec specToDelete) { List specList = declaration.getVarSpecList(); int index = specList.indexOf(specToDelete); assert index >= 0; if (specList.size() == 1) { declaration.delete(); return; } specToDelete.delete(); } public static void deleteSpec(@NotNull GoConstDeclaration declaration, @NotNull GoConstSpec specToDelete) { List specList = declaration.getConstSpecList(); int index = specList.indexOf(specToDelete); assert index >= 0; if (specList.size() == 1) { declaration.delete(); return; } specToDelete.delete(); } public static void deleteExpressionFromAssignment(@NotNull GoAssignmentStatement assignment, @NotNull GoExpression expressionToDelete) { GoExpression expressionValue = getRightExpression(assignment, expressionToDelete); if (expressionValue != null) { if (assignment.getExpressionList().size() == 1) { assignment.delete(); } else { deleteElementFromCommaSeparatedList(expressionToDelete); deleteElementFromCommaSeparatedList(expressionValue); } } } public static void deleteDefinition(@NotNull GoVarSpec spec, @NotNull GoVarDefinition definitionToDelete) { List definitionList = spec.getVarDefinitionList(); int index = definitionList.indexOf(definitionToDelete); assert index >= 0; if (definitionList.size() == 1) { PsiElement parent = spec.getParent(); if (parent instanceof GoVarDeclaration) { ((GoVarDeclaration)parent).deleteSpec(spec); } else { spec.delete(); } return; } GoExpression value = definitionToDelete.getValue(); if (value != null && spec.getRightExpressionsList().size() <= 1) { PsiElement assign = spec.getAssign(); if (assign != null) { assign.delete(); } } deleteElementFromCommaSeparatedList(value); deleteElementFromCommaSeparatedList(definitionToDelete); } public static void deleteDefinition(@NotNull GoConstSpec spec, @NotNull GoConstDefinition definitionToDelete) { List definitionList = spec.getConstDefinitionList(); int index = definitionList.indexOf(definitionToDelete); assert index >= 0; if (definitionList.size() == 1) { PsiElement parent = spec.getParent(); if (parent instanceof GoConstDeclaration) { ((GoConstDeclaration)parent).deleteSpec(spec); } else { spec.delete(); } return; } GoExpression value = definitionToDelete.getValue(); if (value != null && spec.getExpressionList().size() <= 1) { PsiElement assign = spec.getAssign(); if (assign != null) { assign.delete(); } } deleteElementFromCommaSeparatedList(value); deleteElementFromCommaSeparatedList(definitionToDelete); } private static void deleteElementFromCommaSeparatedList(@Nullable PsiElement element) { if (element == null) { return; } PsiElement prevVisibleLeaf = PsiTreeUtil.prevVisibleLeaf(element); PsiElement nextVisibleLeaf = PsiTreeUtil.nextVisibleLeaf(element); if (prevVisibleLeaf != null && prevVisibleLeaf.textMatches(",")) { prevVisibleLeaf.delete(); } else if (nextVisibleLeaf != null && nextVisibleLeaf.textMatches(",")) { nextVisibleLeaf.delete(); } element.delete(); } private static boolean hasNewLineBefore(@NotNull PsiElement anchor) { PsiElement prevSibling = anchor.getPrevSibling(); while (prevSibling instanceof PsiWhiteSpace) { if (prevSibling.textContains('\n')) { return true; } prevSibling = prevSibling.getPrevSibling(); } return false; } @Nullable public static GoExpression getValue(@NotNull GoVarDefinition definition) { PsiElement parent = definition.getParent(); if (parent instanceof GoVarSpec) { int index = ((GoVarSpec)parent).getVarDefinitionList().indexOf(definition); return getByIndex(((GoVarSpec)parent).getRightExpressionsList(), index); } if (parent instanceof GoTypeSwitchGuard) { return ((GoTypeSwitchGuard)parent).getExpression(); } LOG.error("Cannot find value for variable definition: " + definition.getText(), AttachmentFactory.createAttachment(definition.getContainingFile().getVirtualFile())); return null; } @Nullable public static GoExpression getValue(@NotNull GoConstDefinition definition) { PsiElement parent = definition.getParent(); assert parent instanceof GoConstSpec; int index = ((GoConstSpec)parent).getConstDefinitionList().indexOf(definition); return getByIndex(((GoConstSpec)parent).getExpressionList(), index); } private static T getByIndex(@NotNull List list, int index) { return 0 <= index && index < list.size() ? list.get(index) : null; } @Nullable public static GoTypeSpec getTypeSpecSafe(@NotNull GoType type) { GoTypeStub stub = type.getStub(); PsiElement parent = stub == null ? type.getParent() : stub.getParentStub().getPsi(); return ObjectUtils.tryCast(parent, GoTypeSpec.class); } public static boolean canBeAutoImported(@NotNull GoFile file, boolean allowMain, @Nullable Module module) { if (isBuiltinFile(file) || !allowMain && StringUtil.equals(file.getPackageName(), GoConstants.MAIN)) { return false; } return allowed(file, null, module) && !GoUtil.isExcludedFile(file); } @Nullable @Contract("null, _ -> null") public static T getNonStrictTopmostParentOfType(@Nullable PsiElement element, @NotNull Class aClass) { T first = PsiTreeUtil.getNonStrictParentOfType(element, aClass); T topMost = PsiTreeUtil.getTopmostParentOfType(first, aClass); return ObjectUtils.chooseNotNull(topMost, first); } @Nullable public static GoExpression getExpression(@NotNull GoIndexOrSliceExpr slice) { return ContainerUtil.getFirstItem(getExpressionsBefore(slice.getExpressionList(), slice.getLbrack())); } @NotNull public static List getLeftExpressionsList(@NotNull GoRangeClause rangeClause) { return getExpressionsBefore(rangeClause.getExpressionList(), rangeClause.getRange()); } @NotNull public static List getLeftExpressionsList(@NotNull GoRecvStatement recvStatement) { return getExpressionsBefore(recvStatement.getExpressionList(), ObjectUtils.chooseNotNull(recvStatement.getAssign(), recvStatement.getVarAssign())); } @NotNull public static Trinity getIndices(@NotNull GoIndexOrSliceExpr slice) { GoExpression start; GoExpression end = null; GoExpression max = null; ASTNode[] colons = slice.getNode().getChildren(TokenSet.create(GoTypes.COLON)); List exprList = slice.getExpressionList(); start = ContainerUtil.getFirstItem(getExpressionsInRange(exprList, slice.getLbrack(), colons.length > 0 ? colons[0].getPsi() : null)); if (colons.length == 1) { end = ContainerUtil.getFirstItem(getExpressionsInRange(exprList, colons[0].getPsi(), slice.getRbrack())); } if (colons.length == 2) { end = ContainerUtil.getFirstItem(getExpressionsInRange(exprList, colons[0].getPsi(), colons[1].getPsi())); max = ContainerUtil.getFirstItem(getExpressionsInRange(exprList, colons[1].getPsi(), slice.getRbrack())); } return Trinity.create(start, end, max); } @NotNull public static List getRightExpressionsList(@NotNull GoVarSpec varSpec) { return varSpec.getExpressionList(); } @NotNull public static List getRightExpressionsList(@NotNull GoRangeClause rangeClause) { return ContainerUtil.createMaybeSingletonList(rangeClause.getRangeExpression()); } @NotNull public static List getRightExpressionsList(@NotNull GoRecvStatement recvStatement) { return ContainerUtil.createMaybeSingletonList(recvStatement.getRecvExpression()); } @Nullable public static GoExpression getRangeExpression(@NotNull GoRangeClause rangeClause) { return getLastExpressionAfter(rangeClause.getExpressionList(), rangeClause.getRange()); } @Nullable public static GoExpression getRecvExpression(@NotNull GoRecvStatement recvStatement) { return getLastExpressionAfter(recvStatement.getExpressionList(), ObjectUtils.chooseNotNull(recvStatement.getAssign(), recvStatement.getVarAssign())); } @Nullable public static GoExpression getSendExpression(@NotNull GoSendStatement sendStatement) { return getLastExpressionAfter(sendStatement.getExpressionList(), sendStatement.getSendChannel()); } @Nullable private static GoExpression getLastExpressionAfter(@NotNull List list, @Nullable PsiElement anchor) { if (anchor == null) return null; GoExpression last = ContainerUtil.getLastItem(list); return last != null && last.getTextRange().getStartOffset() >= anchor.getTextRange().getEndOffset() ? last : null; } @NotNull private static List getExpressionsInRange(@NotNull List list, @Nullable PsiElement start, @Nullable PsiElement end) { if (start == null && end == null) { return list; } return ContainerUtil.filter(list, expression -> (end == null || expression.getTextRange().getEndOffset() <= end.getTextRange().getStartOffset()) && (start == null || expression.getTextRange().getStartOffset() >= start.getTextRange().getEndOffset())); } @NotNull private static List getExpressionsBefore(@NotNull List list, @Nullable PsiElement anchor) { return getExpressionsInRange(list, null, anchor); } @NotNull public static ReadWriteAccessDetector.Access getReadWriteAccess(@NotNull GoReferenceExpression referenceExpression) { GoExpression expression = getConsiderableExpression(referenceExpression); PsiElement parent = expression.getParent(); if (parent instanceof GoSelectorExpr) { if (expression.equals(((GoSelectorExpr)parent).getRight())) { expression = getConsiderableExpression((GoSelectorExpr)parent); parent = expression.getParent(); } else { return Read; } } if (parent instanceof GoIncDecStatement) { return Write; } if (parent instanceof GoLeftHandExprList) { PsiElement grandParent = parent.getParent(); if (grandParent instanceof GoAssignmentStatement) { return ((GoAssignmentStatement)grandParent).getAssignOp().getAssign() == null ? ReadWrite : Write; } if (grandParent instanceof GoSendStatement) { return Write; } return Read; } if (parent instanceof GoSendStatement && parent.getParent() instanceof GoCommCase) { return expression.equals(((GoSendStatement)parent).getSendExpression()) ? Read : ReadWrite; } if (parent instanceof GoRangeClause) { return expression.equals(((GoRangeClause)parent).getRangeExpression()) ? Read : Write; } if (parent instanceof GoRecvStatement) { return expression.equals(((GoRecvStatement)parent).getRecvExpression()) ? Read : Write; } return Read; } @NotNull private static GoExpression getConsiderableExpression(@NotNull GoExpression element) { GoExpression result = element; while (true) { PsiElement parent = result.getParent(); if (parent == null) { return result; } if (parent instanceof GoParenthesesExpr) { result = (GoParenthesesExpr)parent; continue; } if (parent instanceof GoUnaryExpr) { GoUnaryExpr unaryExpr = (GoUnaryExpr)parent; if (unaryExpr.getMul() != null || unaryExpr.getBitAnd() != null || unaryExpr.getSendChannel() != null) { result = (GoUnaryExpr)parent; continue; } } return result; } } @NotNull public static String getDecodedText(@NotNull GoStringLiteral o) { StringBuilder builder = new StringBuilder(); TextRange range = ElementManipulators.getManipulator(o).getRangeInElement(o); o.createLiteralTextEscaper().decode(range, builder); return builder.toString(); } @Nullable public static PsiElement getOperator(@NotNull GoUnaryExpr o) { return getNotNullElement(o.getNot(), o.getMinus(), o.getPlus(), o.getBitAnd(), o.getBitXor(), o.getMul(), o.getSendChannel()); } @Nullable public static PsiElement getOperator(@NotNull GoBinaryExpr o) { if (o instanceof GoAndExpr) return ((GoAndExpr)o).getCondAnd(); if (o instanceof GoOrExpr) return ((GoOrExpr)o).getCondOr(); if (o instanceof GoSelectorExpr) return ((GoSelectorExpr)o).getDot(); if (o instanceof GoConversionExpr) return ((GoConversionExpr)o).getComma(); if (o instanceof GoMulExpr) { GoMulExpr m = (GoMulExpr)o; return getNotNullElement(m.getMul(), m.getQuotient(), m.getRemainder(), m.getShiftRight(), m.getShiftLeft(), m.getBitAnd(), m.getBitClear()); } if (o instanceof GoAddExpr) { GoAddExpr a = (GoAddExpr)o; return getNotNullElement(a.getBitXor(), a.getBitOr(), a.getMinus(), a.getPlus()); } if (o instanceof GoConditionalExpr) { GoConditionalExpr c = (GoConditionalExpr)o; return getNotNullElement(c.getEq(), c.getNotEq(), c.getGreater(), c.getGreaterOrEqual(), c.getLess(), c.getLessOrEqual()); } return null; } @Nullable private static PsiElement getNotNullElement(@Nullable PsiElement... elements) { if (elements == null) return null; for (PsiElement e : elements) { if (e != null) return e; } return null; } public static boolean isSingleCharLiteral(@NotNull GoStringLiteral literal) { return literal.getDecodedText().length() == 1; } @Nullable public static GoExpression getRightExpression(@NotNull GoAssignmentStatement assignment, @NotNull GoExpression leftExpression) { int fieldIndex = assignment.getLeftHandExprList().getExpressionList().indexOf(leftExpression); return getByIndex(assignment.getExpressionList(), fieldIndex); } } ================================================ FILE: src/com/goide/psi/impl/GoReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoConstants; import com.goide.psi.*; import com.goide.util.GoUtil; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.*; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OrderedSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import static com.goide.psi.impl.GoPsiImplUtil.*; public class GoReference extends GoReferenceBase { private static final Key POINTER = Key.create("POINTER"); private static final Key DONT_PROCESS_METHODS = Key.create("DONT_PROCESS_METHODS"); private static final ResolveCache.PolyVariantResolver MY_RESOLVER = (r, incompleteCode) -> r.resolveInner(); public GoReference(@NotNull GoReferenceExpressionBase o) { super(o, TextRange.from(o.getIdentifier().getStartOffsetInParent(), o.getIdentifier().getTextLength())); } @Nullable static PsiFile getContextFile(@NotNull ResolveState state) { PsiElement element = getContextElement(state); return element != null ? element.getContainingFile() : null; } @NotNull private ResolveResult[] resolveInner() { if (!myElement.isValid()) return ResolveResult.EMPTY_ARRAY; Collection result = new OrderedSet<>(); processResolveVariants(createResolveProcessor(result, myElement)); return result.toArray(new ResolveResult[result.size()]); } @Override public boolean isReferenceTo(@NotNull PsiElement element) { return GoUtil.couldBeReferenceTo(element, myElement) && super.isReferenceTo(element); } @NotNull private PsiElement getIdentifier() { return myElement.getIdentifier(); } @Override @NotNull public ResolveResult[] multiResolve(boolean incompleteCode) { if (!myElement.isValid()) return ResolveResult.EMPTY_ARRAY; return ResolveCache.getInstance(myElement.getProject()).resolveWithCaching(this, MY_RESOLVER, false, false); } @NotNull @Override public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean processResolveVariants(@NotNull GoScopeProcessor processor) { PsiFile file = myElement.getContainingFile(); if (!(file instanceof GoFile)) return false; ResolveState state = createContextOnElement(myElement); GoReferenceExpressionBase qualifier = myElement.getQualifier(); return qualifier != null ? processQualifierExpression((GoFile)file, qualifier, processor, state) : processUnqualifiedResolve((GoFile)file, processor, state); } private boolean processQualifierExpression(@NotNull GoFile file, @NotNull GoReferenceExpressionBase qualifier, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { PsiReference reference = qualifier.getReference(); PsiElement target = reference != null ? reference.resolve() : null; if (target == null) return false; if (target == qualifier) return processor.execute(myElement, state); if (target instanceof GoImportSpec) { if (((GoImportSpec)target).isCImport()) return processor.execute(myElement, state); target = ((GoImportSpec)target).getImportString().resolve(); } if (target instanceof PsiDirectory && !processDirectory((PsiDirectory)target, file, null, processor, state, false)) return false; if (target instanceof GoTypeOwner) { GoType type = typeOrParameterType((GoTypeOwner)target, createContextOnElement(myElement)); if (type instanceof GoCType) return processor.execute(myElement, state); if (type != null) { if (!processGoType(type, processor, state)) return false; GoTypeReferenceExpression ref = getTypeRefExpression(type); if (ref != null && ref.resolve() == ref) return processor.execute(myElement, state); // a bit hacky resolve for: var a C.foo; a.b } } return true; } private boolean processGoType(@NotNull GoType type, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { Boolean result = RecursionManager.doPreventingRecursion(type, true, () -> { if (type instanceof GoParType) return processGoType(((GoParType)type).getActualType(), processor, state); if (!processExistingType(type, processor, state)) return false; if (type instanceof GoPointerType) { if (!processPointer((GoPointerType)type, processor, state.put(POINTER, true))) return false; GoType pointer = ((GoPointerType)type).getType(); if (pointer instanceof GoPointerType) { return processPointer((GoPointerType)pointer, processor, state.put(POINTER, true)); } } return processTypeRef(type, processor, state); }); return Boolean.TRUE.equals(result); } private boolean processPointer(@NotNull GoPointerType type, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { GoType pointer = type.getType(); return pointer == null || processExistingType(pointer, processor, state) && processTypeRef(pointer, processor, state); } private boolean processTypeRef(@Nullable GoType type, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { if (type == null) { return true; } if (builtin(type)) { // do not process builtin types like 'int int' or 'string string' return true; } return processInTypeRef(type.getTypeReferenceExpression(), processor, state); } private boolean processExistingType(@NotNull GoType type, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { PsiFile file = type.getContainingFile(); if (!(file instanceof GoFile)) return true; PsiFile myFile = ObjectUtils.notNull(getContextFile(state), myElement.getContainingFile()); if (!(myFile instanceof GoFile) || !allowed(file, myFile, ModuleUtilCore.findModuleForPsiElement(myFile))) return true; boolean localResolve = isLocalResolve(myFile, file); GoTypeSpec parent = getTypeSpecSafe(type); boolean canProcessMethods = state.get(DONT_PROCESS_METHODS) == null; if (canProcessMethods && parent != null && !processNamedElements(processor, state, parent.getMethods(), localResolve, true)) return false; if (type instanceof GoSpecType) { type = type.getUnderlyingType(); } if (type instanceof GoStructType) { GoScopeProcessorBase delegate = createDelegate(processor); type.processDeclarations(delegate, ResolveState.initial(), null, myElement); List interfaceRefs = ContainerUtil.newArrayList(); List structRefs = ContainerUtil.newArrayList(); for (GoFieldDeclaration d : ((GoStructType)type).getFieldDeclarationList()) { if (!processNamedElements(processor, state, d.getFieldDefinitionList(), localResolve)) return false; GoAnonymousFieldDefinition anon = d.getAnonymousFieldDefinition(); GoTypeReferenceExpression ref = anon != null ? anon.getTypeReferenceExpression() : null; if (ref != null) { (anon.getType() instanceof GoPointerType ? structRefs : interfaceRefs).add(ref); if (!processNamedElements(processor, state, ContainerUtil.createMaybeSingletonList(anon), localResolve)) return false; } } if (!processCollectedRefs(interfaceRefs, processor, state.put(POINTER, null))) return false; if (!processCollectedRefs(structRefs, processor, state)) return false; } else if (state.get(POINTER) == null && type instanceof GoInterfaceType) { if (!processNamedElements(processor, state, ((GoInterfaceType)type).getMethods(), localResolve, true)) return false; if (!processCollectedRefs(((GoInterfaceType)type).getBaseTypesReferences(), processor, state)) return false; } else if (type instanceof GoFunctionType) { GoSignature signature = ((GoFunctionType)type).getSignature(); GoResult result = signature != null ? signature.getResult() : null; GoType resultType = result != null ? result.getType() : null; if (resultType != null && !processGoType(resultType, processor, state)) return false; } return true; } public static boolean isLocalResolve(@NotNull PsiFile originFile, @NotNull PsiFile externalFile) { if (!(originFile instanceof GoFile) || !(externalFile instanceof GoFile)) return false; GoFile o1 = (GoFile)originFile.getOriginalFile(); GoFile o2 = (GoFile)externalFile.getOriginalFile(); return Comparing.equal(o1.getImportPath(false), o2.getImportPath(false)) && Comparing.equal(o1.getPackageName(), o2.getPackageName()); } private boolean processCollectedRefs(@NotNull List refs, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { for (GoTypeReferenceExpression ref : refs) { if (!processInTypeRef(ref, processor, state)) return false; } return true; } private boolean processInTypeRef(@Nullable GoTypeReferenceExpression e, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { PsiElement resolve = e != null ? e.resolve() : null; if (resolve instanceof GoTypeOwner) { GoType type = ((GoTypeOwner)resolve).getGoType(state); if (type == null) return true; if (!processGoType(type, processor, state)) return false; if (type instanceof GoSpecType) { GoType inner = ((GoSpecType)type).getType(); if (inner instanceof GoPointerType && state.get(POINTER) != null) return true; if (inner != null && !processGoType(inner, processor, state.put(DONT_PROCESS_METHODS, true))) return false; } return true; } return true; } private boolean processUnqualifiedResolve(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { if (getIdentifier().textMatches("_")) return processor.execute(myElement, state); PsiElement parent = myElement.getParent(); if (parent instanceof GoSelectorExpr) { boolean result = processSelector((GoSelectorExpr)parent, processor, state, myElement); if (processor.isCompletion()) return result; if (!result || prevDot(myElement)) return false; } PsiElement grandPa = parent.getParent(); if (grandPa instanceof GoSelectorExpr && !processSelector((GoSelectorExpr)grandPa, processor, state, parent)) return false; if (prevDot(parent)) return false; if (!processBlock(processor, state, true)) return false; if (!processReceiver(processor, state, true)) return false; if (!processImports(file, processor, state, myElement)) return false; if (!processFileEntities(file, processor, state, true)) return false; if (!processDirectory(file.getOriginalFile().getParent(), file, file.getPackageName(), processor, state, true)) return false; return processBuiltin(processor, state, myElement); } private boolean processReceiver(@NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localResolve) { GoScopeProcessorBase delegate = createDelegate(processor); GoMethodDeclaration method = PsiTreeUtil.getParentOfType(myElement, GoMethodDeclaration.class); GoReceiver receiver = method != null ? method.getReceiver() : null; if (receiver == null) return true; receiver.processDeclarations(delegate, ResolveState.initial(), null, myElement); return processNamedElements(processor, state, delegate.getVariants(), localResolve); } private boolean processBlock(@NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localResolve) { GoScopeProcessorBase delegate = createDelegate(processor); ResolveUtil.treeWalkUp(myElement, delegate); return processNamedElements(processor, state, delegate.getVariants(), localResolve); } private boolean processSelector(@NotNull GoSelectorExpr parent, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement another) { List list = parent.getExpressionList(); if (list.size() > 1 && list.get(1).isEquivalentTo(another)) { GoExpression e = list.get(0); List refs = ContainerUtil.newArrayList(PsiTreeUtil.findChildrenOfType(e, GoReferenceExpression.class)); GoExpression o = refs.size() > 1 ? refs.get(refs.size() - 1) : e; PsiReference ref = o.getReference(); PsiElement resolve = ref != null ? ref.resolve() : null; if (resolve == o) return processor.execute(myElement, state); // var c = C.call(); c.a.b.d; GoType type = e.getGoType(createContextOnElement(myElement)); if (type != null && !processGoType(type, processor, state)) return false; } return true; } @NotNull private GoVarProcessor createDelegate(@NotNull GoScopeProcessor processor) { return new GoVarProcessor(getIdentifier(), myElement, processor.isCompletion(), true) { @Override protected boolean crossOff(@NotNull PsiElement e) { if (e instanceof GoFieldDefinition) return true; return super.crossOff(e) && !(e instanceof GoTypeSpec); } }; } @Override protected boolean processFileEntities(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localProcessing) { if (!processNamedElements(processor, state, file.getConstants(), o -> !Comparing.equal(GoConstants.IOTA, o.getName()) || !builtin(o) || PsiTreeUtil.getParentOfType(getContextElement(state), GoConstSpec.class) != null, localProcessing, false)) return false; if (!processNamedElements(processor, state, file.getVars(), localProcessing)) return false; Condition dontProcessInit = o -> o instanceof GoFunctionDeclaration && !Comparing.equal(o.getName(), GoConstants.INIT); if (!processNamedElements(processor, state, file.getFunctions(), dontProcessInit, localProcessing, false)) return false; return processNamedElements(processor, state, file.getTypes(), localProcessing); } @NotNull @Override public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException { getIdentifier().replace(GoElementFactory.createIdentifierFromText(myElement.getProject(), newElementName)); return myElement; } @Override public boolean equals(Object o) { return this == o || o instanceof GoReference && getElement() == ((GoReference)o).getElement(); } @Override public int hashCode() { return getElement().hashCode(); } } ================================================ FILE: src/com/goide/psi/impl/GoReferenceBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.goide.sdk.GoSdkUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.Map; import static com.goide.psi.impl.GoPsiImplUtil.allowed; public abstract class GoReferenceBase extends PsiPolyVariantReferenceBase { public static final Key> IMPORT_USERS = Key.create("IMPORT_USERS"); public static final Key ACTUAL_NAME = Key.create("ACTUAL_NAME"); public GoReferenceBase(T element, TextRange range) { super(element, range); } @Nullable protected static String getPath(@Nullable PsiFile file) { if (file == null) return null; VirtualFile virtualFile = file.getOriginalFile().getVirtualFile(); return virtualFile == null ? null : virtualFile.getPath(); } private static void putIfAbsent(@NotNull GoImportSpec importSpec, @NotNull PsiElement usage) { //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (importSpec) { List newUsages = ContainerUtil.newSmartList(usage); newUsages.addAll(IMPORT_USERS.get(importSpec, ContainerUtil.emptyList())); importSpec.putUserData(IMPORT_USERS, newUsages); } } protected boolean processDirectory(@Nullable PsiDirectory dir, @Nullable GoFile file, @Nullable String packageName, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localProcessing) { if (dir == null) return true; String filePath = getPath(file); Module module = file != null ? ModuleUtilCore.findModuleForPsiElement(file) : null; for (PsiFile f : dir.getFiles()) { if (!(f instanceof GoFile) || Comparing.equal(getPath(f), filePath)) continue; if (packageName != null && !packageName.equals(((GoFile)f).getPackageName())) continue; if (!allowed(f, file, module)) continue; if (!processFileEntities((GoFile)f, processor, state, localProcessing)) return false; } return true; } protected boolean processBuiltin(@NotNull GoScopeProcessor processor, @NotNull ResolveState state, @NotNull GoCompositeElement element) { GoFile builtin = GoSdkUtil.findBuiltinFile(element); return builtin == null || processFileEntities(builtin, processor, state, true); } protected boolean processImports(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, @NotNull GoCompositeElement element) { for (Map.Entry> entry : file.getImportMap().entrySet()) { for (GoImportSpec o : entry.getValue()) { if (o.isForSideEffects()) continue; GoImportString importString = o.getImportString(); if (o.isDot()) { PsiDirectory implicitDir = importString.resolve(); boolean resolved = !processDirectory(implicitDir, file, null, processor, state, false); if (resolved && !processor.isCompletion()) { putIfAbsent(o, element); } if (resolved) return false; } else { if (o.getAlias() == null) { PsiDirectory resolve = importString.resolve(); if (resolve != null && !processor.execute(resolve, state.put(ACTUAL_NAME, entry.getKey()))) return false; } // todo: multi-resolve into appropriate package clauses if (!processor.execute(o, state.put(ACTUAL_NAME, entry.getKey()))) return false; } } } return true; } @NotNull protected GoScopeProcessor createResolveProcessor(@NotNull Collection result, @NotNull GoReferenceExpressionBase o) { return new GoScopeProcessor() { @Override public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) { if (element.equals(o)) return !result.add(new PsiElementResolveResult(element)); String name = ObjectUtils.chooseNotNull(state.get(ACTUAL_NAME), element instanceof PsiNamedElement ? ((PsiNamedElement)element).getName() : null); if (name != null && o.getIdentifier().textMatches(name)) { result.add(new PsiElementResolveResult(element)); return false; } return true; } }; } protected abstract boolean processFileEntities(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localProcessing); } ================================================ FILE: src/com/goide/psi/impl/GoScopeProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.intellij.psi.scope.BaseScopeProcessor; abstract public class GoScopeProcessor extends BaseScopeProcessor { public boolean isCompletion() { return false; } } ================================================ FILE: src/com/goide/psi/impl/GoScopeProcessorBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoNamedElement; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OrderedSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public abstract class GoScopeProcessorBase extends GoScopeProcessor { @NotNull private final OrderedSet myResult = new OrderedSet<>(); @NotNull protected final PsiElement myOrigin; @NotNull private final PsiElement myRequestedNameElement; protected final boolean myIsCompletion; public GoScopeProcessorBase(@NotNull PsiElement origin) { this(origin, origin, false); } public GoScopeProcessorBase(@NotNull PsiElement requestedNameElement, @NotNull PsiElement origin, boolean completion) { myRequestedNameElement = requestedNameElement; myOrigin = origin; myIsCompletion = completion; } @Override public boolean execute(@NotNull PsiElement e, @NotNull ResolveState state) { if (e instanceof GoFunctionOrMethodDeclaration) return false; if (!(e instanceof GoNamedElement)) return true; String name = ((GoNamedElement)e).getName(); if (StringUtil.isEmpty(name) || !myIsCompletion && !myRequestedNameElement.textMatches(name)) return true; if (crossOff(e)) return true; if (e.equals(myOrigin)) return true; return add((GoNamedElement)e) || myIsCompletion; } protected boolean add(@NotNull GoNamedElement psiElement) { return !myResult.add(psiElement); } @Nullable public GoNamedElement getResult() { return ContainerUtil.getFirstItem(myResult); } @NotNull public List getVariants() { return myResult; } protected abstract boolean crossOff(@NotNull PsiElement e); } ================================================ FILE: src/com/goide/psi/impl/GoStubbedElementImpl.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoCompositeElement; import com.goide.psi.GoFile; import com.goide.stubs.TextHolder; import com.intellij.extapi.psi.StubBasedPsiElementBase; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.SmartList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public abstract class GoStubbedElementImpl> extends StubBasedPsiElementBase implements GoCompositeElement { public GoStubbedElementImpl(@NotNull T stub, @NotNull IStubElementType nodeType) { super(stub, nodeType); } public GoStubbedElementImpl(@NotNull ASTNode node) { super(node); } @Override public String toString() { return getElementType().toString(); } @Nullable @Override public String getText() { T stub = getStub(); if (stub instanceof TextHolder) { String text = ((TextHolder)stub).getText(); if (text != null) return text; } return super.getText(); } @Override public PsiElement getParent() { return getParentByStub(); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return GoCompositeElementImpl.processDeclarationsDefault(this, processor, state, lastParent, place); } @NotNull @Override public GoFile getContainingFile() { return (GoFile)super.getContainingFile(); } @Override public boolean shouldGoDeeper() { return true; } } ================================================ FILE: src/com/goide/psi/impl/GoTypeProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoTypeReferenceExpression; import com.goide.psi.GoTypeSpec; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public class GoTypeProcessor extends GoScopeProcessorBase { public GoTypeProcessor(@NotNull GoTypeReferenceExpression origin, boolean completion) { super(origin.getIdentifier(), origin, completion); } @Override protected boolean crossOff(@NotNull PsiElement e) { return !(e instanceof GoTypeSpec); } } ================================================ FILE: src/com/goide/psi/impl/GoTypeReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoConstants; import com.goide.GoTypes; import com.goide.psi.*; import com.goide.sdk.GoSdkUtil; import com.goide.util.GoUtil; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.impl.source.resolve.ResolveCache; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OrderedSet; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import java.util.Set; public class GoTypeReference extends GoReferenceBase { private final boolean myInsideInterfaceType; public GoTypeReference(@NotNull GoTypeReferenceExpression o) { super(o, TextRange.from(o.getIdentifier().getStartOffsetInParent(), o.getIdentifier().getTextLength())); myInsideInterfaceType = myElement.getParent() instanceof GoMethodSpec; } private static final ResolveCache.PolyVariantResolver MY_RESOLVER = (psiPolyVariantReferenceBase, incompleteCode) -> ((GoTypeReference)psiPolyVariantReferenceBase).resolveInner(); @NotNull private ResolveResult[] resolveInner() { Collection result = new OrderedSet<>(); processResolveVariants(createResolveProcessor(result, myElement)); return result.toArray(new ResolveResult[result.size()]); } @Override public boolean isReferenceTo(PsiElement element) { return GoUtil.couldBeReferenceTo(element, myElement) && super.isReferenceTo(element); } @NotNull private PsiElement getIdentifier() { return myElement.getIdentifier(); } @Override @NotNull public ResolveResult[] multiResolve(boolean incompleteCode) { return myElement.isValid() ? ResolveCache.getInstance(myElement.getProject()).resolveWithCaching(this, MY_RESOLVER, false, false) : ResolveResult.EMPTY_ARRAY; } @NotNull @Override public Object[] getVariants() { return ArrayUtil.EMPTY_OBJECT_ARRAY; } public boolean processResolveVariants(@NotNull GoScopeProcessor processor) { PsiFile file = myElement.getContainingFile(); if (!(file instanceof GoFile)) return false; ResolveState state = ResolveState.initial(); GoTypeReferenceExpression qualifier = myElement.getQualifier(); if (qualifier != null) { return processQualifierExpression((GoFile)file, qualifier, processor, state); } return processUnqualifiedResolve((GoFile)file, processor, state, true); } private boolean processQualifierExpression(@NotNull GoFile file, @NotNull GoTypeReferenceExpression qualifier, @NotNull GoScopeProcessor processor, @NotNull ResolveState state) { PsiElement target = qualifier.resolve(); if (target == null || target == qualifier) return false; if (target instanceof GoImportSpec) { if (((GoImportSpec)target).isCImport()) return processor.execute(myElement, state); target = ((GoImportSpec)target).getImportString().resolve(); } if (target instanceof PsiDirectory) { processDirectory((PsiDirectory)target, file, null, processor, state, false); } return false; } private boolean processUnqualifiedResolve(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localResolve) { GoScopeProcessorBase delegate = createDelegate(processor); ResolveUtil.treeWalkUp(myElement, delegate); Collection result = delegate.getVariants(); if (!processNamedElements(processor, state, result, localResolve)) return false; if (!processFileEntities(file, processor, state, localResolve)) return false; PsiDirectory dir = file.getOriginalFile().getParent(); if (!processDirectory(dir, file, file.getPackageName(), processor, state, true)) return false; if (PsiTreeUtil.getParentOfType(getElement(), GoReceiver.class) != null) return true; if (!processImports(file, processor, state, myElement)) return false; if (!processBuiltin(processor, state, myElement)) return false; if (getIdentifier().textMatches(GoConstants.NIL) && PsiTreeUtil.getParentOfType(myElement, GoTypeCaseClause.class) != null) { GoType type = PsiTreeUtil.getParentOfType(myElement, GoType.class); if (FormatterUtil.getPrevious(type != null ? type.getNode() : null, GoTypes.CASE) == null) return true; GoFile builtinFile = GoSdkUtil.findBuiltinFile(myElement); if (builtinFile == null) return false; GoVarDefinition nil = ContainerUtil.find(builtinFile.getVars(), v -> GoConstants.NIL.equals(v.getName())); if (nil != null && !processor.execute(nil, state)) return false; } return true; } public final static Set DOC_ONLY_TYPES = ContainerUtil.set("Type", "Type1", "IntegerType", "FloatType", "ComplexType"); private static final Condition BUILTIN_TYPE = spec -> { String name = spec.getName(); return name != null && !DOC_ONLY_TYPES.contains(name); }; @NotNull private GoTypeProcessor createDelegate(@NotNull GoScopeProcessor processor) { return new GoTypeProcessor(myElement, processor.isCompletion()); } @Override protected boolean processFileEntities(@NotNull GoFile file, @NotNull GoScopeProcessor processor, @NotNull ResolveState state, boolean localProcessing) { List types = GoPsiImplUtil.isBuiltinFile(file) ? ContainerUtil.filter(file.getTypes(), BUILTIN_TYPE) : file.getTypes(); return processNamedElements(processor, state, types, localProcessing); } private boolean processNamedElements(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @NotNull Collection elements, boolean localResolve) { for (GoNamedElement definition : elements) { if (definition instanceof GoTypeSpec && !allowed((GoTypeSpec)definition)) continue; if ((definition.isPublic() || localResolve) && !processor.execute(definition, state)) return false; } return true; } public boolean allowed(@NotNull GoTypeSpec definition) { return !myInsideInterfaceType || definition.getSpecType().getType() instanceof GoInterfaceType; } @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { getIdentifier().replace(GoElementFactory.createIdentifierFromText(myElement.getProject(), newElementName)); return myElement; } } ================================================ FILE: src/com/goide/psi/impl/GoTypeUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoConstants; import com.goide.psi.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoTypeUtil { /** * https://golang.org/ref/spec#For_statements * The expression on the right in the "range" clause is called the range expression, * which may be an array, pointer to an array, slice, string, map, or channel permitting receive operations. */ public static boolean isIterable(@Nullable GoType type) { type = type != null ? type.getUnderlyingType() : null; return type instanceof GoArrayOrSliceType || type instanceof GoPointerType && isArray(((GoPointerType)type).getType()) || type instanceof GoMapType || type instanceof GoChannelType || isString(type); } private static boolean isArray(@Nullable GoType type) { type = type != null ? type.getUnderlyingType() : null; return type instanceof GoArrayOrSliceType && ((GoArrayOrSliceType)type).getExpression() != null; } public static boolean isString(@Nullable GoType type) { return isBuiltinType(type, "string"); } public static boolean isBoolean(@Nullable GoType type) { return isBuiltinType(type, "bool"); } private static boolean isBuiltinType(@Nullable GoType type, @Nullable String builtinTypeName) { if (builtinTypeName == null) return false; type = type != null ? type.getUnderlyingType() : null; return type != null && !(type instanceof GoCType) && type.textMatches(builtinTypeName) && GoPsiImplUtil.builtin(type); } @NotNull public static List getExpectedTypes(@NotNull GoExpression expression) { PsiElement parent = expression.getParent(); if (parent == null) return Collections.emptyList(); if (parent instanceof GoAssignmentStatement) { return getExpectedTypesFromAssignmentStatement(expression, (GoAssignmentStatement)parent); } if (parent instanceof GoRangeClause) { return Collections.singletonList(getGoType(null, parent)); } if (parent instanceof GoRecvStatement) { return getExpectedTypesFromRecvStatement((GoRecvStatement)parent); } if (parent instanceof GoVarSpec) { return getExpectedTypesFromVarSpec(expression, (GoVarSpec)parent); } if (parent instanceof GoArgumentList) { return getExpectedTypesFromArgumentList(expression, (GoArgumentList)parent); } if (parent instanceof GoUnaryExpr) { GoUnaryExpr unaryExpr = (GoUnaryExpr)parent; if (unaryExpr.getSendChannel() != null) { GoType type = ContainerUtil.getFirstItem(getExpectedTypes(unaryExpr)); GoType chanType = GoElementFactory.createType(parent.getProject(), "chan " + getInterfaceIfNull(type, parent).getText()); return Collections.singletonList(chanType); } else { return Collections.singletonList(getGoType(null, parent)); } } if (parent instanceof GoSendStatement || parent instanceof GoLeftHandExprList && parent.getParent() instanceof GoSendStatement) { GoSendStatement sendStatement = (GoSendStatement)(parent instanceof GoSendStatement ? parent : parent.getParent()); return getExpectedTypesFromGoSendStatement(expression, sendStatement); } if (parent instanceof GoExprCaseClause) { return getExpectedTypesFromExprCaseClause((GoExprCaseClause)parent); } return Collections.emptyList(); } @NotNull private static List getExpectedTypesFromExprCaseClause(@NotNull GoExprCaseClause exprCaseClause) { GoExprSwitchStatement switchStatement = PsiTreeUtil.getParentOfType(exprCaseClause, GoExprSwitchStatement.class); assert switchStatement != null; GoExpression switchExpr = switchStatement.getExpression(); if (switchExpr != null) { return Collections.singletonList(getGoType(switchExpr, exprCaseClause)); } GoStatement statement = switchStatement.getStatement(); if (statement == null) { return Collections.singletonList(getInterfaceIfNull(GoPsiImplUtil.getBuiltinType("bool", exprCaseClause), exprCaseClause)); } GoLeftHandExprList leftHandExprList = statement instanceof GoSimpleStatement ? ((GoSimpleStatement)statement).getLeftHandExprList() : null; GoExpression expr = leftHandExprList != null ? ContainerUtil.getFirstItem(leftHandExprList.getExpressionList()) : null; return Collections.singletonList(getGoType(expr, exprCaseClause)); } @NotNull private static List getExpectedTypesFromGoSendStatement(@NotNull GoExpression expression, @NotNull GoSendStatement statement) { GoLeftHandExprList leftHandExprList = statement.getLeftHandExprList(); GoExpression channel = ContainerUtil.getFirstItem(leftHandExprList != null ? leftHandExprList.getExpressionList() : statement.getExpressionList()); GoExpression sendExpr = statement.getSendExpression(); assert channel != null; if (expression.isEquivalentTo(sendExpr)) { GoType chanType = channel.getGoType(null); if (chanType instanceof GoChannelType) { return Collections.singletonList(getInterfaceIfNull(((GoChannelType)chanType).getType(), statement)); } } if (expression.isEquivalentTo(channel)) { GoType type = sendExpr != null ? sendExpr.getGoType(null) : null; GoType chanType = GoElementFactory.createType(statement.getProject(), "chan " + getInterfaceIfNull(type, statement).getText()); return Collections.singletonList(chanType); } return Collections.singletonList(getInterfaceIfNull(null, statement)); } @NotNull private static List getExpectedTypesFromArgumentList(@NotNull GoExpression expression, @NotNull GoArgumentList argumentList) { PsiElement parentOfParent = argumentList.getParent(); assert parentOfParent instanceof GoCallExpr; PsiReference reference = ((GoCallExpr)parentOfParent).getExpression().getReference(); if (reference != null) { PsiElement resolve = reference.resolve(); if (resolve instanceof GoFunctionOrMethodDeclaration) { GoSignature signature = ((GoFunctionOrMethodDeclaration)resolve).getSignature(); if (signature != null) { List exprList = argumentList.getExpressionList(); List paramsList = signature.getParameters().getParameterDeclarationList(); if (exprList.size() == 1) { List typeList = ContainerUtil.newSmartList(); for (GoParameterDeclaration parameterDecl : paramsList) { for (GoParamDefinition parameter : parameterDecl.getParamDefinitionList()) { typeList.add(getGoType(parameter, argumentList)); } if (parameterDecl.getParamDefinitionList().isEmpty()) { typeList.add(getInterfaceIfNull(parameterDecl.getType(), argumentList)); } } List result = ContainerUtil.newSmartList(createGoTypeListOrGoType(typeList, argumentList)); if (paramsList.size() > 1) { assert paramsList.get(0) != null; result.add(getInterfaceIfNull(paramsList.get(0).getType(), argumentList)); } return result; } else { int position = exprList.indexOf(expression); if (position >= 0) { int i = 0; for (GoParameterDeclaration parameterDecl : paramsList) { int paramDeclSize = Math.max(1, parameterDecl.getParamDefinitionList().size()); if (i + paramDeclSize > position) { return Collections.singletonList(getInterfaceIfNull(parameterDecl.getType(), argumentList)); } i += paramDeclSize; } } } } } } return Collections.singletonList(getInterfaceIfNull(null, argumentList)); } @NotNull private static List getExpectedTypesFromRecvStatement(@NotNull GoRecvStatement recvStatement) { List typeList = ContainerUtil.newSmartList(); for (GoExpression expr : recvStatement.getLeftExpressionsList()) { typeList.add(getGoType(expr, recvStatement)); } return Collections.singletonList(createGoTypeListOrGoType(typeList, recvStatement)); } @NotNull private static List getExpectedTypesFromVarSpec(@NotNull GoExpression expression, @NotNull GoVarSpec varSpec) { List result = ContainerUtil.newSmartList(); GoType type = getInterfaceIfNull(varSpec.getType(), varSpec); if (varSpec.getRightExpressionsList().size() == 1) { List typeList = ContainerUtil.newSmartList(); int defListSize = varSpec.getVarDefinitionList().size(); for (int i = 0; i < defListSize; i++) { typeList.add(type); } result.add(createGoTypeListOrGoType(typeList, expression)); if (defListSize > 1) { result.add(getInterfaceIfNull(type, varSpec)); } return result; } result.add(type); return result; } @NotNull private static List getExpectedTypesFromAssignmentStatement(@NotNull GoExpression expression, @NotNull GoAssignmentStatement assignment) { List leftExpressions = assignment.getLeftHandExprList().getExpressionList(); if (assignment.getExpressionList().size() == 1) { List typeList = ContainerUtil.newSmartList(); for (GoExpression expr : leftExpressions) { GoType type = expr.getGoType(null); typeList.add(type); } List result = ContainerUtil.newSmartList(createGoTypeListOrGoType(typeList, expression)); if (leftExpressions.size() > 1) { result.add(getGoType(leftExpressions.get(0), assignment)); } return result; } int position = assignment.getExpressionList().indexOf(expression); GoType leftExpression = leftExpressions.size() > position ? leftExpressions.get(position).getGoType(null) : null; return Collections.singletonList(getInterfaceIfNull(leftExpression, assignment)); } @NotNull private static GoType createGoTypeListOrGoType(@NotNull List types, @NotNull PsiElement context) { if (types.size() < 2) { return getInterfaceIfNull(ContainerUtil.getFirstItem(types), context); } return GoElementFactory.createTypeList(context.getProject(), StringUtil.join(types, type -> type == null ? GoConstants.INTERFACE_TYPE : type.getText(), ", ")); } @NotNull private static GoType getInterfaceIfNull(@Nullable GoType type, @NotNull PsiElement context) { return type == null ? GoElementFactory.createType(context.getProject(), GoConstants.INTERFACE_TYPE) : type; } @NotNull private static GoType getGoType(@Nullable GoTypeOwner element, @NotNull PsiElement context) { return getInterfaceIfNull(element != null ? element.getGoType(null) : null, context); } public static boolean isFunction(@Nullable GoType goType) { return goType != null && goType.getUnderlyingType() instanceof GoFunctionType; } } ================================================ FILE: src/com/goide/psi/impl/GoVarProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.*; import com.intellij.openapi.util.Comparing; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoVarProcessor extends GoScopeProcessorBase { private final boolean myImShortVarDeclaration; private final PsiElement myParentGuard; @Nullable private final GoCompositeElement myScope; public GoVarProcessor(@NotNull PsiElement origin, boolean completion) { this(origin, origin, completion, false); } public GoVarProcessor(@NotNull PsiElement requestedName, @NotNull PsiElement origin, boolean completion, boolean delegate) { super(requestedName, origin, completion); myImShortVarDeclaration = PsiTreeUtil.getParentOfType(origin, GoShortVarDeclaration.class) != null && !delegate; myParentGuard = origin.getParent() instanceof GoTypeSwitchGuard ? origin.getParent() : null; myScope = getScope(origin); } @Override protected boolean add(@NotNull GoNamedElement o) { PsiElement commonParent = PsiTreeUtil.findCommonParent(o, myOrigin); if (commonParent instanceof GoRangeClause || commonParent instanceof GoTypeSwitchGuard) return true; PsiElement p = o.getParent(); boolean inVarOrRange = PsiTreeUtil.getParentOfType(o, GoVarDeclaration.class) != null || p instanceof GoRangeClause; boolean differentBlocks = differentBlocks(o); boolean inShortVar = PsiTreeUtil.getParentOfType(o, GoShortVarDeclaration.class, GoRecvStatement.class) != null; if (inShortVar && differentBlocks && myImShortVarDeclaration) return true; if (differentBlocks && inShortVar && !inVarOrRange && getResult() != null && !myIsCompletion) return true; if (inShortVar && fromNotAncestorBlock(o)) return true; if (myParentGuard != null && o instanceof GoVarDefinition && p.isEquivalentTo(myParentGuard)) return true; return super.add(o); } private boolean fromNotAncestorBlock(@NotNull GoNamedElement o) { return (myScope instanceof GoExprCaseClause || myScope instanceof GoCommClause) && !PsiTreeUtil.isAncestor(getScope(o), myOrigin, false); } private boolean differentBlocks(@Nullable GoNamedElement o) { return !Comparing.equal(myScope, getScope(o)); } @Nullable public static GoCompositeElement getScope(@Nullable PsiElement o) { GoForStatement forStatement = PsiTreeUtil.getParentOfType(o, GoForStatement.class); if (forStatement != null) return forStatement.getBlock(); GoIfStatement ifStatement = PsiTreeUtil.getParentOfType(o, GoIfStatement.class); if (ifStatement != null) return ifStatement.getBlock(); GoElseStatement elseStatement = PsiTreeUtil.getParentOfType(o, GoElseStatement.class); if (elseStatement != null) return elseStatement.getBlock(); GoExprCaseClause exprCaseClause = PsiTreeUtil.getParentOfType(o, GoExprCaseClause.class); if (exprCaseClause != null) return exprCaseClause; GoCommClause commClause = PsiTreeUtil.getParentOfType(o, GoCommClause.class); if (commClause != null) return commClause; return PsiTreeUtil.getParentOfType(o, GoBlock.class); } @Override protected boolean crossOff(@NotNull PsiElement e) { return !(e instanceof GoVarDefinition) && !(e instanceof GoParamDefinition) && !(e instanceof GoReceiver) && !(e instanceof GoFieldDefinition) && !(e instanceof GoAnonymousFieldDefinition) && !(e instanceof GoConstDefinition); } } ================================================ FILE: src/com/goide/psi/impl/GoVarReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoBlock; import com.goide.psi.GoFieldDefinition; import com.goide.psi.GoStatement; import com.goide.psi.GoVarDefinition; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoVarReference extends GoCachedReference { private final GoBlock myPotentialStopBlock; public GoVarReference(@NotNull GoVarDefinition element) { super(element); myPotentialStopBlock = PsiTreeUtil.getParentOfType(element, GoBlock.class); } @Nullable @Override public PsiElement resolveInner() { GoVarProcessor p = new GoVarProcessor(myElement, false) { @Override protected boolean crossOff(@NotNull PsiElement e) { return e instanceof GoFieldDefinition || super.crossOff(e); } }; processResolveVariants(p); return p.getResult(); } @Override public boolean processResolveVariants(@NotNull GoScopeProcessor processor) { GoVarProcessor p = processor instanceof GoVarProcessor ? (GoVarProcessor)processor : new GoVarProcessor(myElement, processor.isCompletion()) { @Override public boolean execute(@NotNull PsiElement e, @NotNull ResolveState state) { return super.execute(e, state) && processor.execute(e, state); } }; if (myPotentialStopBlock != null) { myPotentialStopBlock.processDeclarations(p, ResolveState.initial(), PsiTreeUtil.getParentOfType(myElement, GoStatement.class), myElement); return true; } return false; } } ================================================ FILE: src/com/goide/psi/impl/ResolveUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.psi.GoCompositeElement; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class ResolveUtil { private ResolveUtil() {} public static boolean treeWalkUp(@Nullable PsiElement place, @NotNull PsiScopeProcessor processor) { PsiElement lastParent = null; PsiElement run = place; while (run != null) { if (place != run && !run.processDeclarations(processor, ResolveState.initial(), lastParent, place)) return false; lastParent = run; run = run.getParent(); } return true; } public static boolean processChildren(@NotNull PsiElement element, @NotNull PsiScopeProcessor processor, @NotNull ResolveState substitutor, @Nullable PsiElement lastParent, @NotNull PsiElement place) { PsiElement run = lastParent == null ? element.getLastChild() : lastParent.getPrevSibling(); while (run != null) { if (run instanceof GoCompositeElement && !run.processDeclarations(processor, substitutor, null, place)) return false; run = run.getPrevSibling(); } return true; } public static boolean processChildrenFromTop(@NotNull PsiElement element, @NotNull PsiScopeProcessor processor, @NotNull ResolveState substitutor, @Nullable PsiElement lastParent, @NotNull PsiElement place) { PsiElement run = element.getFirstChild(); while (run != null) { if (run instanceof GoCompositeElement) { if (run.isEquivalentTo(lastParent)) return true; if (!run.processDeclarations(processor, substitutor, null, place)) return false; } run = run.getNextSibling(); } return true; } } ================================================ FILE: src/com/goide/psi/impl/imports/GoImportReference.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl.imports; import com.goide.codeInsight.imports.GoGetPackageFix; import com.goide.completion.GoCompletionUtil; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.sdk.GoPackageUtil; import com.intellij.codeInsight.completion.CompletionUtil; import com.intellij.codeInsight.daemon.quickFix.CreateFileFix; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.Set; public class GoImportReference extends FileReference { public GoImportReference(@NotNull FileReferenceSet fileReferenceSet, TextRange range, int index, String text) { super(fileReferenceSet, range, index, text); } @Override protected Object createLookupItem(PsiElement candidate) { if (candidate instanceof PsiDirectory) { return GoCompletionUtil.createDirectoryLookupElement((PsiDirectory)candidate); } return super.createLookupItem(candidate); } @NotNull @Override protected ResolveResult[] innerResolve(boolean caseSensitive, @NotNull PsiFile file) { if (isFirst()) { if (".".equals(getCanonicalText())) { PsiDirectory directory = getDirectory(); return directory != null ? new PsiElementResolveResult[]{new PsiElementResolveResult(directory)} : ResolveResult.EMPTY_ARRAY; } else if ("..".equals(getCanonicalText())) { PsiDirectory directory = getDirectory(); PsiDirectory grandParent = directory != null ? directory.getParentDirectory() : null; return grandParent != null ? new PsiElementResolveResult[]{new PsiElementResolveResult(grandParent)} : ResolveResult.EMPTY_ARRAY; } } String referenceText = getText(); Set result = ContainerUtil.newLinkedHashSet(); Set innerResult = ContainerUtil.newLinkedHashSet(); for (PsiFileSystemItem context : getContexts()) { innerResolveInContext(referenceText, context, innerResult, caseSensitive); for (ResolveResult resolveResult : innerResult) { PsiElement element = resolveResult.getElement(); if (element instanceof PsiDirectory) { if (isLast()) { return new ResolveResult[]{resolveResult}; } result.add(resolveResult); } } innerResult.clear(); } return result.isEmpty() ? ResolveResult.EMPTY_ARRAY : result.toArray(new ResolveResult[result.size()]); } @Override public boolean isReferenceTo(PsiElement element) { if (super.isReferenceTo(element)) { return true; } if (element instanceof PsiDirectoryContainer) { for (PsiDirectory directory : ((PsiDirectoryContainer)element).getDirectories()) { if (super.isReferenceTo(directory)) { return true; } } } return false; } @Override public PsiElement bindToElement(@NotNull PsiElement element, boolean absolute) throws IncorrectOperationException { if (!absolute) { FileReference firstReference = ArrayUtil.getFirstElement(getFileReferenceSet().getAllReferences()); if (firstReference != null) { Collection contexts = getFileReferenceSet().getDefaultContexts(); for (ResolveResult resolveResult : firstReference.multiResolve(false)) { PsiElement resolveResultElement = resolveResult.getElement(); if (resolveResultElement instanceof PsiFileSystemItem) { PsiFileSystemItem parentDirectory = ((PsiFileSystemItem)resolveResultElement).getParent(); if (parentDirectory != null && contexts.contains(parentDirectory)) { return getElement(); } } } } } return super.bindToElement(element, absolute); } @Override public LocalQuickFix[] getQuickFixes() { if (GoPackageUtil.isBuiltinPackage(resolve())) { return new LocalQuickFix[]{new GoDeleteImportQuickFix()}; } List result = ContainerUtil.newArrayList(); FileReferenceSet fileReferenceSet = getFileReferenceSet(); if (fileReferenceSet instanceof GoImportReferenceSet && !((GoImportReferenceSet)fileReferenceSet).isRelativeImport() && !fileReferenceSet.isAbsolutePathReference()) { result.add(new GoGetPackageFix(fileReferenceSet.getPathString())); } String fileNameToCreate = getFileNameToCreate(); for (PsiFileSystemItem context : getContexts()) { if (context instanceof PsiDirectory) { try { ((PsiDirectory)context).checkCreateSubdirectory(fileNameToCreate); String targetPath = context.getVirtualFile().getPath(); result.add(new CreateFileFix(true, fileNameToCreate, (PsiDirectory)context) { @NotNull @Override public String getText() { return "Create Directory " + fileNameToCreate + " at " + targetPath; } }); } catch (IncorrectOperationException ignore) { } } } return result.toArray(new LocalQuickFix[result.size()]); } private boolean isFirst() { return getIndex() <= 0; } @Nullable private PsiDirectory getDirectory() { PsiElement originalElement = CompletionUtil.getOriginalElement(getElement()); PsiFile file = originalElement != null ? originalElement.getContainingFile() : getElement().getContainingFile(); return file.getParent(); } } ================================================ FILE: src/com/goide/psi/impl/imports/GoImportReferenceSet.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl.imports; import com.goide.project.GoVendoringUtil; import com.goide.psi.GoImportString; import com.goide.sdk.GoSdkUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; public class GoImportReferenceSet extends FileReferenceSet { public GoImportReferenceSet(@NotNull GoImportString importString) { super(importString.getPath(), importString, importString.getPathTextRange().getStartOffset(), null, true); } @NotNull @Override public Collection computeDefaultContexts() { PsiFile file = getContainingFile(); if (file == null || !file.isValid() || isAbsolutePathReference()) { return Collections.emptyList(); } PsiManager psiManager = file.getManager(); Module module = ModuleUtilCore.findModuleForPsiElement(file); Project project = file.getProject(); LinkedHashSet sourceRoots = GoVendoringUtil.isVendoringEnabled(module) ? GoSdkUtil.getVendoringAwareSourcesPathsToLookup(project, module, file.getVirtualFile()) : GoSdkUtil.getSourcesPathsToLookup(project, module); return ContainerUtil.mapNotNull(sourceRoots, psiManager::findDirectory); } @Override protected Condition getReferenceCompletionFilter() { if (!isRelativeImport()) { return Conditions.alwaysFalse(); } return super.getReferenceCompletionFilter(); } @Nullable @Override public PsiFileSystemItem resolve() { return isAbsolutePathReference() ? null : super.resolve(); } @Override public boolean absoluteUrlNeedsStartSlash() { return false; } @Override public boolean isEndingSlashNotAllowed() { return !isRelativeImport(); } @NotNull @Override public FileReference createFileReference(TextRange range, int index, String text) { return new GoImportReference(this, range, index, text); } public boolean isRelativeImport() { return isRelativeImport(getPathString()); } public static boolean isRelativeImport(@NotNull String pathString) { return pathString.startsWith("./") || pathString.startsWith("../"); } @Override public boolean couldBeConvertedTo(boolean relative) { return false; } } ================================================ FILE: src/com/goide/psi/impl/imports/GoReferenceImporter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl.imports; import com.goide.GoLanguage; import com.goide.codeInsight.imports.GoImportPackageQuickFix; import com.goide.psi.GoCompositeElement; import com.intellij.codeInsight.daemon.ReferenceImporter; import com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil; import com.intellij.codeInsight.daemon.impl.DaemonListeners; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoReferenceImporter implements ReferenceImporter { @Override public boolean autoImportReferenceAtCursor(@NotNull Editor editor, @NotNull PsiFile file) { if (!file.getViewProvider().getLanguages().contains(GoLanguage.INSTANCE) || !DaemonListeners.canChangeFileSilently(file)) { return false; } int caretOffset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); int lineNumber = document.getLineNumber(caretOffset); int startOffset = document.getLineStartOffset(lineNumber); int endOffset = document.getLineEndOffset(lineNumber); List elements = CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffset); for (PsiElement element : elements) { if (element instanceof GoCompositeElement) { for (PsiReference reference : element.getReferences()) { GoImportPackageQuickFix fix = new GoImportPackageQuickFix(reference); if (fix.doAutoImportOrShowHint(editor, false)) { return true; } } } } return false; } @Override public boolean autoImportReferenceAt(@NotNull Editor editor, @NotNull PsiFile file, int offset) { if (!file.getViewProvider().getLanguages().contains(GoLanguage.INSTANCE)) { return false; } PsiReference reference = file.findReferenceAt(offset); if (reference != null) { return new GoImportPackageQuickFix(reference).doAutoImportOrShowHint(editor, false); } return false; } } ================================================ FILE: src/com/goide/psi/impl/manipulator/GoImportStringManipulator.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl.manipulator; import com.goide.psi.GoImportString; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.util.TextRange; import com.intellij.psi.AbstractElementManipulator; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; public class GoImportStringManipulator extends AbstractElementManipulator { @NotNull @Override public GoImportString handleContentChange(@NotNull GoImportString string, @NotNull TextRange range, String s) throws IncorrectOperationException { String newPackage = range.replace(string.getText(), s); return (GoImportString)string.replace(GoElementFactory.createImportString(string.getProject(), newPackage)); } @NotNull @Override public TextRange getRangeInElement(@NotNull GoImportString element) { return element.getPathTextRange(); } } ================================================ FILE: src/com/goide/psi/impl/manipulator/GoStringManipulator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl.manipulator; import com.goide.psi.impl.GoStringLiteralImpl; import com.intellij.openapi.util.TextRange; import com.intellij.psi.AbstractElementManipulator; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; public class GoStringManipulator extends AbstractElementManipulator { @Override public GoStringLiteralImpl handleContentChange(@NotNull GoStringLiteralImpl literal, @NotNull TextRange range, String newContent) throws IncorrectOperationException { String newText = range.replace(literal.getText(), newContent); return literal.updateText(newText); } @NotNull @Override public TextRange getRangeInElement(@NotNull GoStringLiteralImpl element) { if (element.getTextLength() == 0) { return TextRange.EMPTY_RANGE; } String s = element.getText(); char quote = s.charAt(0); int startOffset = isQuote(quote) ? 1 : 0; int endOffset = s.length(); if (s.length() > 1) { char lastChar = s.charAt(s.length() - 1); if (isQuote(quote) && lastChar == quote) { endOffset = s.length() - 1; } if (!isQuote(quote) && isQuote(lastChar)) { endOffset = s.length() - 1; } } return TextRange.create(startOffset, endOffset); } private static boolean isQuote(char ch) { return ch == '"' || ch == '\'' || ch == '`'; } } ================================================ FILE: src/com/goide/quickfix/GoConvertStringToByteQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoConditionalExpr; import com.goide.psi.GoStringLiteral; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import static com.goide.psi.impl.GoElementFactory.createExpression; import static com.goide.psi.impl.GoPsiImplUtil.isSingleCharLiteral; import static java.lang.String.format; public class GoConvertStringToByteQuickFix extends LocalQuickFixBase { public static final String NAME = "Convert string to byte"; public GoConvertStringToByteQuickFix() { super(NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (!(element instanceof GoConditionalExpr) || !element.isValid()) { return; } GoConditionalExpr expr = (GoConditionalExpr)element; GoStringLiteral literal = ContainerUtil.findInstance(Arrays.asList(expr.getLeft(), expr.getRight()), GoStringLiteral.class); if (literal == null || !isSingleCharLiteral(literal)) { return; } literal.replace(createExpression(project, extractSingleCharFromText(literal))); } @NotNull private static String extractSingleCharFromText(@NotNull GoStringLiteral element) { return format("'%s'", ElementManipulators.getValueText(element)); } } ================================================ FILE: src/com/goide/quickfix/GoCreateWrapperTypeQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoType; import com.goide.psi.GoTypeDeclaration; import com.goide.psi.GoTypeSpec; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInsight.CodeInsightUtilCore; import com.intellij.codeInsight.template.Template; import com.intellij.codeInsight.template.TemplateBuilderImpl; import com.intellij.codeInsight.template.TemplateManager; import com.intellij.codeInsight.template.impl.ConstantNode; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.diagnostic.AttachmentFactory; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoCreateWrapperTypeQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement { private static final String INPUT_NAME = "INPUTVAR"; private static final String OTHER_NAME = "OTHERVAR"; public static final String QUICKFIX_NAME = "Create type"; public GoCreateWrapperTypeQuickFix(@NotNull GoType type) { super(type); } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (editor == null) { LOG.error("Cannot run quick fix without editor: " + getClass().getSimpleName(), AttachmentFactory.createAttachment(file.getVirtualFile())); return; } if (!(startElement instanceof GoType)) return; GoType type = (GoType)startElement; PsiElement anchor = PsiTreeUtil.findPrevParent(file, type); String name = "TypeName"; GoTypeDeclaration decl = (GoTypeDeclaration)file.addBefore(GoElementFactory.createTypeDeclaration(project, name, type), anchor); if (decl == null) return; decl = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl); if (decl == null) return; GoTypeSpec spec = ContainerUtil.getFirstItem(decl.getTypeSpecList()); if (spec == null) return; TemplateBuilderImpl builder = new TemplateBuilderImpl(file); builder.replaceElement(type, OTHER_NAME, INPUT_NAME, false); builder.replaceElement(spec.getIdentifier(), INPUT_NAME, new ConstantNode(name), true); editor.getCaretModel().moveToOffset(file.getTextRange().getStartOffset()); Template template = builder.buildInlineTemplate(); editor.getCaretModel().moveToOffset(file.getTextRange().getStartOffset()); TemplateManager.getInstance(project).startTemplate(editor, template); } @NotNull @Override public String getText() { return QUICKFIX_NAME; } @Nls @NotNull @Override public String getFamilyName() { return QUICKFIX_NAME; } } ================================================ FILE: src/com/goide/quickfix/GoDeleteAmpersandAndTypeInCompositeLitQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoRedundantTypeDeclInCompositeLit; import com.goide.psi.*; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public class GoDeleteAmpersandAndTypeInCompositeLitQuickFix extends LocalQuickFixBase { public GoDeleteAmpersandAndTypeInCompositeLitQuickFix() { super(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element != null && element.isValid()) { if (element instanceof GoUnaryExpr) { GoUnaryExpr unaryExpr = (GoUnaryExpr)element; GoExpression expr = unaryExpr.getExpression(); if (unaryExpr.getBitAnd() != null && expr instanceof GoCompositeLit) { GoLiteralValue literalValue = ((GoCompositeLit)expr).getLiteralValue(); if (literalValue != null) { unaryExpr.replace(literalValue); } } } else if (element instanceof GoTypeReferenceExpression) { PsiElement parent = element.getParent(); if (parent instanceof GoCompositeLit) { GoLiteralValue literalValue = ((GoCompositeLit)parent).getLiteralValue(); if (literalValue != null) { parent.replace(literalValue); } } } } } } ================================================ FILE: src/com/goide/quickfix/GoDeleteConstDefinitionQuickFix.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoConstDefinition; import com.goide.psi.GoConstSpec; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoDeleteConstDefinitionQuickFix extends LocalQuickFixBase { public GoDeleteConstDefinitionQuickFix(@Nullable String constName) { super("Delete const " + (constName != null ? "'" + constName + "'" : ""), "Delete constant"); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element.isValid() && element instanceof GoConstDefinition) { PsiElement parent = element.getParent(); if (parent instanceof GoConstSpec) { ((GoConstSpec)parent).deleteDefinition((GoConstDefinition)element); } } } } ================================================ FILE: src/com/goide/quickfix/GoDeleteImportQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoDeleteImportQuickFix extends LocalQuickFixBase { public static final String QUICK_FIX_NAME = "Delete import"; public GoDeleteImportQuickFix() { super(QUICK_FIX_NAME); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = PsiTreeUtil.getNonStrictParentOfType(descriptor.getPsiElement(), GoImportSpec.class); PsiFile file = element != null ? element.getContainingFile() : null; if (!(file instanceof GoFile)) return; WriteCommandAction.runWriteCommandAction(project, () -> ((GoFile)file).deleteImport((GoImportSpec)element)); } } ================================================ FILE: src/com/goide/quickfix/GoDeleteQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; public class GoDeleteQuickFix extends LocalQuickFixBase { private final Class myClazz; private final IElementType myElementType; public GoDeleteQuickFix(@NotNull String name, @NotNull Class clazz) { super(name); myClazz = clazz; myElementType = null; } public GoDeleteQuickFix(@NotNull String name, @NotNull IElementType elementType) { super(name); myClazz = PsiElement.class; myElementType = elementType; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { WriteCommandAction.runWriteCommandAction(project, () -> { PsiElement element = ObjectUtils.tryCast(descriptor.getStartElement(), myClazz); if (element != null && (myElementType == null || element.getNode().getElementType() == myElementType)) { element.delete(); } }); } } ================================================ FILE: src/com/goide/quickfix/GoDeleteRangeQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoDeleteRangeQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement { private static final Logger LOG = Logger.getInstance(GoDeleteRangeQuickFix.class); private final String myName; public GoDeleteRangeQuickFix(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull String name) { super(startElement, endElement); if (!startElement.getParent().equals(endElement.getParent())) { LOG.error("Cannot delete range of elements with different parents"); } myName = name; } @NotNull @Override public String getText() { return myName; } @Nls @NotNull @Override public String getFamilyName() { return "Delete elements"; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement start, @NotNull PsiElement end) { if (start.isValid() && end.isValid()) { PsiElement parent = start.getParent(); if (parent != null && parent.equals(end.getParent())) { parent.getNode().removeRange(start.getNode(), end.getNode().getTreeNext()); } } } } ================================================ FILE: src/com/goide/quickfix/GoDeleteVarDefinitionQuickFix.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoVarDefinition; import com.goide.psi.GoVarSpec; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoDeleteVarDefinitionQuickFix extends LocalQuickFixBase { public GoDeleteVarDefinitionQuickFix(@Nullable String variableName) { super("Delete variable " + (variableName != null ? "'" + variableName + "'" : ""), "Delete variable"); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element.isValid() && element instanceof GoVarDefinition) { PsiElement parent = element.getParent(); if (parent instanceof GoVarSpec) { ((GoVarSpec)parent).deleteDefinition((GoVarDefinition)element); } } } } ================================================ FILE: src/com/goide/quickfix/GoDisableVendoringInModuleQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.project.GoModuleSettings; import com.goide.sdk.GoSdkService; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.goide.project.GoVendoringUtil.isVendoringEnabled; import static com.goide.project.GoVendoringUtil.vendoringCanBeDisabled; public class GoDisableVendoringInModuleQuickFix extends LocalQuickFixBase { @NotNull private final Module myModule; private GoDisableVendoringInModuleQuickFix(@NotNull Module module) { super("Disable vendoring experiment support in module '" + module.getName() + "'", "Disable vendoring experiment support in module"); myModule = module; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { if (!myModule.isDisposed()) { GoModuleSettings.getInstance(myModule).setVendoringEnabled(ThreeState.NO); } } public static GoDisableVendoringInModuleQuickFix create(@Nullable Module module) { if (!isVendoringEnabled(module)) { return null; } String version = GoSdkService.getInstance(module.getProject()).getSdkVersion(module); return vendoringCanBeDisabled(version) ? new GoDisableVendoringInModuleQuickFix(module) : null; } } ================================================ FILE: src/com/goide/quickfix/GoEmptySignatureQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoSignature; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoEmptySignatureQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement { public static final String QUICK_FIX_NAME = "Fix signature"; public GoEmptySignatureQuickFix(@NotNull GoFunctionDeclaration functionDeclaration) { super(functionDeclaration); } @NotNull @Override public String getText() { return QUICK_FIX_NAME; } @Nls @NotNull @Override public String getFamilyName() { return QUICK_FIX_NAME; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { GoFunctionDeclaration function = ObjectUtils.tryCast(startElement, GoFunctionDeclaration.class); GoSignature signature = function != null ? function.getSignature() : null; if (signature == null) return; signature.replace(GoElementFactory.createFunctionSignatureFromText(project, "")); } } ================================================ FILE: src/com/goide/quickfix/GoMultiplePackagesQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.GoConstants; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.Disposable; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.Collection; public class GoMultiplePackagesQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement { private static String myTestingPackageName; private final Collection myPackages; private final String myPackageName; private final boolean myIsOneTheFly; public GoMultiplePackagesQuickFix(@NotNull PsiElement element, @NotNull String packageName, @NotNull Collection packages, boolean isOnTheFly) { super(element); myPackages = packages; myPackageName = packageName; myIsOneTheFly = isOnTheFly; } private static void renamePackagesInDirectory(@NotNull Project project, @NotNull PsiDirectory dir, @NotNull String newName) { WriteCommandAction.runWriteCommandAction(project, () -> { Module module = ModuleUtilCore.findModuleForPsiElement(dir); for (PsiFile file : dir.getFiles()) { if (file instanceof GoFile && GoPsiImplUtil.allowed(file, null, module)) { GoPackageClause packageClause = ((GoFile)file).getPackage(); String oldName = ((GoFile)file).getPackageName(); if (packageClause != null && oldName != null) { String fullName = GoTestFinder.isTestFile(file) && StringUtil.endsWith(oldName, GoConstants.TEST_SUFFIX) ? newName + GoConstants.TEST_SUFFIX : newName; packageClause.replace(GoElementFactory.createPackageClause(project, fullName)); } } } }); } @TestOnly public static void setTestingPackageName(@NotNull String packageName, @NotNull Disposable disposable) { myTestingPackageName = packageName; Disposer.register(disposable, () -> { //noinspection AssignmentToStaticFieldFromInstanceMethod myTestingPackageName = null; }); } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (editor == null || myTestingPackageName != null) { renamePackagesInDirectory(project, file.getContainingDirectory(), myTestingPackageName != null ? myTestingPackageName : myPackageName); return; } JBList list = new JBList(myPackages); list.installCellRenderer(o -> { JBLabel label = new JBLabel(o.toString()); label.setBorder(IdeBorderFactory.createEmptyBorder(2, 4, 2, 4)); return label; }); JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle("Choose package name").setItemChoosenCallback(() -> { String name = (String)list.getSelectedValue(); if (name != null) { renamePackagesInDirectory(project, file.getContainingDirectory(), name); } }).createPopup().showInBestPositionFor(editor); } @NotNull @Override public String getText() { return "Rename packages" + (myIsOneTheFly ? "" : " to " + myPackageName); } @NotNull @Override public String getFamilyName() { return "Rename packages"; } } ================================================ FILE: src/com/goide/quickfix/GoRenameQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoNamedElement; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInspection.LocalQuickFixOnPsiElement; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.AsyncResult; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.RefactoringActionHandlerFactory; import com.intellij.refactoring.rename.RenameHandler; import com.intellij.refactoring.rename.RenameHandlerRegistry; import com.intellij.usageView.UsageViewTypeLocation; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; public class GoRenameQuickFix extends LocalQuickFixOnPsiElement { private final String myText; public GoRenameQuickFix(@NotNull GoNamedElement element) { super(element); myText = "Rename " + ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE); } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!FileModificationService.getInstance().preparePsiElementsForWrite(startElement)) return; Runnable runnable = () -> { AsyncResult dataContextContainer = DataManager.getInstance().getDataContextFromFocus(); dataContextContainer.doWhenDone(new Consumer() { @Override public void consume(DataContext dataContext) { RenameHandler renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext); if (renameHandler != null) { renameHandler.invoke(project, new PsiElement[]{startElement}, dataContext); } else { RefactoringActionHandler renameRefactoringHandler = RefactoringActionHandlerFactory.getInstance().createRenameHandler(); renameRefactoringHandler.invoke(project, new PsiElement[]{startElement}, dataContext); } } }); }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable, project.getDisposed()); } } @Override @NotNull public String getFamilyName() { return getName(); } @NotNull @Override public String getText() { return myText; } } ================================================ FILE: src/com/goide/quickfix/GoRenameToBlankQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoNoNewVariablesInspection; import com.goide.psi.GoNamedElement; import com.goide.psi.GoVarDefinition; import com.goide.psi.GoVarSpec; import com.intellij.codeInspection.LocalQuickFixOnPsiElement; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoRenameToBlankQuickFix extends LocalQuickFixOnPsiElement { public static final String NAME = "Rename to _"; public GoRenameToBlankQuickFix(GoNamedElement o) { super(o); } @NotNull @Override public String getText() { return NAME; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (startElement.isValid() && startElement instanceof GoNamedElement) { ((GoNamedElement)startElement).setName("_"); if (startElement instanceof GoVarDefinition) { PsiElement parent = startElement.getParent(); if (parent instanceof GoVarSpec) { if (GoNoNewVariablesInspection.hasNonNewVariables(((GoVarSpec)parent).getVarDefinitionList())) { GoNoNewVariablesInspection.replaceWithAssignment(project, parent); } } } } } @NotNull @Override public String getFamilyName() { return getName(); } } ================================================ FILE: src/com/goide/quickfix/GoReplaceWithReturnStatementQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoStatement; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoReplaceWithReturnStatementQuickFix extends LocalQuickFixAndIntentionActionOnPsiElement { public static final String QUICK_FIX_NAME = "Replace with 'return'"; public GoReplaceWithReturnStatementQuickFix(@Nullable PsiElement element) { super(element); } @NotNull @Override public String getText() { return QUICK_FIX_NAME; } @Nls @NotNull @Override public String getFamilyName() { return QUICK_FIX_NAME; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { WriteCommandAction.runWriteCommandAction(project, () -> { if (startElement instanceof GoStatement) { startElement.replace(GoElementFactory.createReturnStatement(project)); } }); } } ================================================ FILE: src/com/goide/quickfix/GoReplaceWithSelectStatementQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.psi.GoForStatement; import com.goide.psi.impl.GoElementFactory; import com.intellij.codeInspection.LocalQuickFixBase; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; public class GoReplaceWithSelectStatementQuickFix extends LocalQuickFixBase { public static final String QUICK_FIX_NAME = "Replace with 'select'"; public GoReplaceWithSelectStatementQuickFix() { super(QUICK_FIX_NAME); } @Nls @NotNull @Override public String getFamilyName() { return QUICK_FIX_NAME; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); if (element instanceof GoForStatement) { element.replace(GoElementFactory.createSelectStatement(project)); } } } ================================================ FILE: src/com/goide/quickfix/GoSimplifyBoolExprQuickFix.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoBoolExpressionsInspection; import com.goide.psi.GoAndExpr; import com.goide.psi.GoBinaryExpr; import com.goide.psi.GoExpression; import com.goide.psi.GoReferenceExpression; import com.goide.psi.impl.GoElementFactory; import com.goide.psi.impl.GoExpressionUtil; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInspection.LocalQuickFixOnPsiElement; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoSimplifyBoolExprQuickFix extends LocalQuickFixOnPsiElement { public static final String QUICK_FIX_NAME = "Simplify expression"; public GoSimplifyBoolExprQuickFix(@NotNull PsiElement element) { super(element); } @Override @NotNull public String getFamilyName() { return getName(); } @NotNull @Override public String getText() { return "Simplify expression"; } @Override public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) { if (!(startElement instanceof GoBinaryExpr)) return; GoBinaryExpr o = (GoBinaryExpr)startElement; boolean and = o instanceof GoAndExpr; List elements = GoBoolExpressionsInspection.collect(o, and); List toRemove = ContainerUtil.newSmartList(); for (int i = 0; i < elements.size(); i++) { GoExpression l = elements.get(i); if (l instanceof GoReferenceExpression && (l.textMatches("true") || l.textMatches("false")) && GoPsiImplUtil.builtin(((GoReferenceExpression)l).resolve())) { boolean trueExpr = l.textMatches("true"); if (and ^ !trueExpr) { toRemove.add(l); } else { replaceExpressionByBoolConst(o, project, !and); return; } } for (int j = i + 1; j < elements.size(); j++) { GoExpression r = elements.get(j); if (GoBoolExpressionsInspection.isEqualsWithNot(l, r) || GoBoolExpressionsInspection.isEqualsWithNot(r, l)) { replaceExpressionByBoolConst(o, project, !and); } if (GoExpressionUtil.identical(l, r)) toRemove.add(l); // todo expr evaluating! x != c1 || x != c2 (c1, c2 const, c1 != c2) } } if (!toRemove.isEmpty()) { removeRedundantExpressions(o, project, elements, toRemove, and); } } private static void removeRedundantExpressions(@NotNull GoBinaryExpr binaryExpr, @NotNull Project project, @NotNull List expressions, @NotNull List toRemove, boolean and) { for (GoExpression e : toRemove) { expressions.remove(e); } String separator = and ? " && " : " || "; String text = StringUtil.join(expressions, PsiElement::getText, separator); GoExpression expression = GoElementFactory.createExpression(project, text); binaryExpr.replace(expression); } private static void replaceExpressionByBoolConst(@NotNull GoBinaryExpr binaryExpr, @NotNull Project project, boolean value) { GoExpression expression = GoElementFactory.createExpression(project, value ? "true" : "false"); binaryExpr.replace(expression); } } ================================================ FILE: src/com/goide/refactor/GoAnonymousFieldProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.psi.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.refactoring.rename.RenamePsiElementProcessor; import com.intellij.util.ObjectUtils; import com.intellij.util.Query; import org.jetbrains.annotations.NotNull; import java.util.Map; public class GoAnonymousFieldProcessor extends RenamePsiElementProcessor { @Override public boolean canProcessElement(@NotNull PsiElement element) { return element instanceof GoTypeSpec || element instanceof GoAnonymousFieldDefinition; } @Override public void prepareRenaming(PsiElement element, String newName, @NotNull Map allRenames, @NotNull SearchScope scope) { if (element instanceof GoTypeSpec) { Query search = ReferencesSearch.search(element, scope); for (PsiReference ref : search) { PsiElement refElement = ref.getElement(); PsiElement type = refElement == null ? null : refElement.getParent(); if (!(type instanceof GoType)) continue; PsiElement typeParent = type.getParent(); GoPointerType pointer = ObjectUtils.tryCast(typeParent, GoPointerType.class); PsiElement anon = pointer != null ? pointer.getParent() : typeParent; if (anon instanceof GoAnonymousFieldDefinition) { allRenames.put(anon, newName); } } } else if (element instanceof GoAnonymousFieldDefinition) { GoTypeReferenceExpression reference = ((GoAnonymousFieldDefinition)element).getTypeReferenceExpression(); PsiElement resolve = reference != null ? reference.resolve() : null; if (resolve instanceof GoTypeSpec) { allRenames.put(resolve, newName); } } } } ================================================ FILE: src/com/goide/refactor/GoDescriptionProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.psi.GoNamedElement; import com.intellij.codeInsight.highlighting.HighlightUsagesDescriptionLocation; import com.intellij.psi.ElementDescriptionLocation; import com.intellij.psi.ElementDescriptionProvider; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageViewLongNameLocation; import com.intellij.usageView.UsageViewShortNameLocation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoDescriptionProvider implements ElementDescriptionProvider { @Nullable @Override public String getElementDescription(@NotNull PsiElement o, @NotNull ElementDescriptionLocation location) { if (location == UsageViewShortNameLocation.INSTANCE || location == UsageViewLongNameLocation.INSTANCE || location == HighlightUsagesDescriptionLocation.INSTANCE) { return o instanceof GoNamedElement ? ((GoNamedElement)o).getName() : null; } return null; } } ================================================ FILE: src/com/goide/refactor/GoIntroduceOperation.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.psi.GoExpression; import com.goide.psi.GoVarDefinition; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import java.util.LinkedHashSet; import java.util.List; public class GoIntroduceOperation { final private Project myProject; final private Editor myEditor; final private PsiFile myFile; private GoExpression myExpression; private List myOccurrences; private LinkedHashSet mySuggestedNames; private String myName; private GoVarDefinition myVar; private boolean myReplaceAll; public GoIntroduceOperation(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { myProject = project; myEditor = editor; myFile = file; } @TestOnly public GoIntroduceOperation(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file, boolean replaceAll) { myProject = project; myEditor = editor; myFile = file; myReplaceAll = replaceAll; } @NotNull public Project getProject() { return myProject; } @NotNull public Editor getEditor() { return myEditor; } @NotNull public PsiFile getFile() { return myFile; } @NotNull public GoExpression getExpression() { return myExpression; } public void setExpression(@NotNull GoExpression expression) { myExpression = expression; } @NotNull public List getOccurrences() { return myOccurrences; } public void setOccurrences(@NotNull List occurrences) { myOccurrences = occurrences; } @NotNull public LinkedHashSet getSuggestedNames() { return mySuggestedNames; } public void setSuggestedNames(@NotNull LinkedHashSet suggestedNames) { mySuggestedNames = suggestedNames; } @NotNull public String getName() { return myName; } public void setName(@NotNull String name) { myName = name; } @NotNull public GoVarDefinition getVar() { return myVar; } public void setVar(@NotNull GoVarDefinition var) { myVar = var; } public boolean isReplaceAll() { return myReplaceAll; } public void setReplaceAll(boolean replaceAll) { myReplaceAll = replaceAll; } } ================================================ FILE: src/com/goide/refactor/GoIntroduceVariableBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.inspections.GoInspectionUtil; import com.goide.psi.*; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.Pass; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SyntaxTraverser; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.IntroduceTargetChooser; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.introduce.inplace.InplaceVariableIntroducer; import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; public class GoIntroduceVariableBase { protected static void performAction(GoIntroduceOperation operation) { SelectionModel selectionModel = operation.getEditor().getSelectionModel(); boolean hasSelection = selectionModel.hasSelection(); GoExpression expression = hasSelection ? findExpressionInSelection(operation.getFile(), selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) : findExpressionAtOffset(operation); if (expression instanceof GoParenthesesExpr) expression = ((GoParenthesesExpr)expression).getExpression(); if (expression == null) { String message = RefactoringBundle.message(hasSelection ? "selected.block.should.represent.an.expression" : "refactoring.introduce.selection.error"); showCannotPerform(operation, message); return; } List extractableExpressions = collectExtractableExpressions(expression); if (extractableExpressions.isEmpty()) { showCannotPerform(operation, RefactoringBundle.message("refactoring.introduce.context.error")); return; } List expressions = ContainerUtil.filter(extractableExpressions, expression12 -> GoInspectionUtil.getExpressionResultCount(expression12) == 1); if (expressions.isEmpty()) { GoExpression closestExpression = ContainerUtil.getFirstItem(extractableExpressions); int resultCount = closestExpression != null ? GoInspectionUtil.getExpressionResultCount(closestExpression) : 0; showCannotPerform(operation, "Expression " + (closestExpression != null ? closestExpression.getText() + " " : "") + (resultCount == 0 ? "doesn't return a value." : "returns multiple values.")); return; } if (expressions.size() == 1 || hasSelection || ApplicationManager.getApplication().isUnitTestMode()) { //noinspection ConstantConditions operation.setExpression(ContainerUtil.getFirstItem(expressions)); performOnElement(operation); } else { IntroduceTargetChooser.showChooser(operation.getEditor(), expressions, new Pass() { @Override public void pass(GoExpression expression) { if (expression.isValid()) { operation.setExpression(expression); performOnElement(operation); } } }, expression1 -> expression1.isValid() ? expression1.getText() : ""); } } @Nullable public static GoExpression findExpressionInSelection(@NotNull PsiFile file, int start, int end) { return PsiTreeUtil.findElementOfClassAtRange(file, start, end, GoExpression.class); } @Nullable private static GoExpression findExpressionAtOffset(GoIntroduceOperation operation) { PsiFile file = operation.getFile(); int offset = operation.getEditor().getCaretModel().getOffset(); GoExpression expr = PsiTreeUtil.getNonStrictParentOfType(file.findElementAt(offset), GoExpression.class); GoExpression preExpr = PsiTreeUtil.getNonStrictParentOfType(file.findElementAt(offset - 1), GoExpression.class); if (expr == null || preExpr != null && PsiTreeUtil.isAncestor(expr, preExpr, false)) return preExpr; return expr; } @NotNull private static List collectExtractableExpressions(@NotNull GoExpression expression) { if (PsiTreeUtil.getParentOfType(expression, GoStatement.class) == null) { return Collections.emptyList(); } return SyntaxTraverser.psiApi().parents(expression).takeWhile(Conditions.notInstanceOf(GoTopLevelDeclaration.class)) .filter(GoExpression.class) .filter(Conditions.notInstanceOf(GoParenthesesExpr.class)) .filter(expression1 -> !(expression1 instanceof GoReferenceExpression && expression1.getParent() instanceof GoCallExpr)) .toList(); } private static void performOnElement(@NotNull GoIntroduceOperation operation) { GoExpression expression = operation.getExpression(); LinkedHashSet suggestedNames = GoRefactoringUtil.getSuggestedNames(expression); operation.setSuggestedNames(suggestedNames); operation.setOccurrences(GoRefactoringUtil.getLocalOccurrences(expression)); Editor editor = operation.getEditor(); if (editor.getSettings().isVariableInplaceRenameEnabled()) { //noinspection ConstantConditions operation.setName(ContainerUtil.getFirstItem(suggestedNames)); if (ApplicationManager.getApplication().isUnitTestMode()) { performInplaceIntroduce(operation); return; } OccurrencesChooser.simpleChooser(editor) .showChooser(expression, operation.getOccurrences(), new Pass() { @Override public void pass(OccurrencesChooser.ReplaceChoice choice) { operation.setReplaceAll(choice == OccurrencesChooser.ReplaceChoice.ALL); performInplaceIntroduce(operation); } }); } else { GoIntroduceVariableDialog dialog = new GoIntroduceVariableDialog(operation); if (dialog.showAndGet()) { operation.setName(dialog.getName()); operation.setReplaceAll(dialog.getReplaceAll()); performReplace(operation); } } } private static void performInplaceIntroduce(GoIntroduceOperation operation) { if (!operation.getExpression().isValid()) { showCannotPerform(operation, RefactoringBundle.message("refactoring.introduce.context.error")); return; } performReplace(operation); new GoInplaceVariableIntroducer(operation).performInplaceRefactoring(operation.getSuggestedNames()); } private static void performReplace(GoIntroduceOperation operation) { Project project = operation.getProject(); PsiElement expression = operation.getExpression(); List occurrences = operation.isReplaceAll() ? operation.getOccurrences() : Collections.singletonList(expression); PsiElement anchor = GoRefactoringUtil.findLocalAnchor(occurrences); if (anchor == null) { showCannotPerform(operation, RefactoringBundle.message("refactoring.introduce.context.error")); return; } GoBlock context = (GoBlock)anchor.getParent(); String name = operation.getName(); List newOccurrences = ContainerUtil.newArrayList(); WriteCommandAction.runWriteCommandAction(project, () -> { GoStatement declarationStatement = GoElementFactory.createShortVarDeclarationStatement(project, name, (GoExpression)expression); PsiElement newLine = GoElementFactory.createNewLine(project); PsiElement statement = context.addBefore(declarationStatement, context.addBefore(newLine, anchor)); GoVarDefinition varDefinition = PsiTreeUtil.findChildOfType(statement, GoVarDefinition.class); assert varDefinition != null; assert varDefinition.isValid() : "invalid var `" + varDefinition.getText() + "` definition in `" + statement.getText() + "`"; operation.setVar(varDefinition); boolean firstOccurrence = true; for (PsiElement occurrence : occurrences) { PsiElement occurrenceParent = occurrence.getParent(); if (occurrenceParent instanceof GoParenthesesExpr) occurrence = occurrenceParent; if (firstOccurrence && occurrence instanceof GoExpression) { firstOccurrence = false; PsiElement parent = occurrence.getParent(); // single-expression statement if (parent instanceof GoLeftHandExprList && parent.getParent() instanceof GoSimpleStatement) { parent.getParent().delete(); continue; } } newOccurrences.add(occurrence.replace(GoElementFactory.createReferenceExpression(project, name))); } operation.getEditor().getCaretModel().moveToOffset(varDefinition.getIdentifier().getTextRange().getStartOffset()); }); operation.setOccurrences(newOccurrences); PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(operation.getEditor().getDocument()); } private static void showCannotPerform(GoIntroduceOperation operation, String message) { message = RefactoringBundle.getCannotRefactorMessage(message); CommonRefactoringUtil.showErrorHint(operation.getProject(), operation.getEditor(), message, RefactoringBundle.getCannotRefactorMessage(null), "refactoring.extractVariable"); } private static class GoInplaceVariableIntroducer extends InplaceVariableIntroducer { public GoInplaceVariableIntroducer(GoIntroduceOperation operation) { super(operation.getVar(), operation.getEditor(), operation.getProject(), "Introduce Variable", ArrayUtil.toObjectArray(operation.getOccurrences(), PsiElement.class), null); } } } ================================================ FILE: src/com/goide/refactor/GoIntroduceVariableDialog.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.GoFileType; import com.goide.GoNamesValidator; import com.intellij.openapi.options.ConfigurationException; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.ui.NameSuggestionsField; import com.intellij.refactoring.ui.RefactoringDialog; import com.intellij.ui.IdeBorderFactory; import com.intellij.util.ArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; class GoIntroduceVariableDialog extends RefactoringDialog { private final GoIntroduceOperation myOperation; private final int myOccurrencesCount; private NameSuggestionsField myNameField; private JCheckBox myReplaceAllCheckBox; protected GoIntroduceVariableDialog(GoIntroduceOperation operation) { super(operation.getProject(), true); myOperation = operation; myOccurrencesCount = operation.getOccurrences().size(); setTitle(RefactoringBundle.message("introduce.variable.title")); setModal(true); init(); } @Override protected boolean hasHelpAction() { return false; } @Override protected boolean hasPreviewButton() { return false; } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myNameField; } @Override protected void canRun() throws ConfigurationException { if (!areButtonsValid()) { throw new ConfigurationException(RefactoringBundle.message("refactoring.introduce.name.error"), getName()); } } @Nullable @Override protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); panel.add(createNamePanel(), BorderLayout.CENTER); if (myOccurrencesCount > 1) panel.add(createReplaceAllPanel(), BorderLayout.SOUTH); panel.setPreferredSize(new Dimension(myNameField.getWidth(), -1)); return panel; } private JComponent createNamePanel() { JPanel panel = new JPanel(new BorderLayout()); String[] names = ArrayUtil.toStringArray(myOperation.getSuggestedNames()); myNameField = new NameSuggestionsField(names, myOperation.getProject(), GoFileType.INSTANCE); myNameField.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 2, 3)); myNameField.addDataChangedListener(this::validateButtons); JLabel label = new JLabel(UIUtil.replaceMnemonicAmpersand(RefactoringBundle.message("name.prompt"))); label.setLabelFor(myNameField); panel.add(myNameField, BorderLayout.CENTER); panel.add(label, BorderLayout.WEST); return panel; } private JComponent createReplaceAllPanel() { JPanel panel = new JPanel(new FlowLayout()); String text = UIUtil.replaceMnemonicAmpersand(RefactoringBundle.message("replace.all.occurences", myOccurrencesCount)); myReplaceAllCheckBox = new JCheckBox(text); panel.add(myReplaceAllCheckBox); return panel; } @Override protected boolean areButtonsValid() { return new GoNamesValidator().isIdentifier(getName(), myProject); } @Override protected void doAction() { closeOKAction(); } public String getName() { return myNameField.getEnteredName(); } public boolean getReplaceAll() { return myReplaceAllCheckBox != null && myReplaceAllCheckBox.isSelected(); } } ================================================ FILE: src/com/goide/refactor/GoIntroduceVariableHandler.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; public class GoIntroduceVariableHandler extends GoIntroduceVariableBase implements RefactoringActionHandler { @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; performAction(new GoIntroduceOperation(project, editor, file)); } @Override public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) { } } ================================================ FILE: src/com/goide/refactor/GoRefactoringSupportProvider.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.psi.GoNamedElement; import com.intellij.lang.refactoring.RefactoringSupportProvider; import com.intellij.psi.PsiElement; import com.intellij.refactoring.RefactoringActionHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoRefactoringSupportProvider extends RefactoringSupportProvider { @Override public boolean isMemberInplaceRenameAvailable(@NotNull PsiElement element, PsiElement context) { return element instanceof GoNamedElement; } @Nullable @Override public RefactoringActionHandler getIntroduceVariableHandler() { return new GoIntroduceVariableHandler(); } } ================================================ FILE: src/com/goide/refactor/GoRefactoringUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.GoLanguage; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.GoTypeUtil; import com.intellij.codeInsight.PsiEquivalenceUtil; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.template.Expression; import com.intellij.codeInsight.template.ExpressionContext; import com.intellij.codeInsight.template.Result; import com.intellij.codeInsight.template.TextResult; import com.intellij.lang.LanguageNamesValidation; import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class GoRefactoringUtil { private GoRefactoringUtil() {} @NotNull public static List getLocalOccurrences(@NotNull PsiElement element) { return getOccurrences(element, PsiTreeUtil.getTopmostParentOfType(element, GoBlock.class)); } @NotNull public static List getOccurrences(@NotNull PsiElement pattern, @Nullable PsiElement context) { if (context == null) return Collections.emptyList(); List occurrences = ContainerUtil.newArrayList(); PsiRecursiveElementVisitor visitor = new PsiRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { if (PsiEquivalenceUtil.areElementsEquivalent(element, pattern)) { occurrences.add(element); return; } super.visitElement(element); } }; context.acceptChildren(visitor); return occurrences; } @Nullable public static PsiElement findLocalAnchor(@NotNull List occurrences) { return findAnchor(occurrences, PsiTreeUtil.getNonStrictParentOfType(PsiTreeUtil.findCommonParent(occurrences), GoBlock.class)); } @Nullable public static PsiElement findAnchor(@NotNull List occurrences, @Nullable PsiElement context) { PsiElement first = ContainerUtil.getFirstItem(occurrences); PsiElement statement = PsiTreeUtil.getNonStrictParentOfType(first, GoStatement.class); while (statement != null && statement.getParent() != context) { statement = statement.getParent(); } return statement == null ? GoPsiImplUtil.getTopLevelDeclaration(first) : statement; } public static LinkedHashSet getSuggestedNames(GoExpression expression) { return getSuggestedNames(expression, expression); } @NotNull public static Expression createParameterNameSuggestedExpression(GoExpression expression) { GoTopLevelDeclaration topLevelDecl = PsiTreeUtil.getParentOfType(expression, GoTopLevelDeclaration.class); return new ParameterNameExpression(getSuggestedNames(expression, topLevelDecl != null ? topLevelDecl.getNextSibling() : null)); } private static class ParameterNameExpression extends Expression { private final Set myNames; public ParameterNameExpression(@NotNull Set names) { myNames = names; } @Nullable @Override public Result calculateResult(ExpressionContext context) { LookupElement firstElement = ArrayUtil.getFirstElement(calculateLookupItems(context)); return new TextResult(firstElement != null ? firstElement.getLookupString() : ""); } @Nullable @Override public Result calculateQuickResult(ExpressionContext context) { return null; } @NotNull @Override public LookupElement[] calculateLookupItems(ExpressionContext context) { int offset = context.getStartOffset(); Project project = context.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); assert context.getEditor() != null; PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument()); assert file != null; PsiElement elementAt = file.findElementAt(offset); Set parameterNames = ContainerUtil.newHashSet(); GoParameters parameters = PsiTreeUtil.getParentOfType(elementAt, GoParameters.class); if (parameters != null) { GoParamDefinition parameter = PsiTreeUtil.getParentOfType(elementAt, GoParamDefinition.class); for (GoParameterDeclaration paramDecl : parameters.getParameterDeclarationList()) { for (GoParamDefinition paramDef : paramDecl.getParamDefinitionList()) { if (parameter != paramDef) { parameterNames.add(paramDef.getName()); } } } } Set set = ContainerUtil.newLinkedHashSet(); for (String name : myNames) { set.add(LookupElementBuilder.create(UniqueNameGenerator.generateUniqueName(name, parameterNames))); } return set.toArray(new LookupElement[set.size()]); } } @NotNull private static LinkedHashSet getSuggestedNames(GoExpression expression, PsiElement context) { // todo rewrite with names resolve; check occurrences contexts if (expression.isEquivalentTo(context)) { context = PsiTreeUtil.getParentOfType(context, GoBlock.class); } LinkedHashSet usedNames = getNamesInContext(context); LinkedHashSet names = ContainerUtil.newLinkedHashSet(); NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(GoLanguage.INSTANCE); if (expression instanceof GoCallExpr) { GoReferenceExpression callReference = PsiTreeUtil.getChildOfType(expression, GoReferenceExpression.class); if (callReference != null) { String name = StringUtil.decapitalize(callReference.getIdentifier().getText()); for (String candidate : NameUtil.getSuggestionsByName(name, "", "", false, false, false)) { if (usedNames.contains(candidate)) continue; if (!isValidName(namesValidator, candidate)) continue; names.add(candidate); } } } GoType type = expression.getGoType(null); String typeText = GoPsiImplUtil.getText(type); if (StringUtil.isNotEmpty(typeText)) { boolean array = GoTypeUtil.isIterable(type) && !GoTypeUtil.isString(type); for (String candidate : NameUtil.getSuggestionsByName(typeText, "", "", false, false, array)) { if (usedNames.contains(candidate) || typeText.equals(candidate)) continue; if (!isValidName(namesValidator, candidate)) continue; names.add(candidate); } } if (names.isEmpty()) { names.add(UniqueNameGenerator.generateUniqueName("i", usedNames)); } return names; } private static boolean isValidName(NamesValidator namesValidator, String candidate) { return namesValidator != null && !namesValidator.isKeyword(candidate, null) && namesValidator.isIdentifier(candidate, null); } @NotNull private static LinkedHashSet getNamesInContext(PsiElement context) { if (context == null) return ContainerUtil.newLinkedHashSet(); LinkedHashSet names = ContainerUtil.newLinkedHashSet(); for (GoNamedElement namedElement : PsiTreeUtil.findChildrenOfType(context, GoNamedElement.class)) { names.add(namedElement.getName()); } names.addAll(((GoFile)context.getContainingFile()).getImportMap().keySet()); GoFunctionDeclaration functionDeclaration = PsiTreeUtil.getParentOfType(context, GoFunctionDeclaration.class); GoSignature signature = PsiTreeUtil.getChildOfType(functionDeclaration, GoSignature.class); for (GoParamDefinition param : PsiTreeUtil.findChildrenOfType(signature, GoParamDefinition.class)) { names.add(param.getName()); } return names; } } ================================================ FILE: src/com/goide/refactor/GoRenameImportSpecProcessor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.psi.GoImportSpec; import com.intellij.find.FindManager; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiElement; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.rename.RenamePsiElementProcessor; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoRenameImportSpecProcessor extends RenamePsiElementProcessor { @Nullable @Override public PsiElement substituteElementToRename(PsiElement element, @Nullable Editor editor) { if (FindManager.getInstance(element.getProject()).canFindUsages(element)) { return element; } String message = RefactoringBundle.message("error.cannot.be.renamed"); CommonRefactoringUtil.showErrorHint(element.getProject(), editor, message, RefactoringBundle.message("rename.title"), null); return null; } @Override public boolean canProcessElement(@NotNull PsiElement element) { return element instanceof GoImportSpec; } } ================================================ FILE: src/com/goide/regexp/GoRegExpLanguage.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.regexp; import com.intellij.lang.Language; import org.intellij.lang.regexp.RegExpLanguage; public class GoRegExpLanguage extends Language { public static final GoRegExpLanguage INSTANCE = new GoRegExpLanguage(); private GoRegExpLanguage() { super(RegExpLanguage.INSTANCE, "GoRegExp"); } } ================================================ FILE: src/com/goide/regexp/GoRegExpParserDefinition.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.regexp; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IFileElementType; import org.intellij.lang.regexp.*; import org.jetbrains.annotations.NotNull; import java.util.EnumSet; public class GoRegExpParserDefinition extends RegExpParserDefinition { private static final IFileElementType GO_REGEXP_FILE = new IFileElementType("GO_REGEXP_FILE", GoRegExpLanguage.INSTANCE); private final EnumSet CAPABILITIES = EnumSet.of(RegExpCapability.UNICODE_CATEGORY_SHORTHAND, RegExpCapability.CARET_NEGATED_PROPERTIES, RegExpCapability.NESTED_CHARACTER_CLASSES, RegExpCapability.OCTAL_NO_LEADING_ZERO, RegExpCapability.POSIX_BRACKET_EXPRESSIONS); @Override @NotNull public Lexer createLexer(Project project) { return new RegExpLexer(CAPABILITIES); } @Override public PsiParser createParser(Project project) { return new RegExpParser(CAPABILITIES); } @Override public IFileElementType getFileNodeType() { return GO_REGEXP_FILE; } @Override public PsiFile createFile(FileViewProvider viewProvider) { return new RegExpFile(viewProvider, GoRegExpLanguage.INSTANCE); } } ================================================ FILE: src/com/goide/regexp/GoRegexHost.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.regexp; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.intellij.lang.regexp.RegExpLanguageHost; import org.intellij.lang.regexp.psi.RegExpChar; import org.intellij.lang.regexp.psi.RegExpGroup; import org.intellij.lang.regexp.psi.RegExpNamedGroupRef; import org.intellij.lang.regexp.psi.RegExpSimpleClass; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; // see https://golang.org/pkg/regexp/syntax/ public class GoRegexHost implements RegExpLanguageHost { @Override public boolean characterNeedsEscaping(char c) { return false; } @Override public boolean supportsPerl5EmbeddedComments() { return false; } @Override public boolean supportsPossessiveQuantifiers() { return false; } @Override public boolean supportsPythonConditionalRefs() { return false; } @Override public boolean supportsNamedGroupSyntax(RegExpGroup group) { return group.isPythonNamedGroup(); // only (?P) group is supported } @Override public boolean supportsNamedGroupRefSyntax(RegExpNamedGroupRef ref) { return false; } @Override public boolean supportsExtendedHexCharacter(RegExpChar regExpChar) { return true; } @Override public boolean isValidCategory(@NotNull String category) { return Lazy.KNOWN_PROPERTIES.contains(category); } @NotNull @Override public String[][] getAllKnownProperties() { return Lazy.KNOWN_PROPERTIES_ARRAY; } @Nullable @Override public String getPropertyDescription(@Nullable String name) { return name; } @NotNull @Override public String[][] getKnownCharacterClasses() { return Lazy.CHARACTER_CLASSES; } @Override public boolean supportsSimpleClass(RegExpSimpleClass simpleClass) { switch (simpleClass.getKind()) { case HORIZONTAL_SPACE: case NON_HORIZONTAL_SPACE: case NON_VERTICAL_SPACE: case XML_NAME_START: case NON_XML_NAME_START: case XML_NAME_PART: case NON_XML_NAME_PART: case UNICODE_GRAPHEME: case UNICODE_LINEBREAK: return false; case ANY: case DIGIT: case NON_DIGIT: case WORD: case NON_WORD: case SPACE: case NON_SPACE: case VERTICAL_SPACE: return true; } return false; } @Override public boolean supportsLiteralBackspace(RegExpChar aChar) { return false; } @Override public boolean supportsInlineOptionFlag(char flag, PsiElement context) { return StringUtil.containsChar("imsU", flag); } private interface Lazy { // SDK/unicode/tables.go Set KNOWN_PROPERTIES = ContainerUtil.immutableSet("C", "Cc", "Cf", "Co", "Cs", "L", "Ll", "Lm", "Lo", "Lt", "Lu", "M", "Mc", "Me", "Mn", "N", "Nd", "Nl", "No", "P", "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps", "S", "Sc", "Sk", "Sm", "So", "Z", "Zl", "Zp", "Zs", "Ahom", "Anatolian_Hieroglyphs", "Arabic", "Armenian", "Avestan", "Balinese", "Bamum", "Bassa_Vah", "Batak", "Bengali", "Bopomofo", "Brahmi", "Braille", "Buginese", "Buhid", "Canadian_Aboriginal", "Carian", "Caucasian_Albanian", "Chakma", "Cham", "Cherokee", "Common", "Coptic", "Cuneiform", "Cypriot", "Cyrillic", "Deseret", "Devanagari", "Duployan", "Egyptian_Hieroglyphs", "Elbasan", "Ethiopic", "Georgian", "Glagolitic", "Gothic", "Grantha", "Greek", "Gujarati", "Gurmukhi", "Han", "Hangul", "Hanunoo", "Hatran", "Hebrew", "Hiragana", "Imperial_Aramaic", "Inherited", "Inscriptional_Pahlavi", "Inscriptional_Parthian", "Javanese", "Kaithi", "Kannada", "Katakana", "Kayah_Li", "Kharoshthi", "Khmer", "Khojki", "Khudawadi", "Lao", "Latin", "Lepcha", "Limbu", "Linear_A", "Linear_B", "Lisu", "Lycian", "Lydian", "Mahajani", "Malayalam", "Mandaic", "Manichaean", "Meetei_Mayek", "Mende_Kikakui", "Meroitic_Cursive", "Meroitic_Hieroglyphs", "Miao", "Modi", "Mongolian", "Mro", "Multani", "Myanmar", "Nabataean", "New_Tai_Lue", "Nko", "Ogham", "Ol_Chiki", "Old_Hungarian", "Old_Italic", "Old_North_Arabian", "Old_Permic", "Old_Persian", "Old_South_Arabian", "Old_Turkic", "Oriya", "Osmanya", "Pahawh_Hmong", "Palmyrene", "Pau_Cin_Hau", "Phags_Pa", "Phoenician", "Psalter_Pahlavi", "Rejang", "Runic", "Samaritan", "Saurashtra", "Sharada", "Shavian", "Siddham", "SignWriting", "Sinhala", "Sora_Sompeng", "Sundanese", "Syloti_Nagri", "Syriac", "Tagalog", "Tagbanwa", "Tai_Le", "Tai_Tham", "Tai_Viet", "Takri", "Tamil", "Telugu", "Thaana", "Thai", "Tibetan", "Tifinagh", "Tirhuta", "Ugaritic", "Vai", "Warang_Citi", "Yi"); String[][] KNOWN_PROPERTIES_ARRAY = ContainerUtil.map2Array(KNOWN_PROPERTIES, new String[KNOWN_PROPERTIES.size()][2], s -> new String[]{s, ""}); String[][] CHARACTER_CLASSES = { // Empty strings {"A", "at beginning of text"}, {"b", "at ASCII word boundary (\\w on one side and \\W, \\A, or \\z on the other)"}, {"B", "not at ASCII word boundary"}, {"z", "at end of text"}, {"Z", "end of the text but for the final terminator, if any"}, // Escape sequences {"a", "bell (== \007)"}, {"f", "form feed (== \014)"}, {"t", "horizontal tab (== \011)"}, {"n", "newline (== \012)"}, {"r", "carriage return (== \015)"}, {"v", "vertical tab character (== \013)"}, {"*", "literal *, for any punctuation character *"}, {"Q", "nothing, but quotes all characters until \\E"}, {"E", "nothing, but ends quoting started by \\Q"}, // Perl character classes (all ASCII-only): {"d", "digits (== [0-9])"}, {"D", "not digits (== [^0-9])"}, {"s", "whitespace (== [\t\n\f\r ])"}, {"S", "not whitespace (== [^\t\n\f\r ])"}, {"w", "word characters (== [0-9A-Za-z_])"}, {"W", "not word characters (== [^0-9A-Za-z_])"}, }; } } ================================================ FILE: src/com/goide/regexp/GoRegexInjector.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.regexp; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.psi.*; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Set; public class GoRegexInjector implements LanguageInjector { private static final Set REGEXP_FUNCTION_NAMES = ContainerUtil.newHashSet( "Compile", "CompilePOSIX", "MustCompile", "MustCompilePOSIX", "Match", "MatchReader", "MatchString" ); @Override public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { if (!(host instanceof GoStringLiteral)) return; PsiElement topMostExpression = host; PsiElement argumentList = host.getParent(); while (argumentList instanceof GoParenthesesExpr) { topMostExpression = argumentList; argumentList = argumentList.getParent(); } if (!(argumentList instanceof GoArgumentList)) return; // must be first argument if (ContainerUtil.getFirstItem(((GoArgumentList)argumentList).getExpressionList()) != topMostExpression) return; GoCallExpr callExpression = ObjectUtils.tryCast(argumentList.getParent(), GoCallExpr.class); if (callExpression == null) return; GoReferenceExpression referenceExpression = ObjectUtils.tryCast(callExpression.getExpression(), GoReferenceExpression.class); if (referenceExpression != null && REGEXP_FUNCTION_NAMES.contains(referenceExpression.getIdentifier().getText())) { GoSignatureOwner resolvedCall = GoPsiImplUtil.resolveCall(callExpression); if (resolvedCall instanceof GoFunctionDeclaration) { PsiFile file = resolvedCall.getContainingFile(); if (file instanceof GoFile && "regexp".equals(((GoFile)file).getImportPath(false))) { injectionPlacesRegistrar.addPlace(GoRegExpLanguage.INSTANCE, ElementManipulators.getValueTextRange(host), null, null); } } } } } ================================================ FILE: src/com/goide/runconfig/GoBuildingRunner.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.GoEnvironmentUtil; import com.goide.dlv.DlvDebugProcess; import com.goide.dlv.DlvRemoteVmConnection; import com.goide.runconfig.application.GoApplicationConfiguration; import com.goide.runconfig.application.GoApplicationRunningState; import com.goide.util.GoHistoryProcessListener; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.RunProfileStarter; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.AsyncGenericProgramRunner; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.RunContentBuilder; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.internal.statistic.UsageTrigger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.net.NetUtils; import com.intellij.xdebugger.XDebugProcess; import com.intellij.xdebugger.XDebugProcessStarter; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.AsyncPromise; import org.jetbrains.concurrency.Promise; import org.jetbrains.debugger.connection.RemoteVmConnection; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; public class GoBuildingRunner extends AsyncGenericProgramRunner { private static final String ID = "GoBuildingRunner"; @NotNull @Override public String getRunnerId() { return ID; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { if (profile instanceof GoApplicationConfiguration) { return DefaultRunExecutor.EXECUTOR_ID.equals(executorId) || DefaultDebugExecutor.EXECUTOR_ID.equals(executorId) && !DlvDebugProcess.IS_DLV_DISABLED; } return false; } @NotNull @Override protected Promise prepare(@NotNull ExecutionEnvironment environment, @NotNull RunProfileState state) throws ExecutionException { File outputFile = getOutputFile(environment, (GoApplicationRunningState)state); FileDocumentManager.getInstance().saveAllDocuments(); AsyncPromise buildingPromise = new AsyncPromise<>(); GoHistoryProcessListener historyProcessListener = new GoHistoryProcessListener(); ((GoApplicationRunningState)state).createCommonExecutor() .withParameters("build") .withParameterString(((GoApplicationRunningState)state).getGoBuildParams()) .withParameters("-o", outputFile.getAbsolutePath()) .withParameters(((GoApplicationRunningState)state).isDebug() ? new String[]{"-gcflags", "-N -l"} : ArrayUtil.EMPTY_STRING_ARRAY) .withParameters(((GoApplicationRunningState)state).getTarget()) .disablePty() .withPresentableName("go build") .withProcessListener(historyProcessListener) .withProcessListener(new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { super.processTerminated(event); boolean compilationFailed = event.getExitCode() != 0; if (((GoApplicationRunningState)state).isDebug()) { buildingPromise.setResult(new MyDebugStarter(outputFile.getAbsolutePath(), historyProcessListener, compilationFailed)); } else { buildingPromise.setResult(new MyRunStarter(outputFile.getAbsolutePath(), historyProcessListener, compilationFailed)); } } }).executeWithProgress(false); return buildingPromise; } @NotNull private static File getOutputFile(@NotNull ExecutionEnvironment environment, @NotNull GoApplicationRunningState state) throws ExecutionException { File outputFile; String outputDirectoryPath = state.getConfiguration().getOutputFilePath(); RunnerAndConfigurationSettings settings = environment.getRunnerAndConfigurationSettings(); String configurationName = settings != null ? settings.getName() : "application"; if (StringUtil.isEmpty(outputDirectoryPath)) { try { outputFile = FileUtil.createTempFile(configurationName, "go", true); } catch (IOException e) { throw new ExecutionException("Cannot create temporary output file", e); } } else { File outputDirectory = new File(outputDirectoryPath); if (outputDirectory.isDirectory() || !outputDirectory.exists() && outputDirectory.mkdirs()) { outputFile = new File(outputDirectoryPath, GoEnvironmentUtil.getBinaryFileNameForPath(configurationName)); try { if (!outputFile.exists() && !outputFile.createNewFile()) { throw new ExecutionException("Cannot create output file " + outputFile.getAbsolutePath()); } } catch (IOException e) { throw new ExecutionException("Cannot create output file " + outputFile.getAbsolutePath()); } } else { throw new ExecutionException("Cannot create output file in " + outputDirectory.getAbsolutePath()); } } if (!prepareFile(outputFile)) { throw new ExecutionException("Cannot make temporary file executable " + outputFile.getAbsolutePath()); } return outputFile; } private static boolean prepareFile(@NotNull File file) { try { FileUtil.writeToFile(file, new byte[]{0x7F, 'E', 'L', 'F'}); } catch (IOException e) { return false; } return file.setExecutable(true); } private class MyDebugStarter extends RunProfileStarter { private final String myOutputFilePath; private final GoHistoryProcessListener myHistoryProcessListener; private final boolean myCompilationFailed; private MyDebugStarter(@NotNull String outputFilePath, @NotNull GoHistoryProcessListener historyProcessListener, boolean compilationFailed) { myOutputFilePath = outputFilePath; myHistoryProcessListener = historyProcessListener; myCompilationFailed = compilationFailed; } @Nullable @Override public RunContentDescriptor execute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env) throws ExecutionException { if (state instanceof GoApplicationRunningState) { int port = findFreePort(); FileDocumentManager.getInstance().saveAllDocuments(); ((GoApplicationRunningState)state).setHistoryProcessHandler(myHistoryProcessListener); ((GoApplicationRunningState)state).setOutputFilePath(myOutputFilePath); ((GoApplicationRunningState)state).setDebugPort(port); ((GoApplicationRunningState)state).setCompilationFailed(myCompilationFailed); // start debugger ExecutionResult executionResult = state.execute(env.getExecutor(), GoBuildingRunner.this); if (executionResult == null) { throw new ExecutionException("Cannot run debugger"); } UsageTrigger.trigger("go.dlv.debugger"); return XDebuggerManager.getInstance(env.getProject()).startSession(env, new XDebugProcessStarter() { @NotNull @Override public XDebugProcess start(@NotNull XDebugSession session) throws ExecutionException { RemoteVmConnection connection = new DlvRemoteVmConnection(); DlvDebugProcess process = new DlvDebugProcess(session, connection, executionResult); connection.open(new InetSocketAddress(NetUtils.getLoopbackAddress(), port)); return process; } }).getRunContentDescriptor(); } return null; } } private class MyRunStarter extends RunProfileStarter { private final String myOutputFilePath; private final GoHistoryProcessListener myHistoryProcessListener; private final boolean myCompilationFailed; private MyRunStarter(@NotNull String outputFilePath, @NotNull GoHistoryProcessListener historyProcessListener, boolean compilationFailed) { myOutputFilePath = outputFilePath; myHistoryProcessListener = historyProcessListener; myCompilationFailed = compilationFailed; } @Nullable @Override public RunContentDescriptor execute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env) throws ExecutionException { if (state instanceof GoApplicationRunningState) { FileDocumentManager.getInstance().saveAllDocuments(); ((GoApplicationRunningState)state).setHistoryProcessHandler(myHistoryProcessListener); ((GoApplicationRunningState)state).setOutputFilePath(myOutputFilePath); ((GoApplicationRunningState)state).setCompilationFailed(myCompilationFailed); ExecutionResult executionResult = state.execute(env.getExecutor(), GoBuildingRunner.this); return executionResult != null ? new RunContentBuilder(executionResult, env).showRunContent(env.getContentToReuse()) : null; } return null; } } private static int findFreePort() { try(ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); return socket.getLocalPort(); } catch (Exception ignore) { } throw new IllegalStateException("Could not find a free TCP/IP port to start dlv"); } } ================================================ FILE: src/com/goide/runconfig/GoConfigurationFactoryBase.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.intellij.compiler.options.CompileStepBeforeRun; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.openapi.util.Key; public abstract class GoConfigurationFactoryBase extends ConfigurationFactory { protected GoConfigurationFactoryBase(ConfigurationType type) { super(type); } @Override public void configureBeforeRunTaskDefaults(Key providerID, BeforeRunTask task) { super.configureBeforeRunTaskDefaults(providerID, task); if (providerID == CompileStepBeforeRun.ID) { task.setEnabled(false); } } } ================================================ FILE: src/com/goide/runconfig/GoConsoleFilter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.codeInsight.imports.GoGetPackageFix; import com.goide.sdk.GoPackageUtil; import com.goide.util.GoPathResolveScope; import com.goide.util.GoUtil; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.OpenFileHyperlinkInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.ex.temp.TempFileSystem; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.ObjectUtils; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GoConsoleFilter implements Filter { private static final Pattern MESSAGE_PATTERN = Pattern.compile("(?:^|\\s)(\\S+\\.\\w+):(\\d+)(:(\\d+))?(?=[:\\s]|$).*"); private static final Pattern GO_GET_MESSAGE_PATTERN = Pattern.compile("^[ \t]*(go get (.*))\n?$"); private static final Pattern APP_ENGINE_PATH_PATTERN = Pattern.compile("/tmp[A-z0-9]+appengine-go-bin/"); private static final Pattern GO_FILE_PATTERN = Pattern.compile("\\((\\w+\\.go)\\)"); @NotNull private final Project myProject; @Nullable private final Module myModule; @Nullable private final String myWorkingDirectoryUrl; @SuppressWarnings("unused") //used by pico container public GoConsoleFilter(@NotNull Project project) { this(project, null, null); } public GoConsoleFilter(@NotNull Project project, @Nullable Module module, @Nullable String workingDirectoryUrl) { myProject = project; myModule = module; myWorkingDirectoryUrl = ObjectUtils.chooseNotNull(workingDirectoryUrl, VfsUtilCore.pathToUrl(System.getProperty("user.dir"))); } @Override public Result applyFilter(@NotNull String line, int entireLength) { Matcher goGetMatcher = GO_GET_MESSAGE_PATTERN.matcher(line); if (goGetMatcher.find() && myModule != null) { String packageName = goGetMatcher.group(2).trim(); HyperlinkInfo hyperlinkInfo = new GoGetHyperlinkInfo(packageName, myModule); int lineStart = entireLength - line.length(); return new Result(lineStart + goGetMatcher.start(1), lineStart + goGetMatcher.end(2), hyperlinkInfo); } Matcher matcher = MESSAGE_PATTERN.matcher(line); if (!matcher.find()) { Matcher fileMatcher = GO_FILE_PATTERN.matcher(line); List resultItems = ContainerUtil.newArrayList(); while (fileMatcher.find()) { VirtualFile file = findSingleFile(fileMatcher.group(1)); if (file != null) { resultItems.add(createResult(line, entireLength, fileMatcher.start(1), fileMatcher.end(1), 0, 0, file)); } } return !resultItems.isEmpty() ? new Result(resultItems) : null; } int startOffset = matcher.start(1); int endOffset = matcher.end(2); String fileName = matcher.group(1); int lineNumber = StringUtil.parseInt(matcher.group(2), 1) - 1; if (lineNumber < 0) { return null; } int columnNumber = -1; if (matcher.groupCount() > 3) { columnNumber = StringUtil.parseInt(matcher.group(4), 1) - 1; endOffset = Math.max(endOffset, matcher.end(4)); } Matcher appEnginePathMatcher = APP_ENGINE_PATH_PATTERN.matcher(fileName); if (appEnginePathMatcher.find()) { fileName = fileName.substring(appEnginePathMatcher.end()); } VirtualFile virtualFile = null; if (FileUtil.isAbsolutePlatformIndependent(fileName)) { virtualFile = ApplicationManager.getApplication().isUnitTestMode() ? TempFileSystem.getInstance().refreshAndFindFileByPath(fileName) : VirtualFileManager.getInstance().refreshAndFindFileByUrl(VfsUtilCore.pathToUrl(fileName)); } else { if (myWorkingDirectoryUrl != null) { virtualFile = VirtualFileManager.getInstance().refreshAndFindFileByUrl(myWorkingDirectoryUrl + "/" + fileName); } if (virtualFile == null && myModule != null) { virtualFile = findInGoPath(fileName); if (virtualFile == null && fileName.startsWith("src/")) { virtualFile = findInGoPath(StringUtil.trimStart(fileName, "src/")); } } if (virtualFile == null) { VirtualFile baseDir = myProject.getBaseDir(); if (baseDir != null) { virtualFile = baseDir.findFileByRelativePath(fileName); if (virtualFile == null && fileName.startsWith("src/")) { // exclude src virtualFile = baseDir.findFileByRelativePath(StringUtil.trimStart(fileName, "src/")); } } } } if (virtualFile == null) { virtualFile = findSingleFile(fileName); } if (virtualFile == null) { return null; } return createResult(line, entireLength, startOffset, endOffset, lineNumber, columnNumber, virtualFile); } @NotNull private Result createResult(@NotNull String line, int entireLength, int startOffset, int endOffset, int lineNumber, int columnNumber, @NotNull VirtualFile virtualFile) { HyperlinkInfo hyperlinkInfo = new OpenFileHyperlinkInfo(myProject, virtualFile, lineNumber, columnNumber); int lineStart = entireLength - line.length(); return new Result(lineStart + startOffset, lineStart + endOffset, hyperlinkInfo); } @Nullable private VirtualFile findSingleFile(@NotNull String fileName) { if (PathUtil.isValidFileName(fileName)) { Collection files = FilenameIndex.getVirtualFilesByName(myProject, fileName, GlobalSearchScope.allScope(myProject)); if (files.size() == 1) { return ContainerUtil.getFirstItem(files); } if (!files.isEmpty()) { GlobalSearchScope goPathScope = GoPathResolveScope.create(myProject, myModule, null); files = ContainerUtil.filter(files, goPathScope::accept); if (files.size() == 1) { return ContainerUtil.getFirstItem(files); } } if (!files.isEmpty()) { GlobalSearchScope smallerScope = GoUtil.moduleScopeWithoutLibraries(myProject, myModule); files = ContainerUtil.filter(files, smallerScope::accept); if (files.size() == 1) { return ContainerUtil.getFirstItem(files); } } } return null; } @Nullable private VirtualFile findInGoPath(@NotNull String fileName) { return GoPackageUtil.findByImportPath(fileName, myProject, myModule); } public static class GoGetHyperlinkInfo implements HyperlinkInfo { private final String myPackageName; private final Module myModule; public GoGetHyperlinkInfo(@NotNull String packageName, @NotNull Module module) { myPackageName = packageName; myModule = module; } @NotNull public String getPackageName() { return myPackageName; } @Override public void navigate(Project project) { GoGetPackageFix.applyFix(project, myModule, myPackageName, false); } } } ================================================ FILE: src/com/goide/runconfig/GoModuleBasedConfiguration.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.intellij.execution.configurations.RunConfigurationModule; import com.intellij.openapi.project.Project; public class GoModuleBasedConfiguration extends RunConfigurationModule { public GoModuleBasedConfiguration(Project project) { super(project); } } ================================================ FILE: src/com/goide/runconfig/GoRunConfigurationBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configuration.EnvironmentVariablesComponent; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.RunConfigurationWithSuppressedDefaultRunAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Map; public abstract class GoRunConfigurationBase extends ModuleBasedConfiguration implements RunConfigurationWithSuppressedDefaultRunAction, RunConfigurationWithSuppressedDefaultDebugAction { private static final String WORKING_DIRECTORY_NAME = "working_directory"; private static final String GO_PARAMETERS_NAME = "go_parameters"; private static final String PARAMETERS_NAME = "parameters"; private static final String PASS_PARENT_ENV = "pass_parent_env"; @NotNull private String myWorkingDirectory = ""; @NotNull private String myGoParams = ""; @NotNull private String myParams = ""; @NotNull private final Map myCustomEnvironment = ContainerUtil.newHashMap(); private boolean myPassParentEnvironment = true; public GoRunConfigurationBase(String name, GoModuleBasedConfiguration configurationModule, ConfigurationFactory factory) { super(name, configurationModule, factory); Module module = configurationModule.getModule(); if (module == null) { Collection modules = getValidModules(); if (modules.size() == 1) { module = ContainerUtil.getFirstItem(modules); getConfigurationModule().setModule(module); } } if (module != null) { if (FileUtil.exists(module.getModuleFilePath())) { myWorkingDirectory = StringUtil.trimEnd(PathUtil.getParentPath(module.getModuleFilePath()), ".idea"); } } else { myWorkingDirectory = StringUtil.notNullize(configurationModule.getProject().getBasePath()); } } @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) throws ExecutionException { return createRunningState(environment); } @NotNull @Override public Collection getValidModules() { return GoSdkUtil.getGoModules(getProject()); } @Override public void checkConfiguration() throws RuntimeConfigurationException { GoModuleBasedConfiguration configurationModule = getConfigurationModule(); Module module = configurationModule.getModule(); if (module != null) { if (GoSdkService.getInstance(module.getProject()).getSdkHomePath(module) == null) { throw new RuntimeConfigurationWarning("Go SDK is not specified for module '" + module.getName() + "'"); } } else { String moduleName = configurationModule.getModuleName(); if (moduleName != null) { throw new RuntimeConfigurationError(ExecutionBundle.message("module.doesn.t.exist.in.project.error.text", moduleName)); } throw new RuntimeConfigurationError(ExecutionBundle.message("module.not.specified.error.text")); } if (myWorkingDirectory.isEmpty()) { throw new RuntimeConfigurationError("Working directory is not specified"); } } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); writeModule(element); addNonEmptyElement(element, WORKING_DIRECTORY_NAME, myWorkingDirectory); addNonEmptyElement(element, GO_PARAMETERS_NAME, myGoParams); addNonEmptyElement(element, PARAMETERS_NAME, myParams); if (!myCustomEnvironment.isEmpty()) { EnvironmentVariablesComponent.writeExternal(element, myCustomEnvironment); } if (!myPassParentEnvironment) { JDOMExternalizerUtil.addElementWithValueAttribute(element, PASS_PARENT_ENV, "false"); } } protected void addNonEmptyElement(@NotNull Element element, @NotNull String attributeName, @Nullable String value) { if (StringUtil.isNotEmpty(value)) { JDOMExternalizerUtil.addElementWithValueAttribute(element, attributeName, value); } } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); readModule(element); myGoParams = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, GO_PARAMETERS_NAME)); myParams = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, PARAMETERS_NAME)); String workingDirectoryValue = JDOMExternalizerUtil.getFirstChildValueAttribute(element, WORKING_DIRECTORY_NAME); if (workingDirectoryValue != null) { myWorkingDirectory = workingDirectoryValue; } EnvironmentVariablesComponent.readExternal(element, myCustomEnvironment); String passEnvValue = JDOMExternalizerUtil.getFirstChildValueAttribute(element, PASS_PARENT_ENV); myPassParentEnvironment = passEnvValue == null || Boolean.valueOf(passEnvValue); } @NotNull private RunningState createRunningState(ExecutionEnvironment env) throws ExecutionException { GoModuleBasedConfiguration configuration = getConfigurationModule(); Module module = configuration.getModule(); if (module == null) { throw new ExecutionException("Go isn't configured for run configuration: " + getName()); } return newRunningState(env, module); } @Nullable protected VirtualFile findFile(@NotNull String filePath) { VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.pathToUrl(filePath)); if (virtualFile == null) { String path = FileUtil.join(getWorkingDirectory(), filePath); virtualFile = VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.pathToUrl(path)); } return virtualFile; } @NotNull protected abstract RunningState newRunningState(ExecutionEnvironment env, Module module); @NotNull public String getGoToolParams() { return myGoParams; } @NotNull public String getParams() { return myParams; } public void setGoParams(@NotNull String params) { myGoParams = params; } public void setParams(@NotNull String params) { myParams = params; } @NotNull public Map getCustomEnvironment() { return myCustomEnvironment; } public void setCustomEnvironment(@NotNull Map customEnvironment) { myCustomEnvironment.clear(); myCustomEnvironment.putAll(customEnvironment); } public void setPassParentEnvironment(boolean passParentEnvironment) { myPassParentEnvironment = passParentEnvironment; } public boolean isPassParentEnvironment() { return myPassParentEnvironment; } @NotNull public String getWorkingDirectory() { return myWorkingDirectory; } @NotNull public String getWorkingDirectoryUrl() { return VfsUtilCore.pathToUrl(myWorkingDirectory); } public void setWorkingDirectory(@NotNull String workingDirectory) { myWorkingDirectory = workingDirectory; } } ================================================ FILE: src/com/goide/runconfig/GoRunConfigurationProducerBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.psi.GoFile; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoRunConfigurationProducerBase extends RunConfigurationProducer implements Cloneable { protected GoRunConfigurationProducerBase(@NotNull ConfigurationType configurationType) { super(configurationType); } @Override protected boolean setupConfigurationFromContext(@NotNull T configuration, @NotNull ConfigurationContext context, Ref sourceElement) { PsiFile file = getFileFromContext(context); if (GoRunUtil.isMainGoFile(file)) { configuration.setName(getConfigurationName(file)); configuration.setFilePath(file.getVirtualFile().getPath()); Module module = context.getModule(); if (module != null) { configuration.setModule(module); } return true; } return false; } @NotNull protected abstract String getConfigurationName(@NotNull PsiFile file); @Override public boolean isConfigurationFromContext(@NotNull T configuration, ConfigurationContext context) { GoFile file = getFileFromContext(context); return file != null && FileUtil.pathsEqual(configuration.getFilePath(), file.getVirtualFile().getPath()); } @Nullable private static GoFile getFileFromContext(@Nullable ConfigurationContext context) { PsiElement contextElement = GoRunUtil.getContextElement(context); PsiFile psiFile = contextElement != null ? contextElement.getContainingFile() : null; return psiFile instanceof GoFile ? (GoFile)psiFile : null; } } ================================================ FILE: src/com/goide/runconfig/GoRunConfigurationWithMain.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.psi.GoFile; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.execution.configurations.RuntimeConfigurationException; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import org.jdom.Element; import org.jetbrains.annotations.NotNull; public abstract class GoRunConfigurationWithMain extends GoRunConfigurationBase { private static final String FILE_PATH_ATTRIBUTE_NAME = "filePath"; @NotNull private String myFilePath = ""; public GoRunConfigurationWithMain(String name, GoModuleBasedConfiguration configurationModule, ConfigurationFactory factory) { super(name, configurationModule, factory); myFilePath = getWorkingDirectory(); } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); myFilePath = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, FILE_PATH_ATTRIBUTE_NAME)); } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); addNonEmptyElement(element, FILE_PATH_ATTRIBUTE_NAME, myFilePath); } protected void checkFileConfiguration() throws RuntimeConfigurationError { VirtualFile file = findFile(getFilePath()); if (file == null) { throw new RuntimeConfigurationError("Main file is not specified"); } PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(file); if (!(psiFile instanceof GoFile)) { throw new RuntimeConfigurationError("Main file is invalid"); } if (!GoRunUtil.isMainGoFile(psiFile)) { throw new RuntimeConfigurationError("Main file has non-main package or doesn't contain main function"); } } protected void checkBaseConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); } @NotNull public String getFilePath() { return myFilePath; } public void setFilePath(@NotNull String filePath) { myFilePath = filePath; } } ================================================ FILE: src/com/goide/runconfig/GoRunLineMarkerProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.GoConstants; import com.goide.GoTypes; import com.goide.psi.GoFunctionDeclaration; import com.intellij.execution.lineMarker.ExecutorAction; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.Function; import org.jetbrains.annotations.Nullable; public class GoRunLineMarkerProvider extends RunLineMarkerContributor { private static final Function TOOLTIP_PROVIDER = element -> "Run Application"; @Nullable @Override public Info getInfo(PsiElement e) { if (e != null && e.getNode().getElementType() == GoTypes.IDENTIFIER) { PsiElement parent = e.getParent(); PsiFile file = e.getContainingFile(); if (GoRunUtil.isMainGoFile(file) && parent instanceof GoFunctionDeclaration) { if (GoConstants.MAIN.equals(((GoFunctionDeclaration)parent).getName())) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, ExecutorAction.getActions(0)); } } } return null; } } ================================================ FILE: src/com/goide/runconfig/GoRunUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.GoConstants; import com.goide.GoFileType; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.ide.scratch.ScratchFileType; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.TextBrowseFolderListener; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; public class GoRunUtil { private GoRunUtil() { } @Contract("null -> false") public static boolean isPackageContext(@Nullable PsiElement contextElement) { return PsiTreeUtil.getNonStrictParentOfType(contextElement, GoPackageClause.class) != null; } @Nullable public static PsiFile findMainFileInDirectory(@NotNull VirtualFile packageDirectory, @NotNull Project project) { for (VirtualFile file : packageDirectory.getChildren()) { if (file == null) { continue; } PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (isMainGoFile(psiFile)) { return psiFile; } } return null; } @Nullable public static PsiElement getContextElement(@Nullable ConfigurationContext context) { if (context == null) { return null; } PsiElement psiElement = context.getPsiLocation(); if (psiElement == null || !psiElement.isValid()) { return null; } FileIndexFacade indexFacade = FileIndexFacade.getInstance(psiElement.getProject()); PsiFileSystemItem psiFile = psiElement instanceof PsiFileSystemItem ? (PsiFileSystemItem)psiElement : psiElement.getContainingFile(); VirtualFile file = psiFile != null ? psiFile.getVirtualFile() : null; if (file != null && file.getFileType() != ScratchFileType.INSTANCE && (!indexFacade.isInContent(file) || indexFacade.isExcludedFile(file))) { return null; } return psiElement; } public static void installGoWithMainFileChooser(Project project, @NotNull TextFieldWithBrowseButton fileField) { installFileChooser(project, fileField, false, false, file -> { if (file.getFileType() != GoFileType.INSTANCE) { return false; } return isMainGoFile(PsiManager.getInstance(project).findFile(file)); }); } @Contract("null -> false") public static boolean isMainGoFile(@Nullable PsiFile psiFile) { if (!GoTestFinder.isTestFile(psiFile) && psiFile instanceof GoFile) { return GoConstants.MAIN.equals(((GoFile)psiFile).getPackageName()) && ((GoFile)psiFile).hasMainFunction(); } return false; } public static void installFileChooser(@NotNull Project project, @NotNull ComponentWithBrowseButton field, boolean directory) { installFileChooser(project, field, directory, false); } public static void installFileChooser(@NotNull Project project, @NotNull ComponentWithBrowseButton field, boolean directory, boolean showFileSystemRoots) { installFileChooser(project, field, directory, showFileSystemRoots, null); } public static void installFileChooser(@NotNull Project project, @NotNull ComponentWithBrowseButton field, boolean directory, boolean showFileSystemRoots, @Nullable Condition fileFilter) { FileChooserDescriptor chooseDirectoryDescriptor = directory ? FileChooserDescriptorFactory.createSingleFolderDescriptor() : FileChooserDescriptorFactory.createSingleLocalFileDescriptor(); chooseDirectoryDescriptor.setRoots(project.getBaseDir()); chooseDirectoryDescriptor.setShowFileSystemRoots(showFileSystemRoots); chooseDirectoryDescriptor.withFileFilter(fileFilter); if (field instanceof TextFieldWithBrowseButton) { ((TextFieldWithBrowseButton)field).addBrowseFolderListener(new TextBrowseFolderListener(chooseDirectoryDescriptor, project)); } else { //noinspection unchecked field.addBrowseFolderListener(project, new ComponentWithBrowseButton.BrowseFolderActionListener(null, null, field, project, chooseDirectoryDescriptor, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT)); } } public static void printGoEnvVariables(@NotNull GeneralCommandLine commandLine, @NotNull ProcessHandler handler) { Map environment = commandLine.getEnvironment(); handler.notifyTextAvailable("GOROOT=" + StringUtil.nullize(environment.get(GoConstants.GO_ROOT)) + '\n', ProcessOutputTypes.SYSTEM); handler.notifyTextAvailable("GOPATH=" + StringUtil.nullize(environment.get(GoConstants.GO_PATH)) + '\n', ProcessOutputTypes.SYSTEM); } } ================================================ FILE: src/com/goide/runconfig/GoRunner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.runners.DefaultProgramRunner; import org.jetbrains.annotations.NotNull; public class GoRunner extends DefaultProgramRunner { private static final String ID = "GoRunner"; @NotNull @Override public String getRunnerId() { return ID; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { return DefaultRunExecutor.EXECUTOR_ID.equals(executorId) && profile instanceof GoRunConfigurationBase; } } ================================================ FILE: src/com/goide/runconfig/GoRunningState.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.util.GoExecutor; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.CommandLineState; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.KillableColoredProcessHandler; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import org.jetbrains.annotations.NotNull; public abstract class GoRunningState> extends CommandLineState { @NotNull protected final Module myModule; @NotNull public T getConfiguration() { return myConfiguration; } @NotNull protected final T myConfiguration; public GoRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull T configuration) { super(env); myModule = module; myConfiguration = configuration; addConsoleFilters(new GoConsoleFilter(myConfiguration.getProject(), myModule, myConfiguration.getWorkingDirectoryUrl())); } @NotNull @Override protected ProcessHandler startProcess() throws ExecutionException { GoExecutor executor = patchExecutor(createCommonExecutor()); GeneralCommandLine commandLine = executor.withParameterString(myConfiguration.getParams()).createCommandLine(); KillableColoredProcessHandler handler = new KillableColoredProcessHandler(commandLine, true); ProcessTerminatedListener.attach(handler); return handler; } @NotNull public GoExecutor createCommonExecutor() { return GoExecutor.in(myModule).withWorkDirectory(myConfiguration.getWorkingDirectory()) .withExtraEnvironment(myConfiguration.getCustomEnvironment()) .withPassParentEnvironment(myConfiguration.isPassParentEnvironment()); } protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { return executor; } } ================================================ FILE: src/com/goide/runconfig/application/GoApplicationConfiguration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.application; import com.goide.runconfig.GoModuleBasedConfiguration; import com.goide.runconfig.GoRunConfigurationWithMain; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.ui.GoApplicationConfigurationEditorForm; import com.goide.sdk.GoPackageUtil; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jdom.Element; import org.jetbrains.annotations.NotNull; public class GoApplicationConfiguration extends GoRunConfigurationWithMain { private static final String PACKAGE_ATTRIBUTE_NAME = "package"; private static final String KIND_ATTRIBUTE_NAME = "kind"; @NotNull private String myPackage = ""; @NotNull private Kind myKind = Kind.FILE; public GoApplicationConfiguration(Project project, String name, @NotNull ConfigurationType configurationType) { super(name, new GoModuleBasedConfiguration(project), configurationType.getConfigurationFactories()[0]); } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); myPackage = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, PACKAGE_ATTRIBUTE_NAME)); try { String kindName = JDOMExternalizerUtil.getFirstChildValueAttribute(element, KIND_ATTRIBUTE_NAME); myKind = kindName != null ? Kind.valueOf(kindName) : Kind.PACKAGE; } catch (IllegalArgumentException e) { myKind = !myPackage.isEmpty() ? Kind.PACKAGE : Kind.FILE; } } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); JDOMExternalizerUtil.addElementWithValueAttribute(element, KIND_ATTRIBUTE_NAME, myKind.name()); if (!myPackage.isEmpty()) { JDOMExternalizerUtil.addElementWithValueAttribute(element, PACKAGE_ATTRIBUTE_NAME, myPackage); } } @NotNull @Override protected ModuleBasedConfiguration createInstance() { return new GoApplicationConfiguration(getProject(), getName(), GoApplicationRunConfigurationType.getInstance()); } @NotNull @Override public SettingsEditor getConfigurationEditor() { return new GoApplicationConfigurationEditorForm(getProject()); } @NotNull @Override protected GoApplicationRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module) { return new GoApplicationRunningState(env, module, this); } @Override public void checkConfiguration() throws RuntimeConfigurationException { checkBaseConfiguration(); switch (myKind) { case PACKAGE: Module module = getConfigurationModule().getModule(); assert module != null; if (StringUtil.isEmptyOrSpaces(myPackage)) { throw new RuntimeConfigurationError("Package is not specified"); } VirtualFile packageDirectory = GoPackageUtil.findByImportPath(myPackage, module.getProject(), module); if (packageDirectory == null || !packageDirectory.isDirectory()) { throw new RuntimeConfigurationError("Cannot find package '" + myPackage + "'"); } if (GoRunUtil.findMainFileInDirectory(packageDirectory, getProject()) == null) { throw new RuntimeConfigurationError("Cannot find Go file with main in '" + myPackage + "'"); } break; case FILE: checkFileConfiguration(); break; } } @NotNull public String getPackage() { return myPackage; } public void setPackage(@NotNull String aPackage) { myPackage = aPackage; } @NotNull public Kind getKind() { return myKind; } public void setKind(@NotNull Kind aKind) { myKind = aKind; } public enum Kind { PACKAGE, FILE } } ================================================ FILE: src/com/goide/runconfig/application/GoApplicationRunConfigurationProducer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.application; import com.goide.psi.GoFile; import com.goide.runconfig.GoRunConfigurationProducerBase; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoSdkUtil; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoApplicationRunConfigurationProducer extends GoRunConfigurationProducerBase implements Cloneable { public GoApplicationRunConfigurationProducer() { super(GoApplicationRunConfigurationType.getInstance()); } @Override protected boolean setupConfigurationFromContext(@NotNull GoApplicationConfiguration configuration, @NotNull ConfigurationContext context, Ref sourceElement) { PsiElement contextElement = GoRunUtil.getContextElement(context); if (contextElement != null && GoTestFinder.isTestFile(contextElement.getContainingFile())) { return false; } String importPath = getImportPathFromContext(contextElement); if (StringUtil.isNotEmpty(importPath)) { configuration.setModule(context.getModule()); configuration.setKind(GoApplicationConfiguration.Kind.PACKAGE); configuration.setPackage(importPath); configuration.setName("Build " + importPath + " and run"); return true; } if (super.setupConfigurationFromContext(configuration, context, sourceElement)) { configuration.setKind(GoApplicationConfiguration.Kind.FILE); return true; } return false; } @Nullable private static String getImportPathFromContext(@Nullable PsiElement contextElement) { if (GoRunUtil.isPackageContext(contextElement)) { PsiFile file = contextElement.getContainingFile(); if (file instanceof GoFile) { return ((GoFile)file).getImportPath(false); } } else if (contextElement instanceof PsiDirectory) { return GoSdkUtil.getImportPath((PsiDirectory)contextElement, false); } return null; } @Override public boolean isConfigurationFromContext(@NotNull GoApplicationConfiguration configuration, ConfigurationContext context) { PsiElement contextElement = GoRunUtil.getContextElement(context); if (contextElement == null) return false; Module module = ModuleUtilCore.findModuleForPsiElement(contextElement); if (!Comparing.equal(module, configuration.getConfigurationModule().getModule())) return false; if (configuration.getKind() == GoApplicationConfiguration.Kind.PACKAGE) { return Comparing.equal(getImportPathFromContext(contextElement), configuration.getPackage()); } return super.isConfigurationFromContext(configuration, context); } @NotNull @Override protected String getConfigurationName(@NotNull PsiFile file) { return "Build " + file.getName() + " and run"; } } ================================================ FILE: src/com/goide/runconfig/application/GoApplicationRunConfigurationType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.application; import com.goide.GoConstants; import com.goide.GoIcons; import com.goide.runconfig.GoConfigurationFactoryBase; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class GoApplicationRunConfigurationType extends ConfigurationTypeBase { public GoApplicationRunConfigurationType() { super("GoApplicationRunConfiguration", "Go Application", "Go application run configuration", GoIcons.APPLICATION_RUN); addFactory(new GoConfigurationFactoryBase(this) { @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new GoApplicationConfiguration(project, GoConstants.GO, getInstance()); } }); } @NotNull public static GoApplicationRunConfigurationType getInstance() { return Extensions.findExtension(CONFIGURATION_TYPE_EP, GoApplicationRunConfigurationType.class); } } ================================================ FILE: src/com/goide/runconfig/application/GoApplicationRunningState.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.application; import com.goide.GoConstants; import com.goide.runconfig.GoRunningState; import com.goide.util.GoExecutor; import com.goide.util.GoHistoryProcessListener; import com.goide.util.GoUtil; import com.intellij.execution.ExecutionException; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; public class GoApplicationRunningState extends GoRunningState { private String myOutputFilePath; @Nullable private GoHistoryProcessListener myHistoryProcessHandler; private int myDebugPort = 59090; private boolean myCompilationFailed; public GoApplicationRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoApplicationConfiguration configuration) { super(env, module, configuration); } @NotNull public String getTarget() { return myConfiguration.getKind() == GoApplicationConfiguration.Kind.PACKAGE ? myConfiguration.getPackage() : myConfiguration.getFilePath(); } @NotNull public String getGoBuildParams() { return myConfiguration.getGoToolParams(); } public boolean isDebug() { return DefaultDebugExecutor.EXECUTOR_ID.equals(getEnvironment().getExecutor().getId()); } @NotNull @Override protected ProcessHandler startProcess() throws ExecutionException { ProcessHandler processHandler = myCompilationFailed ? new GoNopProcessHandler() : super.startProcess(); processHandler.addProcessListener(new ProcessAdapter() { @Override public void startNotified(ProcessEvent event) { if (myHistoryProcessHandler != null) { myHistoryProcessHandler.apply(processHandler); } } @Override public void processTerminated(ProcessEvent event) { super.processTerminated(event); if (StringUtil.isEmpty(myConfiguration.getOutputFilePath())) { File file = new File(myOutputFilePath); if (file.exists()) { //noinspection ResultOfMethodCallIgnored file.delete(); } } } }); return processHandler; } @Override protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { if (isDebug()) { File dlv = dlv(); if (dlv.exists() && !dlv.canExecute()) { //noinspection ResultOfMethodCallIgnored dlv.setExecutable(true, false); } return executor.withExePath(dlv.getAbsolutePath()) .withParameters("--listen=localhost:" + myDebugPort, "--headless=true", "exec", myOutputFilePath, "--"); } return executor.showGoEnvVariables(false).withExePath(myOutputFilePath); } @NotNull private static File dlv() { String dlvPath = System.getProperty("dlv.path"); if (StringUtil.isNotEmpty(dlvPath)) return new File(dlvPath); return new File(GoUtil.getPlugin().getPath(), "lib/dlv/" + (SystemInfo.isMac ? "mac" : SystemInfo.isWindows ? "windows" : "linux") + "/" + GoConstants.DELVE_EXECUTABLE_NAME + (SystemInfo.isWindows ? ".exe" : "")); } public void setOutputFilePath(@NotNull String outputFilePath) { myOutputFilePath = outputFilePath; } public void setHistoryProcessHandler(@Nullable GoHistoryProcessListener historyProcessHandler) { myHistoryProcessHandler = historyProcessHandler; } public void setDebugPort(int debugPort) { myDebugPort = debugPort; } public void setCompilationFailed(boolean compilationFailed) { myCompilationFailed = compilationFailed; } } ================================================ FILE: src/com/goide/runconfig/application/GoNopProcessHandler.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.application; import com.intellij.execution.process.ProcessHandler; import org.jetbrains.annotations.Nullable; import java.io.OutputStream; // todo[zolotov]: replace with built-in implementation in 2017.1 public class GoNopProcessHandler extends ProcessHandler { public GoNopProcessHandler() { destroyProcess(); } @Override protected void destroyProcessImpl() { notifyProcessTerminated(0); } @Override protected void detachProcessImpl() { notifyProcessDetached(); } @Override public boolean detachIsDefault() { return false; } @Nullable @Override public OutputStream getProcessInput() { return null; } } ================================================ FILE: src/com/goide/runconfig/before/GoBeforeRunTaskProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.before; import com.goide.GoIcons; import com.goide.runconfig.GoRunConfigurationBase; import com.goide.sdk.GoSdkService; import com.goide.util.GoExecutor; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoBeforeRunTaskProvider extends BeforeRunTaskProvider { public static final Key ID = Key.create("GoBeforeRunTask"); @Override public Key getId() { return ID; } @Override public String getName() { return "Go Command"; } @Override public String getDescription(GoCommandBeforeRunTask task) { return "Run `" + task + "`"; } @Nullable @Override public Icon getIcon() { return GoIcons.APPLICATION_RUN; } @Override public boolean isConfigurable() { return true; } @Nullable @Override public Icon getTaskIcon(GoCommandBeforeRunTask task) { return getIcon(); } @Nullable @Override public GoCommandBeforeRunTask createTask(RunConfiguration runConfiguration) { return runConfiguration instanceof GoRunConfigurationBase ? new GoCommandBeforeRunTask() : null; } @Override public boolean configureTask(RunConfiguration configuration, GoCommandBeforeRunTask task) { Project project = configuration.getProject(); if (!(configuration instanceof GoRunConfigurationBase)) { showAddingTaskErrorMessage(project, "Go Command task supports only Go Run Configurations"); return false; } Module module = ((GoRunConfigurationBase)configuration).getConfigurationModule().getModule(); if (!GoSdkService.getInstance(project).isGoModule(module)) { showAddingTaskErrorMessage(project, "Go Command task supports only Go Modules"); return false; } GoCommandConfigureDialog dialog = new GoCommandConfigureDialog(project); if (dialog.showAndGet()) { task.setCommand(dialog.getCommand()); return true; } return false; } @Override public boolean canExecuteTask(RunConfiguration configuration, GoCommandBeforeRunTask task) { if (configuration instanceof GoRunConfigurationBase) { Module module = ((GoRunConfigurationBase)configuration).getConfigurationModule().getModule(); GoSdkService sdkService = GoSdkService.getInstance(configuration.getProject()); if (sdkService.isGoModule(module)) { return StringUtil.isNotEmpty(sdkService.getSdkHomePath(module)) && StringUtil.isNotEmpty(task.getCommand()); } } return false; } @Override public boolean executeTask(DataContext context, RunConfiguration configuration, ExecutionEnvironment env, GoCommandBeforeRunTask task) { Semaphore done = new Semaphore(); Ref result = Ref.create(false); GoRunConfigurationBase goRunConfiguration = (GoRunConfigurationBase)configuration; Module module = goRunConfiguration.getConfigurationModule().getModule(); Project project = configuration.getProject(); String workingDirectory = goRunConfiguration.getWorkingDirectory(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { if (StringUtil.isEmpty(task.getCommand())) return; if (project == null || project.isDisposed()) return; GoSdkService sdkService = GoSdkService.getInstance(project); if (!sdkService.isGoModule(module)) return; done.down(); GoExecutor.in(module).withParameterString(task.getCommand()) .withWorkDirectory(workingDirectory) .showOutputOnError() .showNotifications(false, true) .withPresentableName("Executing `" + task + "`") .withProcessListener(new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { done.up(); result.set(event.getExitCode() == 0); } }) .executeWithProgress(false, result1 -> VirtualFileManager.getInstance().asyncRefresh(null)); } }); done.waitFor(); return result.get(); } private static void showAddingTaskErrorMessage(Project project, String message) { Messages.showErrorDialog(project, message, "Go Command Task"); } } ================================================ FILE: src/com/goide/runconfig/before/GoCommandBeforeRunTask.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.before; import com.intellij.execution.BeforeRunTask; import com.intellij.openapi.util.text.StringUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; public class GoCommandBeforeRunTask extends BeforeRunTask { @NonNls private static final String COMMAND_ATTRIBUTE = "command"; private String myCommand; public GoCommandBeforeRunTask() { super(GoBeforeRunTaskProvider.ID); } public String getCommand() { return myCommand; } public void setCommand(String command) { myCommand = command; } @Override public void writeExternal(Element element) { super.writeExternal(element); if (myCommand != null) { element.setAttribute(COMMAND_ATTRIBUTE, myCommand); } } @Override public void readExternal(Element element) { super.readExternal(element); String command = element.getAttributeValue(COMMAND_ATTRIBUTE); if (command != null) { myCommand = command; } } @Override public String toString() { return "go " + StringUtil.notNullize(myCommand); } } ================================================ FILE: src/com/goide/runconfig/before/GoCommandConfigureDialog.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.before; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.ui.TextFieldWithAutoCompletion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Arrays; import java.util.Collection; public class GoCommandConfigureDialog extends DialogWrapper { private static final Collection PREDEFINED_COMMANDS = Arrays.asList("vet", "test -i"); private final TextFieldWithAutoCompletion myCommandTextField; public GoCommandConfigureDialog(@NotNull Project project) { super(project); setTitle("Edit Go Command Task"); setModal(true); myCommandTextField = TextFieldWithAutoCompletion.create(project, PREDEFINED_COMMANDS, false, null); init(); } @Nullable @Override protected ValidationInfo doValidate() { String command = getCommand(); if (command.isEmpty()) { return new ValidationInfo("Empty Go command is not allowed", myCommandTextField); } if (command.startsWith("go ")) { return new ValidationInfo("Go command shouldn't started with `go`", myCommandTextField); } return super.doValidate(); } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myCommandTextField; } @Nullable @Override protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); panel.add(myCommandTextField, BorderLayout.NORTH); return panel; } @NotNull public String getCommand() { return myCommandTextField.getText().trim(); } } ================================================ FILE: src/com/goide/runconfig/file/GoRunFileConfiguration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.file; import com.goide.runconfig.GoModuleBasedConfiguration; import com.goide.runconfig.GoRunConfigurationWithMain; import com.goide.runconfig.ui.GoRunFileConfigurationEditorForm; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.ModuleBasedConfiguration; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.configurations.RuntimeConfigurationException; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.scratch.ScratchFileType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.UUID; public class GoRunFileConfiguration extends GoRunConfigurationWithMain { public GoRunFileConfiguration(Project project, String name, @NotNull ConfigurationType configurationType) { super(name, new GoModuleBasedConfiguration(project), configurationType.getConfigurationFactories()[0]); } @NotNull @Override protected ModuleBasedConfiguration createInstance() { return new GoRunFileConfiguration(getProject(), getName(), GoRunFileConfigurationType.getInstance()); } @NotNull @Override public SettingsEditor getConfigurationEditor() { return new GoRunFileConfigurationEditorForm(getProject()); } @Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkBaseConfiguration(); super.checkFileConfiguration(); } @NotNull @Override protected GoRunFileRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module) { String path = getFilePath(); if (!"go".equals(PathUtil.getFileExtension(path))) { VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); if (f != null && f.getFileType() == ScratchFileType.INSTANCE) { String suffixWithoutExt = "." + UUID.randomUUID().toString().substring(0, 4); String suffix = suffixWithoutExt + ".go"; String before = f.getName(); String beforeWithoutExt = FileUtil.getNameWithoutExtension(before); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { try { f.rename(this, before + suffix); } catch (IOException ignored) { } } }); setFilePath(path + suffix); setName(getName().replace(beforeWithoutExt, beforeWithoutExt + suffixWithoutExt)); } } return new GoRunFileRunningState(env, module, this); } } ================================================ FILE: src/com/goide/runconfig/file/GoRunFileConfigurationProducer.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.file; import com.goide.runconfig.GoRunConfigurationProducerBase; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoRunFileConfigurationProducer extends GoRunConfigurationProducerBase implements Cloneable { public GoRunFileConfigurationProducer() { super(GoRunFileConfigurationType.getInstance()); } @Override @NotNull protected String getConfigurationName(@NotNull PsiFile file) { return "go run " + file.getName(); } } ================================================ FILE: src/com/goide/runconfig/file/GoRunFileConfigurationType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.file; import com.goide.GoConstants; import com.goide.GoIcons; import com.goide.runconfig.GoConfigurationFactoryBase; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class GoRunFileConfigurationType extends ConfigurationTypeBase { public GoRunFileConfigurationType() { super("GoRunFileConfiguration", "Go Single File", "Go single run file configuration", GoIcons.APPLICATION_RUN); addFactory(new GoConfigurationFactoryBase(this) { @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new GoRunFileConfiguration(project, GoConstants.GO, getInstance()); } }); } @NotNull public static GoRunFileConfigurationType getInstance() { return Extensions.findExtension(CONFIGURATION_TYPE_EP, GoRunFileConfigurationType.class); } } ================================================ FILE: src/com/goide/runconfig/file/GoRunFileRunningState.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.file; import com.goide.runconfig.GoRunningState; import com.goide.util.GoExecutor; import com.intellij.execution.ExecutionException; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import org.jetbrains.annotations.NotNull; public class GoRunFileRunningState extends GoRunningState { public GoRunFileRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, GoRunFileConfiguration configuration) { super(env, module, configuration); } @Override protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { return executor .withParameters("run") .withParameterString(myConfiguration.getGoToolParams()) .withParameters(myConfiguration.getFilePath()); } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestConfigurationFactoryBase.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.GoConfigurationFactoryBase; import com.goide.runconfig.before.GoBeforeRunTaskProvider; import com.goide.runconfig.before.GoCommandBeforeRunTask; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; public abstract class GoTestConfigurationFactoryBase extends GoConfigurationFactoryBase { public GoTestConfigurationFactoryBase(@NotNull ConfigurationTypeBase type) { super(type); } @Override public void configureBeforeRunTaskDefaults(Key providerID, BeforeRunTask task) { super.configureBeforeRunTaskDefaults(providerID, task); if (providerID == GoBeforeRunTaskProvider.ID && task instanceof GoCommandBeforeRunTask && ((GoCommandBeforeRunTask)task).getCommand() == null) { task.setEnabled(true); ((GoCommandBeforeRunTask)task).setCommand("test -i"); } } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestConsoleProperties.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.runconfig.GoRunConfigurationBase; import com.goide.sdk.GoPackageUtil; import com.goide.util.GoUtil; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.Location; import com.intellij.execution.PsiLocation; import com.intellij.execution.configurations.RunConfigurationBase; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.Filter; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction; import com.intellij.execution.testframework.sm.SMCustomMessagesParsing; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties; import com.intellij.execution.testframework.sm.runner.SMTestLocator; import com.intellij.execution.ui.ConsoleView; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopesCore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class GoTestConsoleProperties extends SMTRunnerConsoleProperties implements SMCustomMessagesParsing { public GoTestConsoleProperties(@NotNull GoTestRunConfiguration configuration, @NotNull Executor executor) { super(configuration, configuration.getTestFramework().getName(), executor); setPrintTestingStartedTime(false); } @NotNull @Override protected GlobalSearchScope initScope() { RunProfile configuration = getConfiguration(); if (configuration instanceof GoTestRunConfiguration) { Project project = ((GoTestRunConfiguration)configuration).getProject(); Module module = ((GoTestRunConfiguration)configuration).getConfigurationModule().getModule(); switch (((GoTestRunConfiguration)configuration).getKind()) { case DIRECTORY: String directoryUrl = VfsUtilCore.pathToUrl(((GoTestRunConfiguration)configuration).getDirectoryPath()); VirtualFile directory = VirtualFileManager.getInstance().findFileByUrl(directoryUrl); if (directory != null) { return GlobalSearchScopesCore.directoryScope(project, directory, true); } break; case PACKAGE: VirtualFile packageDir = GoPackageUtil.findByImportPath(((GoTestRunConfiguration)configuration).getPackage(), project, module); PsiDirectory psiDirectory = packageDir != null ? PsiManager.getInstance(project).findDirectory(packageDir) : null; if (psiDirectory != null) { return GoPackageUtil.packageScope(psiDirectory, null); } break; case FILE: String fileUrl = VfsUtilCore.pathToUrl(((GoTestRunConfiguration)configuration).getFilePath()); VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(fileUrl); if (file != null) { return GlobalSearchScope.fileScope(project, file); } break; } } if (configuration instanceof GoRunConfigurationBase) { GlobalSearchScope scope = GlobalSearchScope.EMPTY_SCOPE; for (Module module : ((GoRunConfigurationBase)configuration).getModules()) { scope = new GoUtil.TestsScope(GoUtil.goPathResolveScope(module, null)); } return scope; } return super.initScope(); } @Nullable @Override public SMTestLocator getTestLocator() { return GoTestLocator.INSTANCE; } @NotNull @Override public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties) { RunProfile configuration = getConfiguration(); assert configuration instanceof GoTestRunConfiguration; return ((GoTestRunConfiguration)configuration).createTestEventsConverter(consoleProperties); } @Nullable @Override public AbstractRerunFailedTestsAction createRerunFailedTestsAction(ConsoleView consoleView) { AnAction rerunFailedTestsAction = ActionManager.getInstance().getAction("RerunFailedTests"); return rerunFailedTestsAction != null ? new GoRerunFailedTestsAction(this, consoleView) : null; } private static class GoRerunFailedTestsAction extends AbstractRerunFailedTestsAction { public GoRerunFailedTestsAction(GoTestConsoleProperties properties, ConsoleView view) { super(view); init(properties); } @NotNull @Override protected Filter getFilter(@NotNull Project project, @NotNull GlobalSearchScope searchScope) { return super.getFilter(project, searchScope).and(new Filter() { @Override public boolean shouldAccept(AbstractTestProxy test) { Location location = test.getLocation(project, searchScope); return location instanceof PsiLocation && location.getPsiElement() instanceof GoFunctionOrMethodDeclaration; } }); } @Nullable @Override protected MyRunProfile getRunProfile(@NotNull ExecutionEnvironment environment) { return new MyRunProfile((RunConfigurationBase)myConsoleProperties.getConfiguration()) { @NotNull @Override public Module[] getModules() { return Module.EMPTY_ARRAY; } @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) throws ExecutionException { RunConfigurationBase configurationBase = getPeer(); if (configurationBase instanceof GoTestRunConfiguration) { List failedTests = getFailedTests(configurationBase.getProject()); if (failedTests.isEmpty()) { return null; } GoTestRunConfiguration goTestRunConfiguration = (GoTestRunConfiguration)configurationBase; Module module = goTestRunConfiguration.getConfigurationModule().getModule(); GoTestRunningState runningState = goTestRunConfiguration.newRunningState(environment, module); runningState.setFailedTests(failedTests); return runningState; } return null; } }; } } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestEventsConverterBase.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.intellij.openapi.util.Key; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor; import org.jetbrains.annotations.NotNull; import java.text.ParseException; public interface GoTestEventsConverterBase { boolean processServiceMessages(@NotNull String text, Key outputType, ServiceMessageVisitor visitor) throws ParseException; } ================================================ FILE: src/com/goide/runconfig/testing/GoTestFinder.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.GoConstants; import com.goide.GoFileType; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.testIntegration.TestFinder; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; public class GoTestFinder implements TestFinder { private static final String EXTENSION = "." + GoFileType.INSTANCE.getDefaultExtension(); public static boolean isTestFile(@Nullable PsiFile file) { return file instanceof GoFile && file.getName().endsWith(GoConstants.TEST_SUFFIX_WITH_EXTENSION); } public static boolean isTestFile(@NotNull VirtualFile file) { return file.getName().endsWith(GoConstants.TEST_SUFFIX_WITH_EXTENSION); } public static boolean isTestOrExampleFunction(@NotNull GoFunctionOrMethodDeclaration function) { GoTestFunctionType type = GoTestFunctionType.fromName(function.getName()); return type == GoTestFunctionType.EXAMPLE || type == GoTestFunctionType.TEST; } public static boolean isBenchmarkFunction(@NotNull GoFunctionOrMethodDeclaration function) { GoTestFunctionType type = GoTestFunctionType.fromName(function.getName()); return type == GoTestFunctionType.BENCHMARK; } public static boolean isTestFileWithTestPackage(@Nullable PsiFile file) { return getTestTargetPackage(file) != null; } @Nullable public static String getTestTargetPackage(@Nullable PsiFile file) { if (isTestFile(file)) { String packageName = ((GoFile)file).getPackageName(); if (packageName != null && packageName.endsWith(GoConstants.TEST_SUFFIX)) { return StringUtil.nullize(StringUtil.trimEnd(packageName, GoConstants.TEST_SUFFIX)); } } return null; } @Nullable @Override public PsiElement findSourceElement(@NotNull PsiElement from) { return InjectedLanguageUtil.getTopLevelFile(from); } @NotNull @Override public Collection findTestsForClass(@NotNull PsiElement element) { PsiFile file = InjectedLanguageUtil.getTopLevelFile(element); if (file instanceof GoFile) { PsiDirectory directory = file.getContainingDirectory(); PsiFile testFile = directory.findFile(FileUtil.getNameWithoutExtension(file.getName()) + GoConstants.TEST_SUFFIX_WITH_EXTENSION); if (testFile != null) { return ContainerUtil.newSmartList(testFile); } } return Collections.emptyList(); } @NotNull @Override public Collection findClassesForTest(@NotNull PsiElement element) { PsiFile testFile = InjectedLanguageUtil.getTopLevelFile(element); if (testFile instanceof GoFile) { PsiDirectory directory = testFile.getContainingDirectory(); PsiFile sourceFile = directory.findFile(StringUtil.trimEnd(testFile.getName(), GoConstants.TEST_SUFFIX_WITH_EXTENSION) + EXTENSION); if (sourceFile != null) { return ContainerUtil.newSmartList(sourceFile); } } return Collections.emptyList(); } @Override public boolean isTest(@NotNull PsiElement element) { return isTestFile(InjectedLanguageUtil.getTopLevelFile(element)); } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestFramework.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.runconfig.testing.frameworks.gobench.GobenchFramework; import com.goide.runconfig.testing.frameworks.gocheck.GocheckFramework; import com.goide.runconfig.testing.frameworks.gotest.GotestFramework; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public abstract class GoTestFramework { private static class Lazy { private static final ArrayList ALL_FRAMEWORKS = ContainerUtil.newArrayList( GotestFramework.INSTANCE, GocheckFramework.INSTANCE, GobenchFramework.INSTANCE ); } public static List all() { return Lazy.ALL_FRAMEWORKS; } public Collection getGenerateMethodActions() { return Collections.emptyList(); } @NotNull public static GoTestFramework fromName(@Nullable String name) { for (GoTestFramework framework : all()) { if (framework.getName().equals(name)) { return framework; } } return GotestFramework.INSTANCE; } @NotNull public abstract String getName(); public abstract boolean isAvailable(@Nullable Module module); public abstract boolean isAvailableOnFile(@Nullable PsiFile file); public abstract boolean isAvailableOnFunction(@Nullable GoFunctionOrMethodDeclaration functionOrMethodDeclaration); @NotNull protected abstract GoTestRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration runConfiguration); @NotNull public abstract OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull TestConsoleProperties consoleProperties); } ================================================ FILE: src/com/goide/runconfig/testing/GoTestFunctionType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.GoConstants; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; public enum GoTestFunctionType { TEST(GoConstants.TEST_PREFIX, "T"), TEST_MAIN(GoConstants.TEST_PREFIX, "M"), BENCHMARK(GoConstants.BENCHMARK_PREFIX, "B"), EXAMPLE(GoConstants.EXAMPLE_PREFIX, null); private final String myPrefix; private final String myParamType; GoTestFunctionType(String prefix, String paramType) { myPrefix = prefix; myParamType = paramType; } @Nullable public String getParamType() { return myParamType; } @NotNull public String getPrefix() { return myPrefix; } @NotNull public String getQualifiedParamType(@Nullable String testingQualifier) { return myParamType != null ? "*" + GoPsiImplUtil.getFqn(testingQualifier, myParamType) : ""; } @NotNull public String getSignature(@Nullable String testingQualifier) { if (myParamType == null) { return ""; } return myParamType.toLowerCase(Locale.US) + " " + getQualifiedParamType(testingQualifier); } @Nullable public static GoTestFunctionType fromName(@Nullable String functionName) { if (StringUtil.isEmpty(functionName)) return null; if (GoConstants.TEST_MAIN.equals(functionName)) return TEST_MAIN; for (GoTestFunctionType type : values()) { if (checkPrefix(functionName, type.myPrefix)) return type; } return null; } private static boolean checkPrefix(@Nullable String name, @NotNull String prefix) { // https://github.com/golang/go/blob/master/src/cmd/go/test.go#L1161 – isTest() if (name == null || !name.startsWith(prefix)) return false; if (prefix.length() == name.length()) return true; char c = name.charAt(prefix.length()); return !Character.isLetter(c) || !Character.isLowerCase(c); } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestLocator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.psi.GoMethodDeclaration; import com.goide.psi.GoTypeSpec; import com.goide.stubs.index.GoFunctionIndex; import com.goide.stubs.index.GoIdFilter; import com.goide.stubs.index.GoTypesIndex; import com.intellij.execution.Location; import com.intellij.execution.PsiLocation; import com.intellij.execution.testframework.sm.runner.SMTestLocator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; public class GoTestLocator implements SMTestLocator { public static final String SUITE_PROTOCOL = "gosuite"; public static final String PROTOCOL = "gotest"; public static final SMTestLocator INSTANCE = new GoTestLocator(); private GoTestLocator() {} @NotNull @Override public List getLocation(@NotNull String protocolId, @NotNull String path, @NotNull Project project, @NotNull GlobalSearchScope scope) { if (PROTOCOL.equals(protocolId)) { IdFilter idFilter = GoIdFilter.getTestsFilter(project); List locationDataItems = StringUtil.split(path, "."); // Location is a function name, e.g. `TestCheckItOut` if (locationDataItems.size() == 1) { return ContainerUtil.mapNotNull(GoFunctionIndex.find(path, project, scope, idFilter), function -> PsiLocation.fromPsiElement(project, function)); } // Location is a method name, e.g. `FooSuite.TestCheckItOut` if (locationDataItems.size() == 2) { List locations = ContainerUtil.newArrayList(); for (GoTypeSpec typeSpec : GoTypesIndex.find(locationDataItems.get(0), project, scope, idFilter)) { for (GoMethodDeclaration method : typeSpec.getMethods()) { if (locationDataItems.get(1).equals(method.getName())) { ContainerUtil.addIfNotNull(locations, PsiLocation.fromPsiElement(method)); } } } return locations; } } else if (SUITE_PROTOCOL.equals(protocolId)) { IdFilter idFilter = GoIdFilter.getTestsFilter(project); return ContainerUtil.mapNotNull(GoTypesIndex.find(path, project, scope, idFilter), spec -> PsiLocation.fromPsiElement(project, spec)); } else { return Collections.emptyList(); } throw new RuntimeException("Unsupported location: " + path); } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestRunConfiguration.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.GoModuleBasedConfiguration; import com.goide.runconfig.GoRunConfigurationBase; import com.goide.runconfig.testing.frameworks.gotest.GotestFramework; import com.goide.runconfig.testing.ui.GoTestRunConfigurationEditorForm; import com.goide.sdk.GoPackageUtil; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import org.jdom.Element; import org.jetbrains.annotations.NotNull; public class GoTestRunConfiguration extends GoRunConfigurationBase { private static final String PATTERN_ATTRIBUTE_NAME = "pattern"; private static final String FILE_PATH_ATTRIBUTE_NAME = "filePath"; private static final String DIRECTORY_ATTRIBUTE_NAME = "directory"; private static final String PACKAGE_ATTRIBUTE_NAME = "package"; private static final String KIND_ATTRIBUTE_NAME = "kind"; private static final String FRAMEWORK_ATTRIBUTE_NAME = "framework"; @NotNull private String myPackage = ""; @NotNull private String myFilePath = ""; @NotNull private String myDirectoryPath = ""; @NotNull private String myPattern = ""; @NotNull private Kind myKind = Kind.DIRECTORY; private GoTestFramework myTestFramework = GotestFramework.INSTANCE; public GoTestRunConfiguration(@NotNull Project project, String name, @NotNull ConfigurationType configurationType) { super(name, new GoModuleBasedConfiguration(project), configurationType.getConfigurationFactories()[0]); } public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull TestConsoleProperties consoleProperties) { return myTestFramework.createTestEventsConverter(consoleProperties); } @NotNull @Override protected GoTestRunningState newRunningState(ExecutionEnvironment env, Module module) { return myTestFramework.newRunningState(env, module, this); } @Override protected ModuleBasedConfiguration createInstance() { return new GoTestRunConfiguration(getProject(), getName(), GoTestRunConfigurationType.getInstance()); } @NotNull @Override public SettingsEditor getConfigurationEditor() { return new GoTestRunConfigurationEditorForm(getProject()); } @Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); GoModuleBasedConfiguration configurationModule = getConfigurationModule(); if (!myTestFramework.isAvailable(configurationModule.getModule())) { throw new RuntimeConfigurationError("Framework `" + myTestFramework.getName() + "` is not available in selected module"); } switch (myKind) { case DIRECTORY: String directoryPath = FileUtil.isAbsolutePlatformIndependent(myDirectoryPath) ? myDirectoryPath : FileUtil.join(getWorkingDirectory(), myDirectoryPath); if (!FileUtil.isAncestor(getWorkingDirectory(), directoryPath, false)) { throw new RuntimeConfigurationError("Working directory should be ancestor of testing directory"); } VirtualFile testingDirectory = LocalFileSystem.getInstance().findFileByPath(directoryPath); if (testingDirectory == null) { throw new RuntimeConfigurationError("Testing directory doesn't exist"); } break; case PACKAGE: Module module = configurationModule.getModule(); assert module != null; VirtualFile packageDirectory = GoPackageUtil.findByImportPath(myPackage, module.getProject(), module); if (packageDirectory == null || !packageDirectory.isDirectory()) { throw new RuntimeConfigurationError("Cannot find package '" + myPackage + "'"); } for (VirtualFile file : packageDirectory.getChildren()) { PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(file); if (psiFile != null && myTestFramework.isAvailableOnFile(psiFile)) { return; } } String message = "Cannot find Go test files in '" + myPackage + "' compatible with `" + myTestFramework.getName() + "` framework"; throw new RuntimeConfigurationError(message); case FILE: VirtualFile virtualFile = findFile(getFilePath()); if (virtualFile == null) { throw new RuntimeConfigurationError("Test file doesn't exist"); } PsiFile file = PsiManager.getInstance(getProject()).findFile(virtualFile); if (file == null || !myTestFramework.isAvailableOnFile(file)) { message = "Framework `" + myTestFramework.getName() + "` is not available on file `" + myFilePath + "`"; throw new RuntimeConfigurationError(message); } break; } } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); JDOMExternalizerUtil.addElementWithValueAttribute(element, FRAMEWORK_ATTRIBUTE_NAME, myTestFramework.getName()); JDOMExternalizerUtil.addElementWithValueAttribute(element, KIND_ATTRIBUTE_NAME, myKind.name()); if (!myPackage.isEmpty()) { JDOMExternalizerUtil.addElementWithValueAttribute(element, PACKAGE_ATTRIBUTE_NAME, myPackage); } if (!myDirectoryPath.isEmpty()) { JDOMExternalizerUtil.addElementWithValueAttribute(element, DIRECTORY_ATTRIBUTE_NAME, myDirectoryPath); } if (!myFilePath.isEmpty()) { JDOMExternalizerUtil.addElementWithValueAttribute(element, FILE_PATH_ATTRIBUTE_NAME, myFilePath); } if (!myPattern.isEmpty()) { JDOMExternalizerUtil.addElementWithValueAttribute(element, PATTERN_ATTRIBUTE_NAME, myPattern); } } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); try { String kindName = JDOMExternalizerUtil.getFirstChildValueAttribute(element, KIND_ATTRIBUTE_NAME); myKind = kindName != null ? Kind.valueOf(kindName) : Kind.DIRECTORY; } catch (IllegalArgumentException e) { myKind = Kind.DIRECTORY; } myPackage = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, PACKAGE_ATTRIBUTE_NAME)); myDirectoryPath = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, DIRECTORY_ATTRIBUTE_NAME)); myFilePath = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, FILE_PATH_ATTRIBUTE_NAME)); myPattern = StringUtil.notNullize(JDOMExternalizerUtil.getFirstChildValueAttribute(element, PATTERN_ATTRIBUTE_NAME)); myTestFramework = GoTestFramework.fromName(JDOMExternalizerUtil.getFirstChildValueAttribute(element, FRAMEWORK_ATTRIBUTE_NAME)); } @NotNull public String getPattern() { return myPattern; } public void setPattern(@NotNull String pattern) { myPattern = pattern; } @NotNull public Kind getKind() { return myKind; } public void setKind(@NotNull Kind kind) { myKind = kind; } @NotNull public String getPackage() { return myPackage; } public void setPackage(@NotNull String aPackage) { myPackage = aPackage; } @NotNull public String getFilePath() { return myFilePath; } public void setFilePath(@NotNull String filePath) { myFilePath = filePath; } @NotNull public String getDirectoryPath() { return myDirectoryPath; } public void setDirectoryPath(@NotNull String directoryPath) { myDirectoryPath = directoryPath; } public void setTestFramework(@NotNull GoTestFramework testFramework) { myTestFramework = testFramework; } @NotNull public GoTestFramework getTestFramework() { return myTestFramework; } public enum Kind { DIRECTORY, PACKAGE, FILE } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestRunConfigurationProducerBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoMethodDeclaration; import com.goide.runconfig.GoRunUtil; import com.goide.sdk.GoSdkService; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class GoTestRunConfigurationProducerBase extends RunConfigurationProducer { @NotNull private final GoTestFramework myFramework; protected GoTestRunConfigurationProducerBase(@NotNull GoTestFramework framework) { super(GoTestRunConfigurationType.getInstance()); myFramework = framework; } @Override protected boolean setupConfigurationFromContext(@NotNull GoTestRunConfiguration configuration, ConfigurationContext context, Ref sourceElement) { PsiElement contextElement = GoRunUtil.getContextElement(context); if (contextElement == null) { return false; } Module module = ModuleUtilCore.findModuleForPsiElement(contextElement); Project project = contextElement.getProject(); if (module == null || !GoSdkService.getInstance(project).isGoModule(module)) return false; if (!myFramework.isAvailable(module)) return false; configuration.setModule(module); configuration.setTestFramework(myFramework); if (contextElement instanceof PsiDirectory) { configuration.setName(getPackageConfigurationName(((PsiDirectory)contextElement).getName())); configuration.setKind(GoTestRunConfiguration.Kind.DIRECTORY); String directoryPath = ((PsiDirectory)contextElement).getVirtualFile().getPath(); configuration.setDirectoryPath(directoryPath); configuration.setWorkingDirectory(directoryPath); return true; } PsiFile file = contextElement.getContainingFile(); if (myFramework.isAvailableOnFile(file)) { String importPath = ((GoFile)file).getImportPath(false); if (GoRunUtil.isPackageContext(contextElement) && StringUtil.isNotEmpty(importPath)) { configuration.setKind(GoTestRunConfiguration.Kind.PACKAGE); configuration.setPackage(importPath); configuration.setName(getPackageConfigurationName(importPath)); return true; } else { GoFunctionOrMethodDeclaration function = findTestFunctionInContext(contextElement); if (function != null) { if (myFramework.isAvailableOnFunction(function)) { configuration.setName(getFunctionConfigurationName(function, file.getName())); configuration.setPattern("^" + function.getName() + "$"); configuration.setKind(GoTestRunConfiguration.Kind.PACKAGE); configuration.setPackage(StringUtil.notNullize(((GoFile)file).getImportPath(false))); return true; } } else if (hasSupportedFunctions((GoFile)file)) { configuration.setName(getFileConfigurationName(file.getName())); configuration.setKind(GoTestRunConfiguration.Kind.FILE); configuration.setFilePath(file.getVirtualFile().getPath()); return true; } } } return false; } private boolean hasSupportedFunctions(@NotNull GoFile file) { for (GoFunctionDeclaration declaration : file.getFunctions()) { if (myFramework.isAvailableOnFunction(declaration)) { return true; } } for (GoMethodDeclaration declaration : file.getMethods()) { if (myFramework.isAvailableOnFunction(declaration)) { return true; } } return false; } @NotNull protected String getFileConfigurationName(@NotNull String fileName) { return fileName; } @NotNull protected String getFunctionConfigurationName(@NotNull GoFunctionOrMethodDeclaration function, @NotNull String fileName) { return function.getName() + " in " + fileName; } @NotNull protected String getPackageConfigurationName(@NotNull String packageName) { return "All in '" + packageName + "'"; } @Override public boolean isConfigurationFromContext(@NotNull GoTestRunConfiguration configuration, ConfigurationContext context) { PsiElement contextElement = GoRunUtil.getContextElement(context); if (contextElement == null) return false; Module module = ModuleUtilCore.findModuleForPsiElement(contextElement); if (!Comparing.equal(module, configuration.getConfigurationModule().getModule())) return false; if (!Comparing.equal(myFramework, configuration.getTestFramework())) return false; PsiFile file = contextElement.getContainingFile(); switch (configuration.getKind()) { case DIRECTORY: if (contextElement instanceof PsiDirectory) { String directoryPath = ((PsiDirectory)contextElement).getVirtualFile().getPath(); return FileUtil.pathsEqual(configuration.getDirectoryPath(), directoryPath) && FileUtil.pathsEqual(configuration.getWorkingDirectory(), directoryPath); } case PACKAGE: if (!GoTestFinder.isTestFile(file)) return false; if (!Comparing.equal(((GoFile)file).getImportPath(false), configuration.getPackage())) return false; if (GoRunUtil.isPackageContext(contextElement) && configuration.getPattern().isEmpty()) return true; GoFunctionOrMethodDeclaration contextFunction = findTestFunctionInContext(contextElement); return contextFunction != null && myFramework.isAvailableOnFunction(contextFunction) ? configuration.getPattern().equals("^" + contextFunction.getName() + "$") : configuration.getPattern().isEmpty(); case FILE: GoFunctionOrMethodDeclaration contextTestFunction = findTestFunctionInContext(contextElement); return contextTestFunction == null && GoTestFinder.isTestFile(file) && FileUtil.pathsEqual(configuration.getFilePath(), file.getVirtualFile().getPath()); } return false; } @Nullable private static GoFunctionOrMethodDeclaration findTestFunctionInContext(@NotNull PsiElement contextElement) { GoFunctionOrMethodDeclaration function = PsiTreeUtil.getNonStrictParentOfType(contextElement, GoFunctionOrMethodDeclaration.class); return function != null && GoTestFunctionType.fromName(function.getName()) != null ? function : null; } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestRunConfigurationType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.GoIcons; import com.intellij.execution.configurations.ConfigurationTypeBase; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; public class GoTestRunConfigurationType extends ConfigurationTypeBase { public GoTestRunConfigurationType() { super("GoTestRunConfiguration", "Go Test", "Go test run configuration", GoIcons.TEST_RUN); addFactory(new GoTestConfigurationFactoryBase(this) { @Override @NotNull public RunConfiguration createTemplateConfiguration(@NotNull Project project) { return new GoTestRunConfiguration(project, "Go Test", getInstance()); } }); } @NotNull public static GoTestRunConfigurationType getInstance() { return Extensions.findExtension(CONFIGURATION_TYPE_EP, GoTestRunConfigurationType.class); } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestRunLineMarkerProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.GoTypes; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoMethodDeclaration; import com.goide.psi.GoReceiver; import com.goide.runconfig.GoRunUtil; import com.intellij.execution.TestStateStorage; import com.intellij.execution.lineMarker.ExecutorAction; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.execution.testframework.TestIconMapper; import com.intellij.execution.testframework.sm.runner.states.TestStateInfo; import com.intellij.icons.AllIcons; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoTestRunLineMarkerProvider extends RunLineMarkerContributor { private static final Function TOOLTIP_PROVIDER = element -> "Run Test"; @Nullable @Override public Info getInfo(PsiElement e) { if (e != null && e.getNode().getElementType() == GoTypes.IDENTIFIER) { PsiElement parent = e.getParent(); PsiFile file = e.getContainingFile(); if (!GoTestFinder.isTestFile(file)) { return null; } if (GoRunUtil.isPackageContext(e)) { return new Info(AllIcons.RunConfigurations.TestState.Run_run, TOOLTIP_PROVIDER, ExecutorAction.getActions(0)); } else if (parent instanceof GoFunctionOrMethodDeclaration) { GoTestFunctionType functionType = GoTestFunctionType.fromName(((GoFunctionOrMethodDeclaration)parent).getName()); if (functionType != null) { if (parent instanceof GoFunctionDeclaration) { return getInfo(GoTestLocator.PROTOCOL + "://" + ((GoFunctionDeclaration)parent).getName(), e.getProject()); } else if (parent instanceof GoMethodDeclaration) { GoReceiver receiver = ((GoMethodDeclaration)parent).getReceiver(); PsiElement receiverIdentifier = receiver != null ? receiver.getIdentifier() : null; String receiverText = receiverIdentifier != null ? receiverIdentifier.getText() + "." : ""; return getInfo(GoTestLocator.PROTOCOL + "://" + receiverText + ((GoMethodDeclaration)parent).getName(), e.getProject()); } } } } return null; } @NotNull private static Info getInfo(String url, Project project) { Icon icon = getTestStateIcon(url, project); return new Info(icon, TOOLTIP_PROVIDER, ExecutorAction.getActions(0)); } private static Icon getTestStateIcon(@NotNull String url, @NotNull Project project) { TestStateStorage.Record state = TestStateStorage.getInstance(project).getState(url); if (state != null) { TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude); if (magnitude != null) { switch (magnitude) { case ERROR_INDEX: case FAILED_INDEX: return AllIcons.RunConfigurations.TestState.Red2; case PASSED_INDEX: case COMPLETE_INDEX: return AllIcons.RunConfigurations.TestState.Green2; default: } } } return AllIcons.RunConfigurations.TestState.Run; } } ================================================ FILE: src/com/goide/runconfig/testing/GoTestRunningState.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionDeclaration; import com.goide.runconfig.GoConsoleFilter; import com.goide.runconfig.GoRunningState; import com.goide.util.GoExecutor; import com.intellij.execution.DefaultExecutionResult; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.Executor; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.ProgramRunner; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.actions.AbstractRerunFailedTestsAction; import com.intellij.execution.testframework.autotest.ToggleAutoTestAction; import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil; import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView; import com.intellij.execution.ui.ConsoleView; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collection; import java.util.List; public class GoTestRunningState extends GoRunningState { private String myCoverageFilePath; private String myFailedTestsPattern; public GoTestRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration configuration) { super(env, module, configuration); } @NotNull @Override public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunner runner) throws ExecutionException { ProcessHandler processHandler = startProcess(); TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(myConfiguration.getProject()); setConsoleBuilder(consoleBuilder); GoTestConsoleProperties consoleProperties = new GoTestConsoleProperties(myConfiguration, executor); String frameworkName = myConfiguration.getTestFramework().getName(); ConsoleView consoleView = SMTestRunnerConnectionUtil.createAndAttachConsole(frameworkName, processHandler, consoleProperties); consoleView.addMessageFilter(new GoConsoleFilter(myConfiguration.getProject(), myModule, myConfiguration.getWorkingDirectoryUrl())); ProcessTerminatedListener.attach(processHandler); DefaultExecutionResult executionResult = new DefaultExecutionResult(consoleView, processHandler); AbstractRerunFailedTestsAction rerunFailedTestsAction = consoleProperties.createRerunFailedTestsAction(consoleView); if (rerunFailedTestsAction != null) { rerunFailedTestsAction.setModelProvider(((SMTRunnerConsoleView)consoleView)::getResultsViewer); executionResult.setRestartActions(rerunFailedTestsAction, new ToggleAutoTestAction()); } else { executionResult.setRestartActions(new ToggleAutoTestAction()); } return executionResult; } @Override protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { executor.withParameters("test", "-v"); executor.withParameterString(myConfiguration.getGoToolParams()); switch (myConfiguration.getKind()) { case DIRECTORY: String relativePath = FileUtil.getRelativePath(myConfiguration.getWorkingDirectory(), myConfiguration.getDirectoryPath(), File.separatorChar); // TODO Once Go gets support for covering multiple packages the ternary condition should be reverted // See https://golang.org/issues/6909 String pathSuffix = myCoverageFilePath == null ? "..." : "."; if (relativePath != null && !".".equals(relativePath)) { executor.withParameters("./" + relativePath + "/" + pathSuffix); } else { executor.withParameters("./" + pathSuffix); executor.withWorkDirectory(myConfiguration.getDirectoryPath()); } addFilterParameter(executor, ObjectUtils.notNull(myFailedTestsPattern, myConfiguration.getPattern())); break; case PACKAGE: executor.withParameters(myConfiguration.getPackage()); addFilterParameter(executor, ObjectUtils.notNull(myFailedTestsPattern, myConfiguration.getPattern())); break; case FILE: String filePath = myConfiguration.getFilePath(); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath); if (virtualFile == null) { throw new ExecutionException("Test file doesn't exist"); } PsiFile file = PsiManager.getInstance(myConfiguration.getProject()).findFile(virtualFile); if (file == null || !GoTestFinder.isTestFile(file)) { throw new ExecutionException("File '" + filePath + "' is not test file"); } String importPath = ((GoFile)file).getImportPath(false); if (StringUtil.isEmpty(importPath)) { throw new ExecutionException("Cannot find import path for " + filePath); } executor.withParameters(importPath); addFilterParameter(executor, myFailedTestsPattern != null ? myFailedTestsPattern : buildFilterPatternForFile((GoFile)file)); break; } if (myCoverageFilePath != null) { executor.withParameters("-coverprofile=" + myCoverageFilePath, "-covermode=atomic"); } return executor; } @NotNull protected String buildFilterPatternForFile(GoFile file) { Collection testNames = ContainerUtil.newLinkedHashSet(); for (GoFunctionDeclaration function : file.getFunctions()) { ContainerUtil.addIfNotNull(testNames, GoTestFinder.isTestOrExampleFunction(function) ? function.getName() : null); } return "^" + StringUtil.join(testNames, "|") + "$"; } protected void addFilterParameter(@NotNull GoExecutor executor, String pattern) { if (StringUtil.isNotEmpty(pattern)) { executor.withParameters("-run", pattern); } } public void setCoverageFilePath(@Nullable String coverageFile) { myCoverageFilePath = coverageFile; } public void setFailedTests(@NotNull List failedTests) { myFailedTestsPattern = "^" + StringUtil.join(failedTests, AbstractTestProxy::getName, "|") + "$"; } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageAnnotator.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.intellij.coverage.BaseCoverageAnnotator; import com.intellij.coverage.CoverageDataManager; import com.intellij.coverage.CoverageSuite; import com.intellij.coverage.CoverageSuitesBundle; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.progress.ProgressIndicatorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Factory; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiFile; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import java.util.Map; public class GoCoverageAnnotator extends BaseCoverageAnnotator { private static final String STATEMENTS_SUFFIX = "% statements"; private static final String FILES_SUFFIX = "% files"; private final Map myFileCoverageInfos = ContainerUtil.newHashMap(); private final Map myDirCoverageInfos = ContainerUtil.newHashMap(); public GoCoverageAnnotator(@NotNull Project project) { super(project); } public static GoCoverageAnnotator getInstance(Project project) { return ServiceManager.getService(project, GoCoverageAnnotator.class); } @Nullable @Override public String getDirCoverageInformationString(@NotNull PsiDirectory directory, @NotNull CoverageSuitesBundle bundle, @NotNull CoverageDataManager manager) { DirCoverageInfo dirCoverageInfo = myDirCoverageInfos.get(directory.getVirtualFile().getPath()); if (dirCoverageInfo == null) { return null; } if (manager.isSubCoverageActive()) { return dirCoverageInfo.coveredLineCount > 0 ? "covered" : null; } return getDirCoverageString(dirCoverageInfo); } @Nullable private static String getDirCoverageString(@NotNull DirCoverageInfo dirCoverageInfo) { String filesCoverageInfo = getFilesCoverageString(dirCoverageInfo); if (filesCoverageInfo != null) { StringBuilder builder = new StringBuilder(); builder.append(filesCoverageInfo); String statementsCoverageInfo = getStatementsCoverageString(dirCoverageInfo); if (statementsCoverageInfo != null) { builder.append(", ").append(statementsCoverageInfo); } return builder.toString(); } return null; } @Nullable @TestOnly public String getDirCoverageInformationString(@NotNull VirtualFile file) { DirCoverageInfo coverageInfo = myDirCoverageInfos.get(file.getPath()); return coverageInfo != null ? getDirCoverageString(coverageInfo) : null; } @Nullable @Override public String getFileCoverageInformationString(@NotNull PsiFile file, @NotNull CoverageSuitesBundle bundle, @NotNull CoverageDataManager manager) { FileCoverageInfo coverageInfo = myFileCoverageInfos.get(file.getVirtualFile().getPath()); if (coverageInfo == null) { return null; } if (manager.isSubCoverageActive()) { return coverageInfo.coveredLineCount > 0 ? "covered" : null; } return getStatementsCoverageString(coverageInfo); } @Nullable @TestOnly public String getFileCoverageInformationString(@NotNull VirtualFile file) { FileCoverageInfo coverageInfo = myFileCoverageInfos.get(file.getPath()); return coverageInfo != null ? getStatementsCoverageString(coverageInfo) : null; } @Override public void onSuiteChosen(CoverageSuitesBundle newSuite) { super.onSuiteChosen(newSuite); myFileCoverageInfos.clear(); myDirCoverageInfos.clear(); } @Nullable @Override protected Runnable createRenewRequest(@NotNull CoverageSuitesBundle bundle, @NotNull CoverageDataManager manager) { GoCoverageProjectData data = new GoCoverageProjectData(); for (CoverageSuite suite : bundle.getSuites()) { ProjectData toMerge = suite.getCoverageData(manager); if (toMerge != null) { data.merge(toMerge); } } return () -> { annotateAllFiles(data, manager.doInReadActionIfProjectOpen(() -> ProjectRootManager.getInstance(getProject()).getContentRoots())); manager.triggerPresentationUpdate(); }; } @NotNull private DirCoverageInfo getOrCreateDirectoryInfo(VirtualFile file) { return ContainerUtil.getOrCreate(myDirCoverageInfos, file.getPath(), new Factory() { @Override public DirCoverageInfo create() { return new DirCoverageInfo(); } }); } @NotNull private FileCoverageInfo getOrCreateFileInfo(VirtualFile file) { return ContainerUtil.getOrCreate(myFileCoverageInfos, file.getPath(), new Factory() { @Override public FileCoverageInfo create() { return new FileCoverageInfo(); } }); } @Nullable private static String getStatementsCoverageString(@NotNull FileCoverageInfo info) { double percent = calcPercent(info.coveredLineCount, info.totalLineCount); return info.totalLineCount > 0 ? new DecimalFormat("##.#" + STATEMENTS_SUFFIX, DecimalFormatSymbols.getInstance(Locale.US)) .format(percent) : null; } @Nullable private static String getFilesCoverageString(@NotNull DirCoverageInfo info) { double percent = calcPercent(info.coveredFilesCount, info.totalFilesCount); return info.totalFilesCount > 0 ? new DecimalFormat("##.#" + FILES_SUFFIX, DecimalFormatSymbols.getInstance(Locale.US)).format(percent) : null; } private static double calcPercent(int covered, int total) { return total != 0 ? (double)covered / total : 0; } public void annotateAllFiles(@NotNull GoCoverageProjectData data, @Nullable VirtualFile... contentRoots) { if (contentRoots != null) { for (VirtualFile root : contentRoots) { VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() { @NotNull @Override public Result visitFileEx(@NotNull VirtualFile file) { ProgressIndicatorProvider.checkCanceled(); if (file.isDirectory() && !FileIndexFacade.getInstance(getProject()).isInContent(file)) { return SKIP_CHILDREN; } if (!file.isDirectory() && GoCoverageEngine.INSTANCE.coverageProjectViewStatisticsApplicableTo(file)) { DirCoverageInfo dirCoverageInfo = getOrCreateDirectoryInfo(file.getParent()); FileCoverageInfo fileCoverageInfo = getOrCreateFileInfo(file); data.processFile(file.getPath(), rangeData -> { if (rangeData.hits > 0) { fileCoverageInfo.coveredLineCount += rangeData.statements; } fileCoverageInfo.totalLineCount += rangeData.statements; return true; }); if (fileCoverageInfo.totalLineCount > 0) { dirCoverageInfo.totalLineCount += fileCoverageInfo.totalLineCount; dirCoverageInfo.totalFilesCount++; } if (fileCoverageInfo.coveredLineCount > 0) { dirCoverageInfo.coveredLineCount += fileCoverageInfo.coveredLineCount; dirCoverageInfo.coveredFilesCount++; } } return CONTINUE; } @Override public void afterChildrenVisited(@NotNull VirtualFile file) { if (file.isDirectory()) { DirCoverageInfo currentCoverageInfo = getOrCreateDirectoryInfo(file); DirCoverageInfo parentCoverageInfo = getOrCreateDirectoryInfo(file.getParent()); parentCoverageInfo.totalFilesCount += currentCoverageInfo.totalFilesCount; parentCoverageInfo.coveredFilesCount += currentCoverageInfo.coveredFilesCount; parentCoverageInfo.totalLineCount += currentCoverageInfo.totalLineCount; parentCoverageInfo.coveredLineCount += currentCoverageInfo.coveredLineCount; } } }); } } } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageEnabledConfiguration.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.intellij.coverage.CoverageRunner; import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration; public class GoCoverageEnabledConfiguration extends CoverageEnabledConfiguration { public GoCoverageEnabledConfiguration(GoTestRunConfiguration configuration) { super(configuration); setCoverageRunner(CoverageRunner.getInstance(GoCoverageRunner.class)); } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageEngine.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.goide.GoFileType; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.intellij.coverage.*; import com.intellij.coverage.view.CoverageViewExtension; import com.intellij.coverage.view.CoverageViewManager; import com.intellij.coverage.view.DirectoryCoverageViewExtension; import com.intellij.execution.configurations.RunConfigurationBase; import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; public class GoCoverageEngine extends CoverageEngine { private static final Condition NODE_TO_COVERAGE = node -> { Object value = node.getValue(); if (value instanceof PsiFile) { return isProductionGoFile((PsiFile)value); } return !StringUtil.equals(node.getName(), Project.DIRECTORY_STORE_FOLDER); }; public static final GoCoverageEngine INSTANCE = new GoCoverageEngine(); private static final String PRESENTABLE_TEXT = "Go Coverage"; @Override public boolean isApplicableTo(@Nullable RunConfigurationBase conf) { return conf instanceof GoTestRunConfiguration; } @Override public boolean canHavePerTestCoverage(@Nullable RunConfigurationBase conf) { return false; } @NotNull @Override public CoverageEnabledConfiguration createCoverageEnabledConfiguration(@Nullable RunConfigurationBase conf) { return new GoCoverageEnabledConfiguration((GoTestRunConfiguration)conf); } @Override public CoverageSuite createCoverageSuite(@NotNull CoverageRunner runner, @NotNull String name, @NotNull CoverageFileProvider coverageDataFileProvider, @Nullable String[] filters, long lastCoverageTimeStamp, @Nullable String suiteToMerge, boolean coverageByTestEnabled, boolean tracingEnabled, boolean trackTestFolders, Project project) { return new GoCoverageSuite(name, coverageDataFileProvider, lastCoverageTimeStamp, runner, project); } @Override public CoverageSuite createCoverageSuite(@NotNull CoverageRunner runner, @NotNull String name, @NotNull CoverageFileProvider coverageDataFileProvider, @NotNull CoverageEnabledConfiguration config) { if (config instanceof GoCoverageEnabledConfiguration) { return new GoCoverageSuite(name, coverageDataFileProvider, new Date().getTime(), runner, config.getConfiguration().getProject()); } return null; } @Override public CoverageSuite createEmptyCoverageSuite(@NotNull CoverageRunner coverageRunner) { return new GoCoverageSuite(); } @NotNull @Override public CoverageAnnotator getCoverageAnnotator(Project project) { return GoCoverageAnnotator.getInstance(project); } @Override public boolean coverageEditorHighlightingApplicableTo(@NotNull PsiFile psiFile) { return isProductionGoFile(psiFile); } @Override public boolean acceptedByFilters(@NotNull PsiFile psiFile, @NotNull CoverageSuitesBundle suite) { return isProductionGoFile(psiFile); } private static boolean isProductionGoFile(@NotNull PsiFile psiFile) { return psiFile.getFileType() == GoFileType.INSTANCE && !GoTestFinder.isTestFile(psiFile); } @Override public boolean recompileProjectAndRerunAction(@NotNull Module module, @NotNull CoverageSuitesBundle suite, @NotNull Runnable chooseSuiteAction) { return false; } @Override public String getQualifiedName(@NotNull File outputFile, @NotNull PsiFile sourceFile) { return sourceFile.getVirtualFile().getPath(); } @NotNull @Override public Set getQualifiedNames(@NotNull PsiFile sourceFile) { return Collections.singleton(sourceFile.getVirtualFile().getPath()); } @Override public boolean includeUntouchedFileInCoverage(@NotNull String qualifiedName, @NotNull File outputFile, @NotNull PsiFile sourceFile, @NotNull CoverageSuitesBundle suite) { return false; } @Override public List collectSrcLinesForUntouchedFile(@NotNull File classFile, @NotNull CoverageSuitesBundle suite) { return null; } @Override public List findTestsByNames(@NotNull String[] testNames, @NotNull Project project) { return Collections.emptyList(); } @Override public String getTestMethodName(@NotNull PsiElement element, @NotNull AbstractTestProxy testProxy) { return null; } @Override public String getPresentableText() { return PRESENTABLE_TEXT; } @Override public boolean coverageProjectViewStatisticsApplicableTo(VirtualFile fileOrDir) { return !fileOrDir.isDirectory() && fileOrDir.getFileType() == GoFileType.INSTANCE && !GoTestFinder.isTestFile(fileOrDir); } @Override public CoverageViewExtension createCoverageViewExtension(Project project, CoverageSuitesBundle suiteBundle, CoverageViewManager.StateBean stateBean) { return new DirectoryCoverageViewExtension(project, getCoverageAnnotator(project), suiteBundle, stateBean) { @Override public List getChildrenNodes(AbstractTreeNode node) { return ContainerUtil.filter(super.getChildrenNodes(node), NODE_TO_COVERAGE); } }; } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageProgramRunner.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.goide.runconfig.testing.GoTestRunningState; import com.intellij.coverage.CoverageExecutor; import com.intellij.coverage.CoverageHelper; import com.intellij.coverage.CoverageRunnerData; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.configurations.ConfigurationInfoProvider; import com.intellij.execution.configurations.RunProfile; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.configurations.RunnerSettings; import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.GenericProgramRunner; import com.intellij.execution.runners.RunContentBuilder; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoCoverageProgramRunner extends GenericProgramRunner { private static final String ID = "GoCoverageProgramRunner"; @NotNull @Override public String getRunnerId() { return ID; } @Override public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { return executorId.equals(CoverageExecutor.EXECUTOR_ID) && profile instanceof GoTestRunConfiguration; } @Override public RunnerSettings createConfigurationData(ConfigurationInfoProvider settingsProvider) { return new CoverageRunnerData(); } @Nullable @Override protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment environment) throws ExecutionException { assert state instanceof GoTestRunningState; GoTestRunningState runningState = (GoTestRunningState)state; GoTestRunConfiguration runConfiguration = ObjectUtils.tryCast(environment.getRunProfile(), GoTestRunConfiguration.class); if (runConfiguration == null) { return null; } FileDocumentManager.getInstance().saveAllDocuments(); CoverageEnabledConfiguration coverageEnabledConfiguration = CoverageEnabledConfiguration.getOrCreate(runConfiguration); runningState.setCoverageFilePath(coverageEnabledConfiguration.getCoverageFilePath()); ExecutionResult executionResult = state.execute(environment.getExecutor(), this); if (executionResult == null) { return null; } CoverageHelper.attachToProcess(runConfiguration, executionResult.getProcessHandler(), environment.getRunnerSettings()); return new RunContentBuilder(executionResult, environment).showRunContent(environment.getContentToReuse()); } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageProjectData.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.intellij.openapi.util.Factory; import com.intellij.rt.coverage.data.CoverageData; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Map; public class GoCoverageProjectData extends ProjectData { @NotNull private final Map myFilesData = ContainerUtil.newHashMap(); public void processFiles(@NotNull Processor processor) { for (FileData fileData : myFilesData.values()) { if (!processor.process(fileData)) { return; } } } public void processFile(@NotNull String filePath, @NotNull Processor processor) { FileData fileData = myFilesData.get(filePath); if (fileData != null) { for (RangeData rangeData : fileData.myRangesData.values()) { if (!processor.process(rangeData)) { return; } } } } public void addData(String filePath, int startLine, int startColumn, int endLine, int endColumn, int statements, int hits) { FileData fileData = ContainerUtil.getOrCreate(myFilesData, filePath, new Factory() { @Override public FileData create() { return new FileData(filePath); } }); fileData.add(startLine, startColumn, endLine, endColumn, statements, hits); } @Override public void merge(CoverageData data) { super.merge(data); if (data instanceof GoCoverageProjectData) { for (Map.Entry entry : ((GoCoverageProjectData)data).myFilesData.entrySet()) { String filePath = entry.getKey(); FileData fileData = myFilesData.get(filePath); FileData fileDataToMerge = entry.getValue(); if (fileData != null) { for (Map.Entry dataEntry : fileDataToMerge.myRangesData.entrySet()) { RangeData existingRangeData = fileData.myRangesData.get(dataEntry.getKey()); if (existingRangeData != null) { fileData.myRangesData.put(dataEntry.getKey(), new RangeData(existingRangeData.startLine, existingRangeData.startColumn, existingRangeData.endLine, existingRangeData.endColumn, existingRangeData.statements, existingRangeData.hits + dataEntry.getValue().hits)); } else { fileData.myRangesData.put(dataEntry.getKey(), dataEntry.getValue()); } } } else { myFilesData.put(filePath, fileDataToMerge); } } } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof GoCoverageProjectData)) return false; GoCoverageProjectData data = (GoCoverageProjectData)o; return myFilesData.equals(data.myFilesData); } @Override public int hashCode() { return myFilesData.hashCode(); } public static class FileData { @NotNull public final String myFilePath; @NotNull public final Map myRangesData = ContainerUtil.newHashMap(); public FileData(@NotNull String filePath) { myFilePath = filePath; } public void add(int startLine, int startColumn, int endLine, int endColumn, int statements, int hits) { myRangesData.put(rangeKey(startLine, startColumn, endLine, endColumn), new RangeData(startLine, startColumn, endLine, endColumn, statements, hits)); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FileData)) return false; FileData fileData = (FileData)o; if (!myFilePath.equals(fileData.myFilePath)) return false; return myRangesData.equals(fileData.myRangesData); } @Override public int hashCode() { int result = myFilePath.hashCode(); result = 31 * result + myRangesData.hashCode(); return result; } } public static class RangeData { public final int startLine; public final int startColumn; public final int endLine; public final int endColumn; public final int hits; public final int statements; public RangeData(int startLine, int startColumn, int endLine, int endColumn, int statements, int hits) { this.startLine = startLine; this.startColumn = startColumn; this.endLine = endLine; this.endColumn = endColumn; this.hits = hits; this.statements = statements; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RangeData)) return false; RangeData data = (RangeData)o; if (startLine != data.startLine) return false; if (startColumn != data.startColumn) return false; if (endLine != data.endLine) return false; if (endColumn != data.endColumn) return false; if (hits != data.hits) return false; return statements == data.statements; } @Override public int hashCode() { int result = startLine; result = 31 * result + startColumn; result = 31 * result + endLine; result = 31 * result + endColumn; result = 31 * result + hits; result = 31 * result + statements; return result; } @Override public String toString() { return rangeKey(startLine, startColumn, endLine, endColumn) + "; hits: " + hits + "; statements: " + statements; } } private static String rangeKey(int startLine, int startColumn, int endLine, int endColumn) { return startLine + ":" + startColumn + "-" + endLine + ":" + endColumn; } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageRunner.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.goide.GoConstants; import com.goide.sdk.GoPackageUtil; import com.intellij.coverage.BaseCoverageSuite; import com.intellij.coverage.CoverageEngine; import com.intellij.coverage.CoverageRunner; import com.intellij.coverage.CoverageSuite; import com.intellij.execution.configurations.ModuleBasedConfiguration; import com.intellij.execution.configurations.RunConfigurationBase; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import gnu.trove.TIntObjectHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.List; public class GoCoverageRunner extends CoverageRunner { private static final Logger LOG = Logger.getInstance(GoCoverageRunner.class); private static final String ID = "GoCoverage"; private static final String DATA_FILE_EXTENSION = "out"; private static final String PRESENTABLE_NAME = GoConstants.GO; @Override public ProjectData loadCoverageData(@NotNull File sessionDataFile, @Nullable CoverageSuite baseCoverageSuite) { if (!(baseCoverageSuite instanceof BaseCoverageSuite)) { return null; } Project project = baseCoverageSuite.getProject(); if (project == null) { return null; } RunConfigurationBase configuration = ((BaseCoverageSuite)baseCoverageSuite).getConfiguration(); Module module = configuration instanceof ModuleBasedConfiguration ? ((ModuleBasedConfiguration)configuration).getConfigurationModule().getModule() : null; try { BufferedReader reader = new BufferedReader(new FileReader(sessionDataFile.getAbsolutePath())); try { return parseCoverage(reader, project, module); } catch (IOException e) { LOG.warn(e); } finally { try { reader.close(); } catch (IOException e) { LOG.warn(e); } } } catch (FileNotFoundException e) { LOG.warn(e); } return null; } @Nullable public static GoCoverageProjectData parseCoverage(@NotNull BufferedReader dataReader, @NotNull Project project, @Nullable Module module) throws IOException { GoCoverageProjectData result = new GoCoverageProjectData(); String line; while ((line = dataReader.readLine()) != null) { if (line.isEmpty()) continue; List fileNameTail = StringUtil.split(line, ":"); VirtualFile file = GoPackageUtil.findByImportPath(fileNameTail.get(0), project, module); if (file == null) continue; String filePath = file.getPath(); List tailParts = StringUtil.split(fileNameTail.get(1), " "); if (tailParts.size() != 3) continue; int statements = Integer.parseInt(tailParts.get(1)); int hit = Integer.parseInt(tailParts.get(2)); String offsets = tailParts.get(0); int firstDot = offsets.indexOf('.'); int comma = offsets.indexOf(',', firstDot); int secondDot = offsets.indexOf('.', comma); if (firstDot == -1 || comma == -1 || secondDot == -1) continue; int lineStart = Integer.parseInt(offsets.substring(0, firstDot)); int columnStart = Integer.parseInt(offsets.substring(firstDot + 1, comma)); int lineEnd = Integer.parseInt(offsets.substring(comma + 1, secondDot)); int columnEnd = Integer.parseInt(offsets.substring(secondDot + 1)); result.addData(filePath, lineStart, columnStart, lineEnd, columnEnd, statements, hit); } result.processFiles(fileData -> { ClassData classData = result.getOrCreateClassData(fileData.myFilePath); int max = -1; TIntObjectHashMap linesMap = new TIntObjectHashMap<>(); for (GoCoverageProjectData.RangeData rangeData : fileData.myRangesData.values()) { for (int i = rangeData.startLine; i <= rangeData.endLine; i++) { LineData existingData = linesMap.get(i); if (existingData != null) { existingData.setHits(existingData.getHits() + rangeData.hits); // emulate partial existingData.setFalseHits(0, 0); existingData.setTrueHits(0, 0); } else { LineData newData = new LineData(i, null); newData.setHits(newData.getHits() + rangeData.hits); linesMap.put(i, newData); } } max = Math.max(max, rangeData.endLine); } LineData[] linesArray = new LineData[max + 1]; linesMap.forEachValue(data -> { data.fillArrays(); linesArray[data.getLineNumber()] = data; return true; }); classData.setLines(linesArray); return true; }); return result; } @Override public String getPresentableName() { return PRESENTABLE_NAME; } @Override public String getId() { return ID; } @Override public String getDataFileExtension() { return DATA_FILE_EXTENSION; } @Override public boolean acceptsCoverageEngine(@NotNull CoverageEngine engine) { return engine instanceof GoCoverageEngine; } } ================================================ FILE: src/com/goide/runconfig/testing/coverage/GoCoverageSuite.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.coverage; import com.intellij.coverage.BaseCoverageSuite; import com.intellij.coverage.CoverageEngine; import com.intellij.coverage.CoverageFileProvider; import com.intellij.coverage.CoverageRunner; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoCoverageSuite extends BaseCoverageSuite { public GoCoverageSuite() { } public GoCoverageSuite(String name, @Nullable CoverageFileProvider fileProvider, long lastCoverageTimeStamp, CoverageRunner coverageRunner, Project project) { super(name, fileProvider, lastCoverageTimeStamp, false, false, false, coverageRunner, project); } @NotNull @Override public CoverageEngine getCoverageEngine() { return GoCoverageEngine.INSTANCE; } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gobench/GobenchEventsConverter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gobench; import com.goide.GoConstants; import com.goide.runconfig.testing.frameworks.gotest.GoTestEventsConverterBaseImpl; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.ParseException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GobenchEventsConverter extends GoTestEventsConverterBaseImpl { private static final Pattern RUN = Pattern.compile("^(Benchmark(" + GoConstants.TEST_NAME_REGEX + ")?)"); private static final Pattern FAIL = Pattern.compile("^--- FAIL: (Benchmark(" + GoConstants.TEST_NAME_REGEX + ")?).*"); public GobenchEventsConverter(@NotNull TestConsoleProperties properties) { super(GobenchFramework.NAME, properties); } @Override protected int processLine(@NotNull String line, int start, Key outputType, ServiceMessageVisitor visitor) throws ParseException { Matcher matcher; if ((matcher = RUN.matcher(line)).find(start)) { startTest(matcher.group(1), visitor); int newStartOffset = findFirstNonWSIndex(line, matcher.end(1)); return newStartOffset != -1 ? newStartOffset : line.length(); } if ((matcher = FAIL.matcher(line.substring(start))).find()) { finishTest(matcher.group(1), TestResult.FAILED, visitor); int newStartOffset = findFirstNonWSIndex(line, start + matcher.end(1)); return newStartOffset != -1 ? newStartOffset : line.length(); } return start; } @Override protected void startTest(@NotNull String testName, @Nullable ServiceMessageVisitor visitor) throws ParseException { String currentTestName = getCurrentTestName(); if (currentTestName != null && !currentTestName.equals(testName)) { // previous test didn't fail, finish it as passed finishTest(currentTestName, TestResult.PASSED, visitor); } super.startTest(testName, visitor); } private static int findFirstNonWSIndex(@NotNull String text, int startOffset) { int whitespaceIndex = StringUtil.indexOfAny(text, " \t", startOffset, text.length()); if (whitespaceIndex != -1) { int newStartOffset = whitespaceIndex; while (newStartOffset < text.length() && Character.isWhitespace(text.charAt(newStartOffset))) newStartOffset++; return newStartOffset; } return -1; } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gobench/GobenchFramework.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gobench; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestFramework; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.goide.runconfig.testing.GoTestRunningState; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GobenchFramework extends GoTestFramework { public static final String NAME = "gobench"; public static final GobenchFramework INSTANCE = new GobenchFramework(); @NotNull @Override public String getName() { return NAME; } @Override public boolean isAvailable(@Nullable Module module) { return true; } @Override public boolean isAvailableOnFile(@Nullable PsiFile file) { return GoTestFinder.isTestFile(file); } @Override public boolean isAvailableOnFunction(@Nullable GoFunctionOrMethodDeclaration functionOrMethodDeclaration) { return functionOrMethodDeclaration instanceof GoFunctionDeclaration && GoTestFinder.isBenchmarkFunction(functionOrMethodDeclaration); } @NotNull @Override protected GoTestRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration runConfiguration) { return new GobenchRunningState(env, module, runConfiguration); } @NotNull @Override public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull TestConsoleProperties consoleProperties) { return new GobenchEventsConverter(consoleProperties); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gobench/GobenchRunConfigurationProducer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gobench; import com.goide.runconfig.testing.GoTestRunConfigurationProducerBase; import org.jetbrains.annotations.NotNull; public class GobenchRunConfigurationProducer extends GoTestRunConfigurationProducerBase implements Cloneable { public GobenchRunConfigurationProducer() { super(GobenchFramework.INSTANCE); } @NotNull @Override protected String getPackageConfigurationName(@NotNull String packageName) { return "gobench package '" + packageName + "'"; } @NotNull @Override protected String getFileConfigurationName(@NotNull String fileName) { return "gobench " + super.getFileConfigurationName(fileName); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gobench/GobenchRunningState.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gobench; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionDeclaration; import com.goide.runconfig.testing.GoTestFinder; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.goide.runconfig.testing.GoTestRunningState; import com.goide.util.GoExecutor; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GobenchRunningState extends GoTestRunningState { public GobenchRunningState(ExecutionEnvironment env, Module module, GoTestRunConfiguration configuration) { super(env, module, configuration); } @NotNull @Override protected String buildFilterPatternForFile(GoFile file) { Collection benchmarkNames = ContainerUtil.newLinkedHashSet(); for (GoFunctionDeclaration function : file.getFunctions()) { ContainerUtil.addIfNotNull(benchmarkNames, GoTestFinder.isBenchmarkFunction(function) ? function.getName() : null); } return "^" + StringUtil.join(benchmarkNames, "|") + "$"; } @Override protected void addFilterParameter(@NotNull GoExecutor executor, String pattern) { executor.withParameters("-bench", StringUtil.isEmpty(pattern) ? "." : pattern); executor.withParameters("-run", "^$"); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gocheck/GocheckEventsConverter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gocheck; import com.goide.runconfig.testing.GoTestEventsConverterBase; import com.goide.runconfig.testing.GoTestLocator; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.ServiceMessageBuilder; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.ParseException; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.intellij.openapi.util.Pair.pair; public class GocheckEventsConverter extends OutputToGeneralTestEventsConverter implements GoTestEventsConverterBase { private static final String FRAMEWORK_NAME = "gocheck"; /* * Scope hierarchy looks like this: * * GLOBAL * SUITE * SUITE_SETUP * TEST * TEST_SETUP * TEST_TEARDOWN * SUITE_TEARDOWN */ private enum Scope { GLOBAL, SUITE, SUITE_SETUP, SUITE_TEARDOWN, TEST, TEST_SETUP, TEST_TEARDOWN } private static final Pattern SUITE_START = Pattern.compile("=== RUN (.+)\\s*$"); private static final Pattern SUITE_END = Pattern.compile("((PASS)|(FAIL))\\s*$"); private static final Pattern TEST_START = Pattern.compile("(.*)START: [^:]+:\\d+: ([^\\s]+)\\s*$"); private static final Pattern TEST_PASSED = Pattern.compile("(.*)PASS: [^:]+:\\d+: ([^\\s]+)\\t[^\\s]+\\s*$"); private static final Pattern TEST_FAILED = Pattern.compile("(.*)FAIL: [^:]+:\\d+: ([^\\s]+)\\s*$"); private static final Pattern TEST_PANICKED = Pattern.compile("(.*)PANIC: [^:]+:\\d+: ([^\\s]+)\\s*$"); private static final Pattern TEST_MISSED = Pattern.compile("(.*)MISS: [^:]+:\\d+: ([^\\s]+)\\s*$"); private static final Pattern TEST_SKIPPED = Pattern.compile("(.*)SKIP: [^:]+:\\d+: ([^\\s]+)( \\(.*\\))?\\s*$"); private static final Pattern ERROR_LOCATION = Pattern.compile("(.*:\\d+):\\s*$"); private static final Pattern ERROR_ACTUAL = Pattern.compile("\\.\\.\\. ((obtained)|(value)) (.*?)( \\+)?\\s*$"); private static final Pattern ERROR_EXPECTED = Pattern.compile("\\.\\.\\. ((expected)|(regex)) (.*?)( \\+)?\\s*$"); private static final Pattern ERROR_CONTINUATION = Pattern.compile("\\.\\.\\. {5}(.*?)( +\\+)?\\s*$"); private static final Pattern PANIC_VALUE = Pattern.compile("(.*)\\.\\.\\. (Panic: .* \\(.*\\)\\s*)$"); private Scope myScope = Scope.GLOBAL; private String mySuiteName; private String myTestName; private long myCurrentTestStart; private TestResult myFixtureFailure; private List myStdOut; private enum Status { PASSED, FAILED, PANICKED, MISSED, SKIPPED } private static final class TestResult { private final Status myStatus; private final Map myAttributes = ContainerUtil.newHashMap(); TestResult(@NotNull Status status) { this(status, null); } TestResult(@NotNull Status status, @Nullable Map attributes) { myStatus = status; if (attributes != null) myAttributes.putAll(attributes); } @NotNull public Status getStatus() { return myStatus; } public void addAttributesTo(@NotNull ServiceMessageBuilder serviceMessageBuilder) { for (Map.Entry entry : myAttributes.entrySet()) { serviceMessageBuilder.addAttribute(entry.getKey(), entry.getValue()); } } } public GocheckEventsConverter(@NotNull TestConsoleProperties consoleProperties) { super(FRAMEWORK_NAME, consoleProperties); } @Override public boolean processServiceMessages(@NotNull String text, Key outputType, ServiceMessageVisitor visitor) throws ParseException { Matcher matcher; switch (myScope) { case GLOBAL: if (SUITE_START.matcher(text).matches()) { myScope = Scope.SUITE; return true; } break; case SUITE: if ((matcher = TEST_START.matcher(text)).matches()) { myStdOut = ContainerUtil.newArrayList(); myTestName = matcher.group(2); processTestSectionStart(myTestName, outputType, visitor); if (myTestName.endsWith(".SetUpSuite")) { myScope = Scope.SUITE_SETUP; return true; } if (myTestName.endsWith(".TearDownSuite")) { myScope = Scope.SUITE_TEARDOWN; return true; } myScope = Scope.TEST; return processTestStarted(myTestName, outputType, visitor); } if (SUITE_END.matcher(text).matches()) { myScope = Scope.GLOBAL; if (mySuiteName != null) { String suiteFinishedMsg = ServiceMessageBuilder.testSuiteFinished(mySuiteName).toString(); super.processServiceMessages(suiteFinishedMsg, outputType, visitor); processStdOut("SuiteTearDown", outputType, visitor); } return true; } break; case SUITE_SETUP: TestResult suiteSetUpResult = detectTestResult(text, true); if (suiteSetUpResult != null) { myScope = Scope.SUITE; if (suiteSetUpResult.getStatus() != Status.PASSED) { myFixtureFailure = suiteSetUpResult; } return true; } break; case SUITE_TEARDOWN: if (detectTestResult(text, false) != null) { myScope = Scope.SUITE; return true; } break; case TEST: if ((matcher = TEST_START.matcher(text)).matches()) { String stdOutLeftover = matcher.group(1); if (!StringUtil.isEmptyOrSpaces(stdOutLeftover)) { myStdOut.add(stdOutLeftover); } String testName = matcher.group(2); if (testName.endsWith(".SetUpTest")) { myScope = Scope.TEST_SETUP; return true; } if (testName.endsWith(".TearDownTest")) { myScope = Scope.TEST_TEARDOWN; return true; } } TestResult testResult = detectTestResult(text, true); if (testResult != null) { myScope = Scope.SUITE; if (StringUtil.notNullize(testResult.myAttributes.get("details")).contains("Fixture has panicked") || (testResult.getStatus() == Status.MISSED || testResult.getStatus() == Status.SKIPPED) && myFixtureFailure != null) { testResult = myFixtureFailure; } myFixtureFailure = null; processTestResult(testResult, outputType, visitor); return true; } break; case TEST_SETUP: TestResult testSetUpResult = detectTestResult(text, true); if (testSetUpResult != null) { myScope = Scope.TEST; if (testSetUpResult.getStatus() != Status.PASSED) { myFixtureFailure = testSetUpResult; } return true; } break; case TEST_TEARDOWN: boolean isSetUpFailed = myFixtureFailure != null; TestResult testTearDownResult = detectTestResult(text, !isSetUpFailed); if (testTearDownResult != null) { myScope = Scope.TEST; if (!isSetUpFailed && testTearDownResult.getStatus() != Status.PASSED) { myFixtureFailure = testTearDownResult; } return true; } break; } if (myStdOut != null) { myStdOut.add(text); return true; } return super.processServiceMessages(text, outputType, visitor); } @Nullable private TestResult detectTestResult(String text, boolean parseDetails) { Matcher matcher; if ((matcher = TEST_PASSED.matcher(text)).matches()) { myStdOut.add(StringUtil.notNullize(matcher.group(1)).trim()); return new TestResult(Status.PASSED); } if ((matcher = TEST_MISSED.matcher(text)).matches()) { myStdOut.add(StringUtil.notNullize(matcher.group(1)).trim()); return new TestResult(Status.MISSED); } if ((matcher = TEST_SKIPPED.matcher(text)).matches()) { myStdOut.add(StringUtil.notNullize(matcher.group(1)).trim()); return new TestResult(Status.SKIPPED); } if ((matcher = TEST_FAILED.matcher(text)).matches()) { myStdOut.add(StringUtil.notNullize(matcher.group(1)).trim()); if (parseDetails) { return new TestResult(Status.FAILED, parseFailureAttributes()); } return new TestResult(Status.FAILED); } if ((matcher = TEST_PANICKED.matcher(text)).matches()) { myStdOut.add(StringUtil.notNullize(matcher.group(1)).trim()); if (parseDetails) { return new TestResult(Status.PANICKED, parsePanickedAttributes()); } return new TestResult(Status.FAILED); } return null; } private boolean processTestStarted(@NotNull String testName, Key outputType, ServiceMessageVisitor visitor) throws ParseException { String testStartedMsg = ServiceMessageBuilder.testStarted(testName) .addAttribute("locationHint", testUrl(testName)).toString(); return super.processServiceMessages(testStartedMsg, outputType, visitor); } private void processTestResult(@NotNull TestResult testResult, Key outputType, ServiceMessageVisitor visitor) throws ParseException { processStdOut(myTestName, outputType, visitor); switch (testResult.getStatus()) { case PASSED: break; case MISSED: case SKIPPED: String testIgnoredStr = ServiceMessageBuilder.testIgnored(myTestName).toString(); super.processServiceMessages(testIgnoredStr, outputType, visitor); break; case FAILED: ServiceMessageBuilder testError = ServiceMessageBuilder.testFailed(myTestName); testResult.addAttributesTo(testError); super.processServiceMessages(testError.toString(), outputType, visitor); break; case PANICKED: ServiceMessageBuilder testPanicked = ServiceMessageBuilder.testFailed(myTestName); testResult.addAttributesTo(testPanicked); super.processServiceMessages(testPanicked.toString(), outputType, visitor); break; default: throw new RuntimeException("Unexpected test result: " + testResult); } long duration = System.currentTimeMillis() - myCurrentTestStart; String testFinishedMsg = ServiceMessageBuilder.testFinished(myTestName).addAttribute("duration", Long.toString(duration)).toString(); super.processServiceMessages(testFinishedMsg, outputType, visitor); } private void processStdOut(@NotNull String testName, Key outputType, ServiceMessageVisitor visitor) throws ParseException { if (myStdOut == null) { return; } String allStdOut = StringUtil.join(myStdOut, ""); if (!StringUtil.isEmptyOrSpaces(allStdOut)) { String testStdOutMsg = ServiceMessageBuilder.testStdOut(testName).addAttribute("out", allStdOut).toString(); super.processServiceMessages(testStdOutMsg, outputType, visitor); } myStdOut = null; } private void processTestSectionStart(@NotNull String testName, Key outputType, ServiceMessageVisitor visitor) throws ParseException { String suiteName = testName.substring(0, testName.indexOf(".")); myTestName = testName; myCurrentTestStart = System.currentTimeMillis(); if (!suiteName.equals(mySuiteName)) { if (mySuiteName != null) { String suiteFinishedMsg = ServiceMessageBuilder.testSuiteFinished(mySuiteName).toString(); super.processServiceMessages(suiteFinishedMsg, outputType, visitor); } mySuiteName = suiteName; String suiteStartedMsg = ServiceMessageBuilder.testSuiteStarted(suiteName) .addAttribute("locationHint", suiteUrl(suiteName)).toString(); super.processServiceMessages(suiteStartedMsg, outputType, visitor); } } /** * Parses assertion error report into a set of SystemMessage attributes. *

    * An assertion error report usually looks like this: *

       * all_fail_test.go:36:
       *     c.Assert("Foo", Equals, "Bar")
       * ... obtained string = "Foo"
       * ... expected string = "Bar"
       * 
    * or this: *
       * all_fail_test.go:21:
       *     c.Assert("Foo", IsNil)
       * ... value string = "Foo"
       * 
    * or this: *
       * all_fail_test.go:54:
       *     c.Assert(`multi
       *
       *     	          line
       *     	          string`,
       *         Equals,
       *         `Another
       *     multi
       *     	line
       *     		string`)
       * ... obtained string = "" +
       * ...     "multi\n" +
       * ...     "\n" +
       * ...     "\t          line\n" +
       * ...     "\t          string"
       * ... expected string = "" +
       * ...     "Another\n" +
       * ...     "multi\n" +
       * ...     "\tline\n" +
       * ...     "\t\tstring"
       * 
    * There are other variation. Check out the respective unit test. * * @return a map of system message attributes. */ @Nullable private Map parseFailureAttributes() { if (myStdOut == null || myStdOut.isEmpty()) return null; int lineNumber = myStdOut.size() - 1; StringBuilder expectedMessage = new StringBuilder(); StringBuilder actualMessage = new StringBuilder(); StringBuilder errorMessage = new StringBuilder(); String details = ""; // Skip forward to the error description. while (lineNumber >= 0 && !StringUtil.startsWith(myStdOut.get(lineNumber), "...")) { lineNumber--; } lineNumber = collectErrorMessage(myStdOut, lineNumber, ERROR_CONTINUATION, ERROR_EXPECTED, expectedMessage); lineNumber = collectErrorMessage(myStdOut, lineNumber, ERROR_CONTINUATION, ERROR_ACTUAL, actualMessage); // Collect all lines of the error message and details while (lineNumber >= 0) { String line = myStdOut.get(lineNumber); Matcher matcher = ERROR_LOCATION.matcher(line); if (matcher.matches()) { details = matcher.group(1); break; } else { errorMessage.insert(0, line); lineNumber--; } } // Remove the assertion error info from the test StdOut. myStdOut = safeSublist(myStdOut, lineNumber); return ContainerUtil.newHashMap(pair("expected", expectedMessage.toString().trim()), pair("actual", actualMessage.toString().trim()), pair("type", "comparisonFailure"), pair("message", errorMessage.toString().trim()), pair("details", details)); } private static int collectErrorMessage(List lines, int currentLine, Pattern continuationPattern, Pattern messagePattern, StringBuilder result) { while (currentLine >= 0) { String line = lines.get(currentLine); Matcher continuationMatcher = continuationPattern.matcher(line); if (continuationMatcher.matches()) { result.insert(0, '\n').insert(0, continuationMatcher.group(1)); currentLine--; continue; } Matcher messageMatcher = messagePattern.matcher(line); if (messageMatcher.matches()) { result.insert(0, '\n').insert(0, messageMatcher.group(4)); currentLine--; } break; } return currentLine; } /** * Parses panic report into a set of SystemMessage attributes. *

    * A panic report usually looks like this: *

       * ... Panic: bar (PC=0x3B0A5)
       *
       * /usr/local/go/src/runtime/panic.go:387
       *   in gopanic
       * some_panic_test.go:31
       *   in SomePanicSuite.TestD
       * /usr/local/go/src/reflect/value.go:296
       *   in Value.Call
       * /usr/local/go/src/runtime/asm_amd64.s:2232
       *   in goexit
       * 
    * * @return a map of system message attributes. */ @Nullable private Map parsePanickedAttributes() { if (myStdOut == null || myStdOut.isEmpty()) return null; int lineNumber = myStdOut.size() - 1; // Ignore trailing empty lines. while (lineNumber >= 0 && StringUtil.isEmptyOrSpaces(myStdOut.get(lineNumber))) { lineNumber--; } StringBuilder detailsMessage = new StringBuilder(); // All lines up until an empty one comprise the stack trace. while (lineNumber >= 0 && !StringUtil.isEmptyOrSpaces(myStdOut.get(lineNumber))) { detailsMessage.insert(0, myStdOut.get(lineNumber)); lineNumber--; } lineNumber--; // skip empty line // Then follows the panic description. String errorMessage = ""; Matcher matcher; if (lineNumber >= 0 && (matcher = PANIC_VALUE.matcher(myStdOut.get(lineNumber))).matches()) { String stdoutLeftover = matcher.group(1); if (!StringUtil.isEmptyOrSpaces(stdoutLeftover)) { myStdOut.set(lineNumber, stdoutLeftover); lineNumber++; } errorMessage = matcher.group(2); } // Remove the panic info from the test StdOut. myStdOut = safeSublist(myStdOut, lineNumber); return ContainerUtil.newHashMap(pair("details", detailsMessage.toString()), pair("message", errorMessage)); } @NotNull private static List safeSublist(@NotNull List list, int until) { if (0 < until && until <= list.size() - 1) { return list.subList(0, until); } return ContainerUtil.newArrayList(); } @NotNull private static String suiteUrl(@NotNull String suiteName) { return GoTestLocator.SUITE_PROTOCOL + "://" + suiteName; } @NotNull private static String testUrl(@NotNull String testName) { return GoTestLocator.PROTOCOL + "://" + testName; } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gocheck/GocheckFramework.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gocheck; import com.goide.psi.GoFile; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoMethodDeclaration; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.*; import com.goide.stubs.index.GoPackagesIndex; import com.goide.util.GoUtil; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiFile; import com.intellij.psi.stubs.StubIndex; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.regex.Pattern; public class GocheckFramework extends GoTestFramework { public static final String NAME = "gocheck"; public static final GocheckFramework INSTANCE = new GocheckFramework(); private static final Pattern GO_CHECK_IMPORT_PATH = Pattern.compile("gopkg\\.in/check\\.v\\d+"); private static final Pattern GO_CHECK_GITHUB_IMPORT_PATH = Pattern.compile("github\\.com/go-check/check\\.v\\d+"); private GocheckFramework() { } @Nullable public static String getGocheckTestName(@NotNull GoMethodDeclaration method) { String methodName = GoTestFunctionType.fromName(method.getName()) == GoTestFunctionType.TEST ? method.getName() : null; if (methodName != null) { String suiteName = GoPsiImplUtil.getText(method.getReceiverType()); if (!suiteName.isEmpty()) { return suiteName + "." + methodName; } } return null; } @NotNull @Override public String getName() { return NAME; } @Override public boolean isAvailable(@Nullable Module module) { if (module == null) return false; return !StubIndex.getInstance().processElements(GoPackagesIndex.KEY, "check", module.getProject(), GoUtil.goPathResolveScope(module, null), GoFile.class, file -> !isGoCheckImportPath(file.getImportPath(true))); } private static boolean isGoCheckImportPath(String importPath) { if (importPath == null) return false; return GO_CHECK_IMPORT_PATH.matcher(importPath).matches() || GO_CHECK_GITHUB_IMPORT_PATH.matcher(importPath).matches(); } @Override public boolean isAvailableOnFile(@Nullable PsiFile file) { if (!GoTestFinder.isTestFile(file)) { return false; } for (String importPath : ((GoFile)file).getImportedPackagesMap().keySet()) { if (isGoCheckImportPath(importPath)) { return true; } } return false; } @Override public boolean isAvailableOnFunction(@Nullable GoFunctionOrMethodDeclaration functionOrMethodDeclaration) { return functionOrMethodDeclaration instanceof GoMethodDeclaration && GoTestFinder.isTestOrExampleFunction(functionOrMethodDeclaration); } @NotNull @Override protected GoTestRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration runConfiguration) { return new GocheckRunningState(env, module, runConfiguration); } @NotNull @Override public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull TestConsoleProperties consoleProperties) { return new GocheckEventsConverter(consoleProperties); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gocheck/GocheckRunConfigurationProducer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gocheck; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoMethodDeclaration; import com.goide.runconfig.testing.GoTestRunConfigurationProducerBase; import org.jetbrains.annotations.NotNull; public class GocheckRunConfigurationProducer extends GoTestRunConfigurationProducerBase implements Cloneable { public GocheckRunConfigurationProducer() { super(GocheckFramework.INSTANCE); } @NotNull @Override protected String getPackageConfigurationName(@NotNull String packageName) { return "gocheck package '" + packageName + "'"; } @NotNull @Override protected String getFunctionConfigurationName(@NotNull GoFunctionOrMethodDeclaration function, @NotNull String fileName) { return function instanceof GoMethodDeclaration ? GocheckFramework.getGocheckTestName((GoMethodDeclaration)function) + " in " + fileName : super.getFunctionConfigurationName(function, fileName); } @NotNull @Override protected String getFileConfigurationName(@NotNull String fileName) { return "gocheck " + super.getFileConfigurationName(fileName); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gocheck/GocheckRunningState.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gocheck; import com.goide.psi.GoFile; import com.goide.psi.GoMethodDeclaration; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.goide.runconfig.testing.GoTestRunningState; import com.goide.util.GoExecutor; import com.intellij.execution.ExecutionException; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GocheckRunningState extends GoTestRunningState { public GocheckRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration configuration) { super(env, module, configuration); } @Override protected GoExecutor patchExecutor(@NotNull GoExecutor executor) throws ExecutionException { return super.patchExecutor(executor).withParameters("-check.vv"); } @NotNull @Override protected String buildFilterPatternForFile(GoFile file) { Collection testNames = ContainerUtil.newLinkedHashSet(); for (GoMethodDeclaration method : file.getMethods()) { ContainerUtil.addIfNotNull(testNames, GocheckFramework.getGocheckTestName(method)); } return "^" + StringUtil.join(testNames, "|") + "$"; } @Override protected void addFilterParameter(@NotNull GoExecutor executor, String pattern) { if (StringUtil.isNotEmpty(pattern)) { executor.withParameters("-check.f", pattern); } } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gotest/GoTestEventsConverterBaseImpl.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gotest; import com.goide.runconfig.testing.GoTestEventsConverterBase; import com.goide.runconfig.testing.GoTestLocator; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.ServiceMessageBuilder; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTypes; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.text.ParseException; public abstract class GoTestEventsConverterBaseImpl extends OutputToGeneralTestEventsConverter implements GoTestEventsConverterBase { public enum TestResult {PASSED, FAILED, SKIPPED} @Nullable private ServiceMessageVisitor myVisitor; @Nullable private String myCurrentTestName; @Nullable private TestResult myCurrentTestResult; private long myCurrentTestStart; public GoTestEventsConverterBaseImpl(@NotNull String testFrameworkName, @NotNull TestConsoleProperties consoleProperties) { super(testFrameworkName, consoleProperties); } protected abstract int processLine(@NotNull String line, int start, Key outputType, ServiceMessageVisitor visitor) throws ParseException; @Nullable protected String getCurrentTestName() { return myCurrentTestName; } @Override public final boolean processServiceMessages(@NotNull String text, Key outputType, ServiceMessageVisitor visitor) throws ParseException { if (myVisitor == null && visitor != null) { myVisitor = visitor; } if (text.isEmpty()) { return true; } int startOffset = 0; int newStartOffset = processLine(text, startOffset, outputType, visitor); while (startOffset != newStartOffset && newStartOffset < text.length()) { startOffset = newStartOffset; newStartOffset = processLine(text, startOffset, outputType, visitor); } if (newStartOffset < text.length()) { processOutput(text.substring(startOffset), outputType, visitor); } return true; } protected void processOutput(@NotNull String text, Key outputType, ServiceMessageVisitor visitor) throws ParseException { if (text.isEmpty()) { return; } boolean isErrorMessage = ProcessOutputTypes.STDERR == outputType; if (myCurrentTestName != null) { ServiceMessageBuilder builder = isErrorMessage ? ServiceMessageBuilder.testStdErr(myCurrentTestName) : ServiceMessageBuilder.testStdOut(myCurrentTestName); super.processServiceMessages(builder.addAttribute("out", text).toString(), outputType, visitor); return; } ServiceMessageBuilder messageBuilder = new ServiceMessageBuilder(ServiceMessageTypes.MESSAGE); if (isErrorMessage) { messageBuilder.addAttribute("text", StringUtil.trimEnd(text, "\n")).addAttribute("status", "ERROR"); } else { messageBuilder.addAttribute("text", text).addAttribute("status", "NORMAL"); } super.processServiceMessages(messageBuilder.toString(), outputType, visitor); } @Override public void dispose() { myVisitor = null; super.dispose(); } protected void startTest(@NotNull String testName, @Nullable ServiceMessageVisitor visitor) throws ParseException { if (isCurrentlyRunningTest(testName)) { return; } finishDelayedTest(visitor); myCurrentTestName = testName; myCurrentTestResult = null; myCurrentTestStart = System.currentTimeMillis(); String testStartedMessage = ServiceMessageBuilder.testStarted(testName).addAttribute("locationHint", testUrl(testName)).toString(); super.processServiceMessages(testStartedMessage, null, visitor); } @Override public final void flushBufferBeforeTerminating() { try { if (!finishDelayedTest(myVisitor)) { if (myCurrentTestName != null) { finishTestInner(myCurrentTestName, TestResult.PASSED, myVisitor); } } } catch (ParseException ignore) { } myVisitor = null; super.flushBufferBeforeTerminating(); } protected void finishTest(@NotNull String name, @NotNull TestResult result, @Nullable ServiceMessageVisitor visitor) throws ParseException { if (isCurrentlyRunningTest(name)) { if (myCurrentTestResult == null) { // delay finishing test, we'll use it as a container for future output myCurrentTestResult = result; } return; } finishTestInner(name, result, visitor); } protected boolean finishDelayedTest(ServiceMessageVisitor visitor) throws ParseException { if (myCurrentTestName != null && myCurrentTestResult != null) { finishTestInner(myCurrentTestName, myCurrentTestResult, visitor); return true; } return false; } private boolean isCurrentlyRunningTest(@NotNull String testName) { return testName.equals(myCurrentTestName); } private void finishTestInner(@NotNull String name, @NotNull TestResult result, @Nullable ServiceMessageVisitor visitor) throws ParseException { if (isCurrentlyRunningTest(name)) { myCurrentTestName = null; myCurrentTestResult = null; } String duration = myCurrentTestStart > 0 ? Long.toString(System.currentTimeMillis() - myCurrentTestStart) : null; switch (result) { case PASSED: break; case FAILED: String failedMessage = ServiceMessageBuilder.testFailed(name).addAttribute("message", "").toString(); super.processServiceMessages(failedMessage, null, visitor); break; case SKIPPED: String skipMessage = ServiceMessageBuilder.testIgnored(name).addAttribute("message", "").toString(); super.processServiceMessages(skipMessage, null, visitor); break; } String finishedMessage = ServiceMessageBuilder.testFinished(name).addAttribute("duration", duration).toString(); super.processServiceMessages(finishedMessage, null, visitor); } @NotNull private static String testUrl(@NotNull String testName) { return GoTestLocator.PROTOCOL + "://" + testName; } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gotest/GotestEventsConverter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gotest; import com.goide.GoConstants; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.openapi.util.Key; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageVisitor; import org.jetbrains.annotations.NotNull; import java.text.ParseException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GotestEventsConverter extends GoTestEventsConverterBaseImpl { private static final Pattern RUN = Pattern.compile("^=== RUN\\s+(" + GoConstants.TEST_NAME_REGEX + ")"); private static final Pattern PASSED = Pattern.compile("--- PASS:\\s+(" + GoConstants.TEST_NAME_REGEX + ")"); private static final Pattern SKIP = Pattern.compile("--- SKIP:\\s+(" + GoConstants.TEST_NAME_REGEX + ")"); private static final Pattern FAILED = Pattern.compile("--- FAIL:\\s+(" + GoConstants.TEST_NAME_REGEX + ")"); private static final Pattern FINISHED = Pattern.compile("^(PASS)|(FAIL)$"); public GotestEventsConverter(@NotNull TestConsoleProperties consoleProperties) { super(GotestFramework.NAME, consoleProperties); } @Override protected int processLine(@NotNull String line, int start, Key outputType, ServiceMessageVisitor visitor) throws ParseException { Matcher matcher; if ((matcher = RUN.matcher(line)).find(start)) { startTest(matcher.group(1), visitor); return line.length(); } if ((matcher = SKIP.matcher(line)).find(start)) { processOutput(line.substring(start, matcher.start()), outputType, visitor); finishTest(matcher.group(1), TestResult.SKIPPED, visitor); return line.length(); } if ((matcher = FAILED.matcher(line)).find(start)) { processOutput(line.substring(start, matcher.start()), outputType, visitor); finishTest(matcher.group(1), TestResult.FAILED, visitor); return line.length(); } if ((matcher = PASSED.matcher(line)).find(start)) { processOutput(line.substring(start, matcher.start()), outputType, visitor); finishTest(matcher.group(1), TestResult.PASSED, visitor); return line.length(); } if (FINISHED.matcher(line).find(start)) { finishDelayedTest(visitor); return line.length(); } return start; } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gotest/GotestFramework.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gotest; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.runconfig.testing.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; public class GotestFramework extends GoTestFramework { public static final String NAME = "gotest"; public static final GotestFramework INSTANCE = new GotestFramework(); private static final ArrayList GENERATE_ACTIONS = ContainerUtil.newArrayList( new GotestGenerateAction(GoTestFunctionType.TEST), new GotestGenerateAction(GoTestFunctionType.BENCHMARK), new GotestGenerateAction(GoTestFunctionType.EXAMPLE)); private GotestFramework() { } @Override public Collection getGenerateMethodActions() { return GENERATE_ACTIONS; } @NotNull @Override public String getName() { return NAME; } @Override public boolean isAvailable(@Nullable Module module) { return true; } @Override public boolean isAvailableOnFile(@Nullable PsiFile file) { return GoTestFinder.isTestFile(file); } @Override public boolean isAvailableOnFunction(@Nullable GoFunctionOrMethodDeclaration functionOrMethodDeclaration) { return functionOrMethodDeclaration instanceof GoFunctionDeclaration && GoTestFinder.isTestOrExampleFunction(functionOrMethodDeclaration); } @NotNull @Override protected GoTestRunningState newRunningState(@NotNull ExecutionEnvironment env, @NotNull Module module, @NotNull GoTestRunConfiguration runConfiguration) { return new GoTestRunningState(env, module, runConfiguration); } @NotNull @Override public OutputToGeneralTestEventsConverter createTestEventsConverter(@NotNull TestConsoleProperties consoleProperties) { return new GotestEventsConverter(consoleProperties); } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gotest/GotestGenerateAction.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gotest; import com.goide.GoConstants; import com.goide.generate.GoGenerateTestActionBase; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFunctionType; import com.goide.template.GoLiveTemplateContextType; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.template.TemplateContextType; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.NotNull; import java.util.Locale; public class GotestGenerateAction extends GoGenerateTestActionBase { public GotestGenerateAction(@NotNull GoTestFunctionType type) { super(GotestFramework.INSTANCE, new GenerateActionHandler(type)); String presentationName = StringUtil.capitalize(type.toString().toLowerCase(Locale.US)); Presentation presentation = getTemplatePresentation(); presentation.setText(presentationName); presentation.setDescription("Generate " + presentationName + " function"); } @Override protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { GoLiveTemplateContextType.File fileContextType = TemplateContextType.EP_NAME.findExtension(GoLiveTemplateContextType.File.class); return fileContextType != null && fileContextType.isInContext(file, editor.getCaretModel().getOffset()); } @NotNull public static String importTestingPackageIfNeeded(@NotNull GoFile file) { GoImportSpec alreadyImportedPackage = file.getImportedPackagesMap().get(GoConstants.TESTING_PATH); String qualifier = GoPsiImplUtil.getImportQualifierToUseInFile(alreadyImportedPackage, GoConstants.TESTING_PATH); if (qualifier != null) { return qualifier; } String localName = UniqueNameGenerator.generateUniqueName(GoConstants.TESTING_PATH, file.getImportMap().keySet()); file.addImport(GoConstants.TESTING_PATH, !GoConstants.TESTING_PATH.equals(localName) ? localName : null); return localName; } private static class GenerateActionHandler implements CodeInsightActionHandler { @NotNull private final GoTestFunctionType myType; public GenerateActionHandler(@NotNull GoTestFunctionType type) { myType = type; } @Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { if (!(file instanceof GoFile)) { return; } String testingQualifier = null; if (myType.getParamType() != null) { testingQualifier = importTestingPackageIfNeeded((GoFile)file); PsiDocumentManager.getInstance(file.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument()); } String functionText = "func " + myType.getPrefix(); int offset = functionText.length(); functionText += "(" + myType.getSignature(testingQualifier) + ") {\n\t\n}"; EditorModificationUtil.insertStringAtCaret(editor, functionText, false, offset); AutoPopupController.getInstance(project).scheduleAutoPopup(editor); } @Override public boolean startInWriteAction() { return true; } } } ================================================ FILE: src/com/goide/runconfig/testing/frameworks/gotest/GotestRunConfigurationProducer.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.frameworks.gotest; import com.goide.runconfig.testing.GoTestRunConfigurationProducerBase; public class GotestRunConfigurationProducer extends GoTestRunConfigurationProducerBase implements Cloneable { public GotestRunConfigurationProducer() { super(GotestFramework.INSTANCE); } } ================================================ FILE: src/com/goide/runconfig/testing/ui/GoPackageFieldCompletionProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.ui; import com.goide.completion.GoImportPathsCompletionProvider; import com.goide.util.GoUtil; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.openapi.module.Module; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.Producer; import com.intellij.util.TextFieldCompletionProvider; import org.jetbrains.annotations.NotNull; public class GoPackageFieldCompletionProvider extends TextFieldCompletionProvider { @NotNull private final Producer myModuleProducer; public GoPackageFieldCompletionProvider(@NotNull Producer moduleProducer) { myModuleProducer = moduleProducer; } @Override protected void addCompletionVariants(@NotNull String text, int offset, @NotNull String prefix, @NotNull CompletionResultSet result) { Module module = myModuleProducer.produce(); if (module != null) { GlobalSearchScope scope = GoUtil.moduleScopeWithoutLibraries(module.getProject(), module); GoImportPathsCompletionProvider.addCompletions(result, module, null, scope, true); } } } ================================================ FILE: src/com/goide/runconfig/testing/ui/GoTestRunConfigurationEditorForm.form ================================================
    ================================================ FILE: src/com/goide/runconfig/testing/ui/GoTestRunConfigurationEditorForm.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing.ui; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.testing.GoTestRunConfiguration; import com.goide.runconfig.testing.frameworks.gobench.GobenchFramework; import com.goide.runconfig.testing.frameworks.gocheck.GocheckFramework; import com.goide.runconfig.testing.frameworks.gotest.GotestFramework; import com.goide.runconfig.ui.GoCommonSettingsPanel; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.EditorTextField; import com.intellij.ui.ListCellRendererWrapper; import org.intellij.lang.regexp.RegExpLanguage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Locale; public class GoTestRunConfigurationEditorForm extends SettingsEditor { @NotNull private final Project myProject; private JPanel myComponent; private EditorTextField myPatternEditor; private JComboBox myTestKindComboBox; private JLabel myFileLabel; private TextFieldWithBrowseButton myFileField; private JLabel myPackageLabel; private EditorTextField myPackageField; private JLabel myDirectoryLabel; private TextFieldWithBrowseButton myDirectoryField; private JLabel myPatternLabel; private GoCommonSettingsPanel myCommonSettingsPanel; private JRadioButton myGotestFrameworkRadioButton; private JRadioButton myGocheckFrameworkRadioButton; private JRadioButton myGobenchRadioButton; public GoTestRunConfigurationEditorForm(@NotNull Project project) { super(null); myProject = project; myCommonSettingsPanel.init(project); installTestKindComboBox(); installFileChoosers(project); } private void onTestKindChanged() { GoTestRunConfiguration.Kind selectedKind = (GoTestRunConfiguration.Kind)myTestKindComboBox.getSelectedItem(); if (selectedKind == null) { selectedKind = GoTestRunConfiguration.Kind.DIRECTORY; } boolean allInPackage = selectedKind == GoTestRunConfiguration.Kind.PACKAGE; boolean allInDirectory = selectedKind == GoTestRunConfiguration.Kind.DIRECTORY; boolean file = selectedKind == GoTestRunConfiguration.Kind.FILE; myPackageField.setVisible(allInPackage); myPackageLabel.setVisible(allInPackage); myDirectoryField.setVisible(allInDirectory); myDirectoryLabel.setVisible(allInDirectory); myFileField.setVisible(file); myFileLabel.setVisible(file); myPatternEditor.setVisible(!file); myPatternLabel.setVisible(!file); } @Override protected void resetEditorFrom(@NotNull GoTestRunConfiguration configuration) { myGotestFrameworkRadioButton.setSelected(configuration.getTestFramework() == GotestFramework.INSTANCE); myGocheckFrameworkRadioButton.setSelected(configuration.getTestFramework() == GocheckFramework.INSTANCE); myGobenchRadioButton.setSelected(configuration.getTestFramework() == GobenchFramework.INSTANCE); myTestKindComboBox.setSelectedItem(configuration.getKind()); myPackageField.setText(configuration.getPackage()); String directoryPath = configuration.getDirectoryPath(); myDirectoryField.setText(directoryPath.isEmpty() ? configuration.getProject().getBasePath() : directoryPath); String filePath = configuration.getFilePath(); myFileField.setText(filePath.isEmpty() ? configuration.getProject().getBasePath() : filePath); myPatternEditor.setText(configuration.getPattern()); myCommonSettingsPanel.resetEditorFrom(configuration); } @Override protected void applyEditorTo(@NotNull GoTestRunConfiguration configuration) throws ConfigurationException { if (myGocheckFrameworkRadioButton.isSelected()) { configuration.setTestFramework(GocheckFramework.INSTANCE); } else if (myGobenchRadioButton.isSelected()) { configuration.setTestFramework(GobenchFramework.INSTANCE); } else { configuration.setTestFramework(GotestFramework.INSTANCE); } configuration.setKind((GoTestRunConfiguration.Kind)myTestKindComboBox.getSelectedItem()); configuration.setPackage(myPackageField.getText()); configuration.setDirectoryPath(myDirectoryField.getText()); configuration.setFilePath(myFileField.getText()); configuration.setPattern(myPatternEditor.getText()); myCommonSettingsPanel.applyEditorTo(configuration); } @NotNull @Override protected JComponent createEditor() { return myComponent; } @Override protected void disposeEditor() { myComponent.setVisible(false); } private void createUIComponents() { myPatternEditor = new EditorTextField("", null, RegExpLanguage.INSTANCE.getAssociatedFileType()); myPackageField = new GoPackageFieldCompletionProvider( () -> myCommonSettingsPanel != null ? myCommonSettingsPanel.getSelectedModule() : null).createEditor(myProject); } @Nullable private static ListCellRendererWrapper getTestKindListCellRendererWrapper() { return new ListCellRendererWrapper() { @Override public void customize(JList list, @Nullable GoTestRunConfiguration.Kind kind, int index, boolean selected, boolean hasFocus) { if (kind != null) { String kindName = StringUtil.capitalize(kind.toString().toLowerCase(Locale.US)); setText(kindName); } } }; } private void installFileChoosers(@NotNull Project project) { GoRunUtil.installFileChooser(project, myFileField, false); GoRunUtil.installFileChooser(project, myDirectoryField, true); } private void installTestKindComboBox() { myTestKindComboBox.removeAllItems(); myTestKindComboBox.setRenderer(getTestKindListCellRendererWrapper()); for (GoTestRunConfiguration.Kind kind : GoTestRunConfiguration.Kind.values()) { myTestKindComboBox.addItem(kind); } myTestKindComboBox.addActionListener(e -> onTestKindChanged()); } } ================================================ FILE: src/com/goide/runconfig/ui/GoApplicationConfigurationEditorForm.form ================================================
    ================================================ FILE: src/com/goide/runconfig/ui/GoApplicationConfigurationEditorForm.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.ui; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.application.GoApplicationConfiguration; import com.goide.runconfig.testing.ui.GoPackageFieldCompletionProvider; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.EditorTextField; import com.intellij.ui.ListCellRendererWrapper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Locale; public class GoApplicationConfigurationEditorForm extends SettingsEditor { @NotNull private final Project myProject; private JPanel myComponent; private TextFieldWithBrowseButton myFileField; private GoCommonSettingsPanel myCommonSettingsPanel; private EditorTextField myPackageField; private JComboBox myRunKindComboBox; private JLabel myPackageLabel; private JLabel myFileLabel; private TextFieldWithBrowseButton myOutputFilePathField; public GoApplicationConfigurationEditorForm(@NotNull Project project) { super(null); myProject = project; myCommonSettingsPanel.init(project); installRunKindComboBox(); GoRunUtil.installGoWithMainFileChooser(myProject, myFileField); GoRunUtil.installFileChooser(myProject, myOutputFilePathField, true, true); } private void onRunKindChanged() { GoApplicationConfiguration.Kind selectedKind = (GoApplicationConfiguration.Kind)myRunKindComboBox.getSelectedItem(); if (selectedKind == null) { selectedKind = GoApplicationConfiguration.Kind.PACKAGE; } boolean thePackage = selectedKind == GoApplicationConfiguration.Kind.PACKAGE; boolean file = selectedKind == GoApplicationConfiguration.Kind.FILE; myPackageField.setVisible(thePackage); myPackageLabel.setVisible(thePackage); myFileField.setVisible(file); myFileLabel.setVisible(file); } @Override protected void resetEditorFrom(@NotNull GoApplicationConfiguration configuration) { myFileField.setText(configuration.getFilePath()); myPackageField.setText(configuration.getPackage()); myRunKindComboBox.setSelectedItem(configuration.getKind()); myOutputFilePathField.setText(StringUtil.notNullize(configuration.getOutputFilePath())); myCommonSettingsPanel.resetEditorFrom(configuration); } @Override protected void applyEditorTo(@NotNull GoApplicationConfiguration configuration) throws ConfigurationException { configuration.setFilePath(myFileField.getText()); configuration.setPackage(myPackageField.getText()); configuration.setKind((GoApplicationConfiguration.Kind)myRunKindComboBox.getSelectedItem()); configuration.setFileOutputPath(StringUtil.nullize(myOutputFilePathField.getText())); myCommonSettingsPanel.applyEditorTo(configuration); } private void createUIComponents() { myPackageField = new GoPackageFieldCompletionProvider( () -> myCommonSettingsPanel != null ? myCommonSettingsPanel.getSelectedModule() : null).createEditor(myProject); } @Nullable private static ListCellRendererWrapper getRunKindListCellRendererWrapper() { return new ListCellRendererWrapper() { @Override public void customize(JList list, @Nullable GoApplicationConfiguration.Kind kind, int index, boolean selected, boolean hasFocus) { if (kind != null) { String kindName = StringUtil.capitalize(kind.toString().toLowerCase(Locale.US)); setText(kindName); } } }; } private void installRunKindComboBox() { myRunKindComboBox.removeAllItems(); myRunKindComboBox.setRenderer(getRunKindListCellRendererWrapper()); for (GoApplicationConfiguration.Kind kind : GoApplicationConfiguration.Kind.values()) { myRunKindComboBox.addItem(kind); } myRunKindComboBox.addActionListener(e -> onRunKindChanged()); } @NotNull @Override protected JComponent createEditor() { return myComponent; } @Override protected void disposeEditor() { myComponent.setVisible(false); } } ================================================ FILE: src/com/goide/runconfig/ui/GoCommonSettingsPanel.form ================================================
    ================================================ FILE: src/com/goide/runconfig/ui/GoCommonSettingsPanel.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.ui; import com.goide.runconfig.GoRunConfigurationBase; import com.goide.runconfig.GoRunUtil; import com.intellij.application.options.ModulesComboBox; import com.intellij.execution.configuration.EnvironmentVariablesTextFieldWithBrowseButton; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.ui.RawCommandLineEditor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class GoCommonSettingsPanel extends JPanel { private RawCommandLineEditor myGoToolParamsField; private RawCommandLineEditor myParamsField; private TextFieldWithBrowseButton myWorkingDirectoryField; private EnvironmentVariablesTextFieldWithBrowseButton myEnvironmentField; private ModulesComboBox myModulesComboBox; @SuppressWarnings("unused") private JPanel myRoot; public void init(@NotNull Project project) { GoRunUtil.installFileChooser(project, myWorkingDirectoryField, true); myGoToolParamsField.setDialogCaption("Go tool arguments"); myParamsField.setDialogCaption("Program arguments"); } public void resetEditorFrom(@NotNull GoRunConfigurationBase configuration) { myModulesComboBox.setModules(configuration.getValidModules()); myModulesComboBox.setSelectedModule(configuration.getConfigurationModule().getModule()); myGoToolParamsField.setText(configuration.getGoToolParams()); myParamsField.setText(configuration.getParams()); myWorkingDirectoryField.setText(configuration.getWorkingDirectory()); myEnvironmentField.setEnvs(configuration.getCustomEnvironment()); myEnvironmentField.setPassParentEnvs(configuration.isPassParentEnvironment()); } public void applyEditorTo(@NotNull GoRunConfigurationBase configuration) { configuration.setModule(myModulesComboBox.getSelectedModule()); configuration.setGoParams(myGoToolParamsField.getText()); configuration.setParams(myParamsField.getText()); configuration.setWorkingDirectory(myWorkingDirectoryField.getText()); configuration.setCustomEnvironment(myEnvironmentField.getEnvs()); configuration.setPassParentEnvironment(myEnvironmentField.isPassParentEnvs()); } @Nullable public Module getSelectedModule() { return myModulesComboBox.getSelectedModule(); } } ================================================ FILE: src/com/goide/runconfig/ui/GoRunFileConfigurationEditorForm.form ================================================
    ================================================ FILE: src/com/goide/runconfig/ui/GoRunFileConfigurationEditorForm.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.ui; import com.goide.runconfig.GoRunUtil; import com.goide.runconfig.file.GoRunFileConfiguration; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class GoRunFileConfigurationEditorForm extends SettingsEditor { private JPanel myComponent; private TextFieldWithBrowseButton myFileField; private GoCommonSettingsPanel myCommonSettingsPanel; public GoRunFileConfigurationEditorForm(@NotNull Project project) { myCommonSettingsPanel.init(project); GoRunUtil.installGoWithMainFileChooser(project, myFileField); } @Override protected void resetEditorFrom(GoRunFileConfiguration configuration) { myFileField.setText(configuration.getFilePath()); myCommonSettingsPanel.resetEditorFrom(configuration); } @Override protected void applyEditorTo(GoRunFileConfiguration configuration) throws ConfigurationException { configuration.setFilePath(myFileField.getText()); myCommonSettingsPanel.applyEditorTo(configuration); } @NotNull @Override protected JComponent createEditor() { return myComponent; } } ================================================ FILE: src/com/goide/sdk/GoEnvironmentGoPathModificationTracker.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoEnvironmentUtil; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.Collection; import java.util.Set; public class GoEnvironmentGoPathModificationTracker { private final Set pathsToTrack = ContainerUtil.newHashSet(); private final Collection goPathRoots = ContainerUtil.newLinkedHashSet(); public GoEnvironmentGoPathModificationTracker() { String goPath = GoEnvironmentUtil.retrieveGoPathFromEnvironment(); if (goPath != null) { String home = SystemProperties.getUserHome(); for (String s : StringUtil.split(goPath, File.pathSeparator)) { if (s.contains("$HOME")) { if (home == null) { continue; } s = s.replaceAll("\\$HOME", home); } pathsToTrack.add(s); } } recalculateFiles(); VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override public void fileCreated(@NotNull VirtualFileEvent event) { handleEvent(event); } @Override public void fileDeleted(@NotNull VirtualFileEvent event) { handleEvent(event); } @Override public void fileMoved(@NotNull VirtualFileMoveEvent event) { handleEvent(event); } @Override public void fileCopied(@NotNull VirtualFileCopyEvent event) { handleEvent(event); } private void handleEvent(VirtualFileEvent event) { if (pathsToTrack.contains(event.getFile().getPath())) { recalculateFiles(); } } }); } private void recalculateFiles() { Collection result = ContainerUtil.newLinkedHashSet(); for (String path : pathsToTrack) { ContainerUtil.addIfNotNull(result, LocalFileSystem.getInstance().findFileByPath(path)); } updateGoPathRoots(result); } private synchronized void updateGoPathRoots(Collection newRoots) { goPathRoots.clear(); goPathRoots.addAll(newRoots); } private synchronized Collection getGoPathRoots() { return goPathRoots; } public static Collection getGoEnvironmentGoPathRoots() { return ServiceManager.getService(GoEnvironmentGoPathModificationTracker.class).getGoPathRoots(); } } ================================================ FILE: src/com/goide/sdk/GoIdeaSdkService.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoModuleType; import com.intellij.ProjectTopics; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoIdeaSdkService extends GoSdkService { public GoIdeaSdkService(@NotNull Project project) { super(project); myProject.getMessageBus().connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { @Override public void rootsChanged(ModuleRootEvent event) { incModificationCount(); } }); } @Override public String getSdkHomePath(@Nullable Module module) { ComponentManager holder = ObjectUtils.notNull(module, myProject); return CachedValuesManager.getManager(myProject).getCachedValue(holder, () -> { Sdk sdk = getGoSdk(module); return CachedValueProvider.Result.create(sdk != null ? sdk.getHomePath() : null, this); }); } @Nullable @Override public String getSdkVersion(@Nullable Module module) { String parentVersion = super.getSdkVersion(module); if (parentVersion != null) { return parentVersion; } ComponentManager holder = ObjectUtils.notNull(module, myProject); return CachedValuesManager.getManager(myProject).getCachedValue(holder, () -> { Sdk sdk = getGoSdk(module); return CachedValueProvider.Result.create(sdk != null ? sdk.getVersionString() : null, this); }); } @Override public void chooseAndSetSdk(@Nullable Module module) { Sdk projectSdk = ProjectSettingsService.getInstance(myProject).chooseAndSetSdk(); if (projectSdk == null && module != null) { ApplicationManager.getApplication().runWriteAction(() -> { if (!module.isDisposed()) { ModuleRootModificationUtil.setSdkInherited(module); } }); } } @Override public boolean isGoModule(@Nullable Module module) { return super.isGoModule(module) && ModuleUtil.getModuleType(module) == GoModuleType.getInstance(); } private Sdk getGoSdk(@Nullable Module module) { if (module != null) { Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); if (sdk != null && sdk.getSdkType() instanceof GoSdkType) { return sdk; } } Sdk sdk = ProjectRootManager.getInstance(myProject).getProjectSdk(); return sdk != null && sdk.getSdkType() instanceof GoSdkType ? sdk : null; } } ================================================ FILE: src/com/goide/sdk/GoPackageUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoConstants; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.goide.psi.GoFile; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; import java.util.List; public class GoPackageUtil { private static final Key>> PACKAGES_CACHE = Key.create("packages_cache"); private static final Key>> PACKAGES_TEST_TRIMMED_CACHE = Key.create("packages_test_trimmed_cache"); private GoPackageUtil() {} @Contract("null -> false") public static boolean isBuiltinPackage(@Nullable PsiFileSystemItem directory) { return directory instanceof PsiDirectory && GoConstants.BUILTIN_PACKAGE_NAME.equals(directory.getName()) && GoConstants.BUILTIN_PACKAGE_NAME.equals(GoSdkUtil.getImportPath((PsiDirectory)directory, false)); } @NotNull public static List getAllPackageFiles(@NotNull GoFile file) { String packageName = file.getPackageName(); PsiDirectory parent = file.getParent(); if (parent == null || StringUtil.isEmpty(packageName)) return ContainerUtil.list(file); return getAllPackageFiles(parent, packageName); } @NotNull public static List getAllPackageFiles(@Nullable PsiDirectory directory, @Nullable String packageName) { if (directory == null) { return Collections.emptyList(); } PsiElement[] children = directory.getChildren(); List files = ContainerUtil.newArrayListWithCapacity(children.length); for (PsiElement element : children) { if (element instanceof GoFile && (packageName == null || Comparing.equal(((GoFile)element).getPackageName(), packageName))) { files.add((GoFile)element); } } return files; } @NotNull public static GlobalSearchScope packageScope(@NotNull GoFile file) { List files = getAllPackageFiles(file); return GlobalSearchScope.filesWithLibrariesScope(file.getProject(), ContainerUtil.map(files, PsiFile::getVirtualFile)); } @NotNull public static GlobalSearchScope packageScope(@NotNull PsiDirectory psiDirectory, @Nullable String packageName) { List files = getAllPackageFiles(psiDirectory, packageName); return GlobalSearchScope.filesWithLibrariesScope(psiDirectory.getProject(), ContainerUtil.map(files, PsiFile::getVirtualFile)); } @NotNull public static Collection getAllPackagesInDirectory(@Nullable PsiDirectory dir, @Nullable Module contextModule, boolean trimTestSuffices) { if (dir == null) return Collections.emptyList(); if (contextModule != null) { return getAllPackagesInDirectoryInner(dir, contextModule, trimTestSuffices); } Key>> key = trimTestSuffices ? PACKAGES_TEST_TRIMMED_CACHE : PACKAGES_CACHE; return CachedValuesManager.getManager(dir.getProject()).getCachedValue(dir, key, () -> { Module module = ModuleUtilCore.findModuleForPsiElement(dir); GoBuildTargetSettings buildTargetSettings = module != null ? GoModuleSettings.getInstance(module).getBuildTargetSettings() : null; // todo[zolotov]: implement package modification tracker return buildTargetSettings != null ? CachedValueProvider.Result.create(getAllPackagesInDirectoryInner(dir, module, trimTestSuffices), dir, buildTargetSettings) : CachedValueProvider.Result.create(getAllPackagesInDirectoryInner(dir, null, trimTestSuffices), dir); }, false); } @NotNull private static Collection getAllPackagesInDirectoryInner(@NotNull PsiDirectory dir, @Nullable Module contextModule, boolean trimTestSuffices) { Collection set = ContainerUtil.newLinkedHashSet(); for (PsiFile file : dir.getFiles()) { if (file instanceof GoFile && GoPsiImplUtil.allowed(file, null, contextModule)) { String name = trimTestSuffices ? ((GoFile)file).getCanonicalPackageName() : ((GoFile)file).getPackageName(); if (StringUtil.isNotEmpty(name)) { set.add(name); } } } return set; } @Nullable public static VirtualFile findByImportPath(@NotNull String importPath, @NotNull Project project, @Nullable Module module) { if (importPath.isEmpty()) { return null; } importPath = FileUtil.toSystemIndependentName(importPath); for (VirtualFile root : GoSdkUtil.getSourcesPathsToLookup(project, module)) { VirtualFile file = root.findFileByRelativePath(importPath); if (file != null) { return file; } } return null; } } ================================================ FILE: src/com/goide/sdk/GoSdkLibraryPresentationProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoIcons; import com.intellij.openapi.roots.libraries.DummyLibraryProperties; import com.intellij.openapi.roots.libraries.LibraryKind; import com.intellij.openapi.roots.libraries.LibraryPresentationProvider; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public class GoSdkLibraryPresentationProvider extends LibraryPresentationProvider { private static final LibraryKind KIND = LibraryKind.create("go"); public GoSdkLibraryPresentationProvider() { super(KIND); } @Override @Nullable public Icon getIcon() { return GoIcons.ICON; } @Override @Nullable public DummyLibraryProperties detect(@NotNull List classesRoots) { for (VirtualFile root : classesRoots) { if (GoSmallIDEsSdkService.isGoSdkLibRoot(root) && !GoSdkService.isAppEngineSdkPath(GoSdkService.libraryRootToSdkPath(root))) { return DummyLibraryProperties.INSTANCE; } } return null; } } ================================================ FILE: src/com/goide/sdk/GoSdkService.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoConstants; import com.goide.GoEnvironmentUtil; import com.intellij.execution.configurations.PathEnvironmentVariableUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SimpleModificationTracker; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.util.Set; public abstract class GoSdkService extends SimpleModificationTracker { public static final Logger LOG = Logger.getInstance(GoSdkService.class); private static final Set FEDORA_SUBDIRECTORIES = ContainerUtil.newHashSet("linux_amd64", "linux_386", "linux_arm"); private static String ourTestSdkVersion; @NotNull protected final Project myProject; protected GoSdkService(@NotNull Project project) { myProject = project; } public static GoSdkService getInstance(@NotNull Project project) { return ServiceManager.getService(project, GoSdkService.class); } @Nullable public abstract String getSdkHomePath(@Nullable Module module); @NotNull public static String libraryRootToSdkPath(@NotNull VirtualFile root) { return VfsUtilCore.urlToPath(StringUtil.trimEnd(StringUtil.trimEnd(StringUtil.trimEnd(root.getUrl(), "src/pkg"), "src"), "/")); } @Nullable public String getSdkVersion(@Nullable Module module) { return ourTestSdkVersion; } public boolean isAppEngineSdk(@Nullable Module module) { return isAppEngineSdkPath(getSdkHomePath(module)); } public static boolean isAppEngineSdkPath(@Nullable String path) { return isLooksLikeAppEngineSdkPath(path) && getGaeExecutablePath(path) != null; } private static boolean isLooksLikeAppEngineSdkPath(@Nullable String path) { return path != null && path.endsWith(GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH); } public abstract void chooseAndSetSdk(@Nullable Module module); /** * Use this method in order to check whether the method is appropriate for providing Go-specific code insight */ @Contract("null -> false") public boolean isGoModule(@Nullable Module module) { return module != null && !module.isDisposed(); } @Nullable public Configurable createSdkConfigurable() { return null; } @Nullable public String getGoExecutablePath(@Nullable Module module) { return getGoExecutablePath(getSdkHomePath(module)); } public static String getGoExecutablePath(@Nullable String sdkHomePath) { if (sdkHomePath != null) { if (isLooksLikeAppEngineSdkPath(sdkHomePath)) { LOG.debug("Looks like GAE sdk at " + sdkHomePath); String executablePath = getGaeExecutablePath(sdkHomePath); if (executablePath != null) return executablePath; } File binDirectory = new File(sdkHomePath, "bin"); if (!binDirectory.exists() && SystemInfo.isLinux) { LOG.debug(sdkHomePath + "/bin doesn't exist, checking linux-specific paths"); // failed to define executable path in old linux and old go File goFromPath = PathEnvironmentVariableUtil.findInPath(GoConstants.GO_EXECUTABLE_NAME); if (goFromPath != null && goFromPath.exists()) { LOG.debug("Go executable found at " + goFromPath.getAbsolutePath()); return goFromPath.getAbsolutePath(); } } String executableName = GoEnvironmentUtil.getBinaryFileNameForPath(GoConstants.GO_EXECUTABLE_NAME); String executable = FileUtil.join(sdkHomePath, "bin", executableName); if (!new File(executable).exists() && SystemInfo.isLinux) { LOG.debug(executable + " doesn't exists. Looking for binaries in fedora-specific directories"); // fedora for (String directory : FEDORA_SUBDIRECTORIES) { File file = new File(binDirectory, directory); if (file.exists() && file.isDirectory()) { LOG.debug("Go executable found at " + file.getAbsolutePath()); return FileUtil.join(file.getAbsolutePath(), executableName); } } } LOG.debug("Go executable found at " + executable); return executable; } return null; } @Nullable private static String getGaeExecutablePath(@NotNull String sdkHomePath) { String goExecutablePath = PathUtil.toSystemIndependentName(sdkHomePath); goExecutablePath = StringUtil.trimEnd(goExecutablePath, GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH); boolean gcloudInstallation = goExecutablePath.endsWith(GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH); if (gcloudInstallation) { LOG.debug("Detected gcloud GAE installation at " + goExecutablePath); goExecutablePath = FileUtil.join(StringUtil.trimEnd(goExecutablePath, GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH), "bin"); } String executablePath = FileUtil.join(goExecutablePath, GoEnvironmentUtil.getGaeExecutableFileName(gcloudInstallation)); return new File(executablePath).exists() ? executablePath : null; } @TestOnly public static void setTestingSdkVersion(@Nullable String version, @NotNull Disposable disposable) { ourTestSdkVersion = version; Disposer.register(disposable, () -> { //noinspection AssignmentToStaticFieldFromInstanceMethod ourTestSdkVersion = null; }); } } ================================================ FILE: src/com/goide/sdk/GoSdkType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoConstants; import com.goide.GoIcons; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.vfs.VirtualFile; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; public class GoSdkType extends SdkType { public GoSdkType() { super(GoConstants.SDK_TYPE_ID); } @NotNull public static GoSdkType getInstance() { return SdkType.findInstance(GoSdkType.class); } @NotNull @Override public Icon getIcon() { return GoIcons.ICON; } @NotNull @Override public Icon getIconForAddAction() { return getIcon(); } @Nullable @Override public String suggestHomePath() { VirtualFile suggestSdkDirectory = GoSdkUtil.suggestSdkDirectory(); return suggestSdkDirectory != null ? suggestSdkDirectory.getPath() : null; } @Override public boolean isValidSdkHome(@NotNull String path) { GoSdkService.LOG.debug("Validating sdk path: " + path); String executablePath = GoSdkService.getGoExecutablePath(path); if (executablePath == null) { GoSdkService.LOG.debug("Go executable is not found: "); return false; } if (!new File(executablePath).canExecute()) { GoSdkService.LOG.debug("Go binary cannot be executed: " + path); return false; } if (getVersionString(path) != null) { GoSdkService.LOG.debug("Cannot retrieve version for sdk: " + path); return true; } return false; } @NotNull @Override public String adjustSelectedSdkHome(@NotNull String homePath) { return GoSdkUtil.adjustSdkPath(homePath); } @NotNull @Override public String suggestSdkName(@Nullable String currentSdkName, @NotNull String sdkHome) { String version = getVersionString(sdkHome); if (version == null) { return "Unknown Go version at " + sdkHome; } return "Go " + version; } @Nullable @Override public String getVersionString(@NotNull String sdkHome) { return GoSdkUtil.retrieveGoVersion(sdkHome); } @Nullable @Override public String getDefaultDocumentationUrl(@NotNull Sdk sdk) { return null; } @Nullable @Override public AdditionalDataConfigurable createAdditionalDataConfigurable(@NotNull SdkModel sdkModel, @NotNull SdkModificator sdkModificator) { return null; } @Override public void saveAdditionalData(@NotNull SdkAdditionalData additionalData, @NotNull Element additional) { } @NotNull @NonNls @Override public String getPresentableName() { return "Go SDK"; } @Override public void setupSdkPaths(@NotNull Sdk sdk) { String versionString = sdk.getVersionString(); if (versionString == null) throw new RuntimeException("SDK version is not defined"); SdkModificator modificator = sdk.getSdkModificator(); String path = sdk.getHomePath(); if (path == null) return; modificator.setHomePath(path); for (VirtualFile file : GoSdkUtil.getSdkDirectoriesToAttach(path, versionString)) { modificator.addRoot(file, OrderRootType.CLASSES); modificator.addRoot(file, OrderRootType.SOURCES); } modificator.commitChanges(); } } ================================================ FILE: src/com/goide/sdk/GoSdkUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoConstants; import com.goide.GoEnvironmentUtil; import com.goide.appengine.YamlFilesModificationTracker; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoLibrariesService; import com.goide.psi.GoFile; import com.intellij.execution.configurations.PathEnvironmentVariableUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.VersionComparatorUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.intellij.util.containers.ContainerUtil.newLinkedHashSet; public class GoSdkUtil { private static final Pattern GO_VERSION_PATTERN = Pattern.compile("[tT]heVersion\\s*=\\s*`go([\\d.]+\\w+(\\d+)?)`"); private static final Pattern GAE_VERSION_PATTERN = Pattern.compile("[tT]heVersion\\s*=\\s*`go([\\d.]+)( \\(appengine-[\\d.]+\\))?`"); private static final Pattern GO_DEVEL_VERSION_PATTERN = Pattern.compile("[tT]heVersion\\s*=\\s*`(devel.*)`"); private static final Key ZVERSION_DATA_KEY = Key.create("GO_ZVERSION_KEY"); private GoSdkUtil() {} @Nullable public static VirtualFile getSdkSrcDir(@NotNull Project project, @Nullable Module module) { if (module != null) { return CachedValuesManager.getManager(project).getCachedValue(module, () -> { GoSdkService sdkService = GoSdkService.getInstance(module.getProject()); return CachedValueProvider.Result.create(getInnerSdkSrcDir(sdkService, module), sdkService); }); } return CachedValuesManager.getManager(project).getCachedValue(project, () -> { GoSdkService sdkService = GoSdkService.getInstance(project); return CachedValueProvider.Result.create(getInnerSdkSrcDir(sdkService, null), sdkService); }); } @Nullable private static VirtualFile getInnerSdkSrcDir(@NotNull GoSdkService sdkService, @Nullable Module module) { String sdkHomePath = sdkService.getSdkHomePath(module); String sdkVersionString = sdkService.getSdkVersion(module); return sdkHomePath != null && sdkVersionString != null ? getSdkSrcDir(sdkHomePath, sdkVersionString) : null; } @Nullable private static VirtualFile getSdkSrcDir(@NotNull String sdkPath, @NotNull String sdkVersion) { String srcPath = getSrcLocation(sdkVersion); VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.pathToUrl(FileUtil.join(sdkPath, srcPath))); return file != null && file.isDirectory() ? file : null; } @Nullable public static GoFile findBuiltinFile(@NotNull PsiElement context) { Project project = context.getProject(); // it's important to ask module on file, otherwise module won't be found for elements in libraries files [zolotov] Module moduleFromContext = ModuleUtilCore.findModuleForPsiElement(context.getContainingFile()); if (moduleFromContext == null) { for (Module module : ModuleManager.getInstance(project).getModules()) { if (GoSdkService.getInstance(project).isGoModule(module)) { moduleFromContext = module; break; } } } Module module = moduleFromContext; UserDataHolder holder = ObjectUtils.notNull(module, project); VirtualFile file = CachedValuesManager.getManager(context.getProject()).getCachedValue(holder, () -> { VirtualFile sdkSrcDir = getSdkSrcDir(project, module); VirtualFile result = sdkSrcDir != null ? sdkSrcDir.findFileByRelativePath(GoConstants.BUILTIN_FILE_PATH) : null; return CachedValueProvider.Result.create(result, getSdkAndLibrariesCacheDependencies(project, module, result)); }); if (file == null) return null; PsiFile psiBuiltin = context.getManager().findFile(file); return psiBuiltin instanceof GoFile ? (GoFile)psiBuiltin : null; } @Nullable public static VirtualFile findExecutableInGoPath(@NotNull String executableName, @NotNull Project project, @Nullable Module module) { executableName = GoEnvironmentUtil.getBinaryFileNameForPath(executableName); Collection roots = getGoPathRoots(project, module); for (VirtualFile file : roots) { VirtualFile child = VfsUtil.findRelativeFile(file, "bin", executableName); if (child != null) return child; } File fromPath = PathEnvironmentVariableUtil.findInPath(executableName); return fromPath != null ? VfsUtil.findFileByIoFile(fromPath, true) : null; } /** * @return concatenation of {@link this#getSdkSrcDir(Project, Module)} and {@link this#getGoPathSources(Project, Module)} */ @NotNull public static LinkedHashSet getSourcesPathsToLookup(@NotNull Project project, @Nullable Module module) { LinkedHashSet sdkAndGoPath = newLinkedHashSet(); ContainerUtil.addIfNotNull(sdkAndGoPath, getSdkSrcDir(project, module)); ContainerUtil.addAllNotNull(sdkAndGoPath, getGoPathSources(project, module)); return sdkAndGoPath; } @NotNull public static LinkedHashSet getVendoringAwareSourcesPathsToLookup(@NotNull Project project, @Nullable Module module, @Nullable VirtualFile contextFile) { LinkedHashSet sdkAndGoPath = getSourcesPathsToLookup(project, module); if (contextFile != null) { Collection vendorDirectories = collectVendorDirectories(contextFile, sdkAndGoPath); if (!vendorDirectories.isEmpty()) { LinkedHashSet result = newLinkedHashSet(vendorDirectories); result.addAll(sdkAndGoPath); return result; } } return sdkAndGoPath; } @NotNull private static Collection collectVendorDirectories(@Nullable VirtualFile contextDirectory, @NotNull Set sourceRoots) { if (contextDirectory == null) { return Collections.emptyList(); } Collection vendorDirectories = ContainerUtil.newArrayList(); VirtualFile directory = contextDirectory; while (directory != null) { VirtualFile vendorDirectory = directory.findChild(GoConstants.VENDOR); if (vendorDirectory != null && vendorDirectory.isDirectory()) { vendorDirectories.add(vendorDirectory); } if (sourceRoots.contains(directory)) { break; } directory = directory.getParent(); } return vendorDirectories; } @NotNull private static Collection getGoPathRoots(@NotNull Project project, @Nullable Module module) { Collection roots = ContainerUtil.newArrayList(); if (GoApplicationLibrariesService.getInstance().isUseGoPathFromSystemEnvironment()) { roots.addAll(getGoPathsRootsFromEnvironment()); } roots.addAll(module != null ? GoLibrariesService.getUserDefinedLibraries(module) : GoLibrariesService.getUserDefinedLibraries(project)); return roots; } @NotNull public static Collection getGoPathSources(@NotNull Project project, @Nullable Module module) { if (module != null) { return CachedValuesManager.getManager(project).getCachedValue(module, () -> { Collection result = newLinkedHashSet(); Project project1 = module.getProject(); GoSdkService sdkService = GoSdkService.getInstance(project1); if (sdkService.isAppEngineSdk(module)) { ContainerUtil.addAllNotNull(result, ContainerUtil.mapNotNull(YamlFilesModificationTracker.getYamlFiles(project1, module), VirtualFile::getParent)); } result.addAll(getInnerGoPathSources(project1, module)); return CachedValueProvider.Result .create(result, getSdkAndLibrariesCacheDependencies(project1, module, YamlFilesModificationTracker.getInstance(project1))); }); } return CachedValuesManager.getManager(project).getCachedValue(project, (CachedValueProvider>)() -> CachedValueProvider.Result .create(getInnerGoPathSources(project, null), getSdkAndLibrariesCacheDependencies(project, null, YamlFilesModificationTracker.getInstance(project)))); } @NotNull private static List getInnerGoPathSources(@NotNull Project project, @Nullable Module module) { return ContainerUtil.mapNotNull(getGoPathRoots(project, module), new RetrieveSubDirectoryOrSelfFunction("src")); } @NotNull private static Collection getGoPathBins(@NotNull Project project, @Nullable Module module) { Collection result = newLinkedHashSet(ContainerUtil.mapNotNull(getGoPathRoots(project, module), new RetrieveSubDirectoryOrSelfFunction("bin"))); String executableGoPath = GoSdkService.getInstance(project).getGoExecutablePath(module); if (executableGoPath != null) { VirtualFile executable = VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.pathToUrl(executableGoPath)); if (executable != null) ContainerUtil.addIfNotNull(result, executable.getParent()); } return result; } /** * Retrieves root directories from GOPATH env-variable. * This method doesn't consider user defined libraries, * for that case use {@link {@link this#getGoPathRoots(Project, Module)} */ @NotNull public static Collection getGoPathsRootsFromEnvironment() { return GoEnvironmentGoPathModificationTracker.getGoEnvironmentGoPathRoots(); } @NotNull public static String retrieveGoPath(@NotNull Project project, @Nullable Module module) { return StringUtil.join(ContainerUtil.map(getGoPathRoots(project, module), VirtualFile::getPath), File.pathSeparator); } @NotNull public static String retrieveEnvironmentPathForGo(@NotNull Project project, @Nullable Module module) { return StringUtil.join(ContainerUtil.map(getGoPathBins(project, module), VirtualFile::getPath), File.pathSeparator); } @NotNull private static String getSrcLocation(@NotNull String version) { if (ApplicationManager.getApplication().isUnitTestMode()) { return "src/pkg"; } if (version.startsWith("devel")) { return "src"; } if (version.length() > 2 && StringUtil.parseDouble(version.substring(0, 3), 1.4) < 1.4) { return "src/pkg"; } return "src"; } public static int compareVersions(@NotNull String lhs, @NotNull String rhs) { return VersionComparatorUtil.compare(lhs, rhs); } @Nullable @Contract("null, _ -> null") public static String getImportPath(@Nullable PsiDirectory psiDirectory, boolean withVendoring) { if (psiDirectory == null) { return null; } return CachedValuesManager.getCachedValue(psiDirectory, withVendoring ? new CachedVendoredImportPathProvider(psiDirectory) : new CachedImportPathProviderImpl(psiDirectory)); } @Nullable private static String getPathRelativeToSdkAndLibrariesAndVendor(@NotNull PsiDirectory psiDirectory, boolean withVendoring) { VirtualFile file = psiDirectory.getVirtualFile(); Project project = psiDirectory.getProject(); Module module = ModuleUtilCore.findModuleForPsiElement(psiDirectory); LinkedHashSet sourceRoots = withVendoring ? getVendoringAwareSourcesPathsToLookup(project, module, file) : getSourcesPathsToLookup(project, module); String relativePath = getRelativePathToRoots(file, sourceRoots); if (relativePath != null) { return relativePath; } String filePath = file.getPath(); int src = filePath.lastIndexOf("/src/"); if (src > -1) { return filePath.substring(src + 5); } return null; } @Nullable public static String getRelativePathToRoots(@NotNull VirtualFile file, @NotNull Collection sourceRoots) { for (VirtualFile root : sourceRoots) { String relativePath = VfsUtilCore.getRelativePath(file, root, '/'); if (StringUtil.isNotEmpty(relativePath)) { return relativePath; } } return null; } @Nullable public static VirtualFile suggestSdkDirectory() { if (SystemInfo.isWindows) { return ObjectUtils.chooseNotNull(LocalFileSystem.getInstance().findFileByPath("C:\\Go"), LocalFileSystem.getInstance().findFileByPath("C:\\cygwin")); } if (SystemInfo.isMac || SystemInfo.isLinux) { String fromEnv = suggestSdkDirectoryPathFromEnv(); if (fromEnv != null) { return LocalFileSystem.getInstance().findFileByPath(fromEnv); } VirtualFile usrLocal = LocalFileSystem.getInstance().findFileByPath("/usr/local/go"); if (usrLocal != null) return usrLocal; } if (SystemInfo.isMac) { String macPorts = "/opt/local/lib/go"; String homeBrew = "/usr/local/Cellar/go"; File file = FileUtil.findFirstThatExist(macPorts, homeBrew); if (file != null) { return LocalFileSystem.getInstance().findFileByIoFile(file); } } return null; } @Nullable private static String suggestSdkDirectoryPathFromEnv() { File fileFromPath = PathEnvironmentVariableUtil.findInPath("go"); if (fileFromPath != null) { File canonicalFile; try { canonicalFile = fileFromPath.getCanonicalFile(); String path = canonicalFile.getPath(); if (path.endsWith("bin/go")) { return StringUtil.trimEnd(path, "bin/go"); } } catch (IOException ignore) { } } return null; } @Nullable public static String parseGoVersion(@NotNull String text) { Matcher matcher = GO_VERSION_PATTERN.matcher(text); if (matcher.find()) { return matcher.group(1); } matcher = GAE_VERSION_PATTERN.matcher(text); if (matcher.find()) { return matcher.group(1) + matcher.group(2); } matcher = GO_DEVEL_VERSION_PATTERN.matcher(text); if (matcher.find()) { return matcher.group(1); } return null; } @Nullable public static String retrieveGoVersion(@NotNull String sdkPath) { try { VirtualFile sdkRoot = VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.pathToUrl(sdkPath)); if (sdkRoot != null) { String cachedVersion = sdkRoot.getUserData(ZVERSION_DATA_KEY); if (cachedVersion != null) { return !cachedVersion.isEmpty() ? cachedVersion : null; } VirtualFile versionFile = sdkRoot.findFileByRelativePath("src/" + GoConstants.GO_VERSION_NEW_FILE_PATH); if (versionFile == null) { versionFile = sdkRoot.findFileByRelativePath("src/" + GoConstants.GO_VERSION_FILE_PATH); } if (versionFile == null) { versionFile = sdkRoot.findFileByRelativePath("src/pkg/" + GoConstants.GO_VERSION_FILE_PATH); } if (versionFile != null) { String text = VfsUtilCore.loadText(versionFile); String version = parseGoVersion(text); if (version == null) { GoSdkService.LOG.debug("Cannot retrieve go version from zVersion file: " + text); } sdkRoot.putUserData(ZVERSION_DATA_KEY, StringUtil.notNullize(version)); return version; } else { GoSdkService.LOG.debug("Cannot find go version file in sdk path: " + sdkPath); } } } catch (IOException e) { GoSdkService.LOG.debug("Cannot retrieve go version from sdk path: " + sdkPath, e); } return null; } @NotNull public static String adjustSdkPath(@NotNull String path) { if (new File(path, GoConstants.LIB_EXEC_DIRECTORY).exists()) { path += File.separatorChar + GoConstants.LIB_EXEC_DIRECTORY; } File possibleGCloudSdk = new File(path, GoConstants.GCLOUD_APP_ENGINE_DIRECTORY_PATH); if (possibleGCloudSdk.exists() && possibleGCloudSdk.isDirectory()) { if (isAppEngine(possibleGCloudSdk.getAbsolutePath())) { return possibleGCloudSdk.getAbsolutePath() + GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH; } } return isAppEngine(path) ? path + GoConstants.APP_ENGINE_GO_ROOT_DIRECTORY_PATH : path; } private static boolean isAppEngine(@NotNull String path) { return new File(path, GoConstants.APP_ENGINE_MARKER_FILE).exists(); } @NotNull public static Collection getSdkDirectoriesToAttach(@NotNull String sdkPath, @NotNull String versionString) { // scr is enough at the moment, possible process binaries from pkg return ContainerUtil.createMaybeSingletonList(getSdkSrcDir(sdkPath, versionString)); } @NotNull private static Collection getSdkAndLibrariesCacheDependencies(@NotNull Project project, @Nullable Module module, Object... extra) { Collection dependencies = ContainerUtil.newArrayList((Object[])GoLibrariesService.getModificationTrackers(project, module)); ContainerUtil.addAllNotNull(dependencies, GoSdkService.getInstance(project)); ContainerUtil.addAllNotNull(dependencies, extra); return dependencies; } @NotNull public static Collection getGoModules(@NotNull Project project) { if (project.isDefault()) return Collections.emptyList(); GoSdkService sdkService = GoSdkService.getInstance(project); return ContainerUtil.filter(ModuleManager.getInstance(project).getModules(), sdkService::isGoModule); } public static boolean isUnreachableInternalPackage(@NotNull VirtualFile targetDirectory, @NotNull VirtualFile referenceContextFile, @NotNull Set sourceRoots) { return isUnreachablePackage(GoConstants.INTERNAL, targetDirectory, referenceContextFile, sourceRoots); } public static boolean isUnreachableVendoredPackage(@NotNull VirtualFile targetDirectory, @NotNull VirtualFile referenceContextFile, @NotNull Set sourceRoots) { return isUnreachablePackage(GoConstants.VENDOR, targetDirectory, referenceContextFile, sourceRoots); } @Nullable public static VirtualFile findParentDirectory(@Nullable VirtualFile file, @NotNull Set sourceRoots, @NotNull String name) { if (file == null) { return null; } VirtualFile currentFile = file.isDirectory() ? file : file.getParent(); while (currentFile != null && !sourceRoots.contains(currentFile)) { if (currentFile.isDirectory() && name.equals(currentFile.getName())) { return currentFile; } currentFile = currentFile.getParent(); } return null; } private static boolean isUnreachablePackage(@NotNull String unreachableDirectoryName, @NotNull VirtualFile targetDirectory, @NotNull VirtualFile referenceContextFile, @NotNull Set sourceRoots) { VirtualFile directory = findParentDirectory(targetDirectory, sourceRoots, unreachableDirectoryName); VirtualFile parent = directory != null ? directory.getParent() : null; return directory != null && !VfsUtilCore.isAncestor(parent, referenceContextFile, false); } private static class RetrieveSubDirectoryOrSelfFunction implements Function { @NotNull private final String mySubdirName; public RetrieveSubDirectoryOrSelfFunction(@NotNull String subdirName) { mySubdirName = subdirName; } @Override public VirtualFile fun(VirtualFile file) { return file == null || FileUtil.namesEqual(mySubdirName, file.getName()) ? file : file.findChild(mySubdirName); } } private abstract static class CachedImportPathProvider implements CachedValueProvider { private final PsiDirectory myPsiDirectory; private final boolean myWithVendoring; public CachedImportPathProvider(@NotNull PsiDirectory psiDirectory, boolean vendoring) { myPsiDirectory = psiDirectory; myWithVendoring = vendoring; } @Nullable @Override public Result compute() { String path = getPathRelativeToSdkAndLibrariesAndVendor(myPsiDirectory, myWithVendoring); Module module = ModuleUtilCore.findModuleForPsiElement(myPsiDirectory); return Result.create(path, getSdkAndLibrariesCacheDependencies(myPsiDirectory.getProject(), module, myPsiDirectory)); } } private static class CachedImportPathProviderImpl extends CachedImportPathProvider { public CachedImportPathProviderImpl(@NotNull PsiDirectory psiDirectory) { super(psiDirectory, false); } } private static class CachedVendoredImportPathProvider extends CachedImportPathProvider { public CachedVendoredImportPathProvider(@NotNull PsiDirectory psiDirectory) { super(psiDirectory, true); } } } ================================================ FILE: src/com/goide/sdk/GoSmallIDEsSdkService.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoConstants; import com.goide.configuration.GoSdkConfigurable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoSmallIDEsSdkService extends GoSdkService { public static final String LIBRARY_NAME = "Go SDK"; public GoSmallIDEsSdkService(@NotNull Project project) { super(project); } @Nullable @Override public String getSdkHomePath(@Nullable Module module) { ComponentManager holder = ObjectUtils.notNull(module, myProject); return CachedValuesManager.getManager(myProject).getCachedValue(holder, () -> CachedValueProvider.Result .create(ApplicationManager.getApplication().runReadAction(new Computable() { @Nullable @Override public String compute() { LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTable(myProject); for (Library library : table.getLibraries()) { String libraryName = library.getName(); if (libraryName != null && libraryName.startsWith(LIBRARY_NAME)) { for (VirtualFile root : library.getFiles(OrderRootType.CLASSES)) { if (isGoSdkLibRoot(root)) { return libraryRootToSdkPath(root); } } } } return null; } }), this)); } @Nullable @Override public String getSdkVersion(@Nullable Module module) { String parentVersion = super.getSdkVersion(module); if (parentVersion != null) { return parentVersion; } ComponentManager holder = ObjectUtils.notNull(module, myProject); return CachedValuesManager.getManager(myProject).getCachedValue(holder, () -> { String result = null; String sdkHomePath = getSdkHomePath(module); if (sdkHomePath != null) { result = GoSdkUtil.retrieveGoVersion(sdkHomePath); } return CachedValueProvider.Result.create(result, this); }); } @Override public void chooseAndSetSdk(@Nullable Module module) { ShowSettingsUtil.getInstance().editConfigurable(myProject, new GoSdkConfigurable(myProject, true)); } @Nullable @Override public Configurable createSdkConfigurable() { return !myProject.isDefault() ? new GoSdkConfigurable(myProject, false) : null; } @Override public boolean isGoModule(@Nullable Module module) { return super.isGoModule(module) && getSdkHomePath(module) != null; } public static boolean isGoSdkLibRoot(@NotNull VirtualFile root) { return root.isInLocalFileSystem() && root.isDirectory() && (VfsUtilCore.findRelativeFile(GoConstants.GO_VERSION_FILE_PATH, root) != null || VfsUtilCore.findRelativeFile(GoConstants.GO_VERSION_NEW_FILE_PATH, root) != null ); } } ================================================ FILE: src/com/goide/stubs/GoAnonymousFieldDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoAnonymousFieldDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoAnonymousFieldDefinitionStub extends GoNamedStub { public GoAnonymousFieldDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoAnonymousFieldDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoConstDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoConstDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoConstDefinitionStub extends GoNamedStub { public GoConstDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoConstDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoConstSpecStub.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoConstSpec; import com.goide.psi.GoExpression; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class GoConstSpecStub extends StubBase { private final StringRef myExpressionsRef; private List myList; public GoConstSpecStub(StubElement parent, IStubElementType elementType, StringRef ref) { super(parent, elementType); myExpressionsRef = ref; } @Nullable public String getExpressionsText() { return myExpressionsRef == null? null : myExpressionsRef.getString(); } @NotNull public List getExpressionList() { if (myList == null) { String text = getExpressionsText(); if (!StringUtil.isNotEmpty(text)) return myList = ContainerUtil.emptyList(); Project project = getPsi().getProject(); List split = StringUtil.split(text, ";"); myList = ContainerUtil.map(split, s -> GoElementFactory.createExpression(project, s)); } return myList; } } ================================================ FILE: src/com/goide/stubs/GoElementTypeFactory.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoType; import com.goide.psi.GoVarSpec; import com.goide.psi.impl.*; import com.goide.stubs.types.*; import com.intellij.psi.stubs.IStubElementType; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NotNull; import java.util.Map; public class GoElementTypeFactory { private static final Map TYPES = new HashMap() { { put("ARRAY_OR_SLICE_TYPE", GoArrayOrSliceTypeImpl.class); put("CHANNEL_TYPE", GoChannelTypeImpl.class); put("FUNCTION_TYPE", GoFunctionTypeImpl.class); put("INTERFACE_TYPE", GoInterfaceTypeImpl.class); put("MAP_TYPE", GoMapTypeImpl.class); put("POINTER_TYPE", GoPointerTypeImpl.class); put("STRUCT_TYPE", GoStructTypeImpl.class); put("TYPE", GoTypeImpl.class); put("PAR_TYPE", GoParTypeImpl.class); put("SPEC_TYPE", GoSpecTypeImpl.class); put("TYPE_LIST", GoTypeListImpl.class); } }; private GoElementTypeFactory() {} public static IStubElementType stubFactory(@NotNull String name) { if ("CONST_DEFINITION".equals(name)) return new GoConstDefinitionStubElementType(name); if ("FIELD_DEFINITION".equals(name)) return new GoFieldDefinitionStubElementType(name); if ("ANONYMOUS_FIELD_DEFINITION".equals(name)) return new GoAnonymousFieldDefinitionStubElementType(name); if ("FUNCTION_DECLARATION".equals(name)) return new GoFunctionDeclarationStubElementType(name); if ("METHOD_DECLARATION".equals(name)) return new GoMethodDeclarationStubElementType(name); if ("IMPORT_SPEC".equals(name)) return new GoImportSpecStubElementType(name); if ("PARAM_DEFINITION".equals(name)) return new GoParamDefinitionStubElementType(name); if ("RECEIVER".equals(name)) return new GoReceiverStubElementType(name); if ("TYPE_SPEC".equals(name)) return new GoTypeSpecStubElementType(name); if ("METHOD_SPEC".equals(name)) return new GoMethodSpecStubElementType(name); if ("CONST_SPEC".equals(name)) return new GoConstSpecStubElementType(name); if ("PACKAGE_CLAUSE".equals(name)) return GoPackageClauseStubElementType.INSTANCE; if ("VAR_SPEC".equals(name)) return new GoVarSpecStubElementType(name); if ("SHORT_VAR_DECLARATION".equals(name)) return new GoVarSpecStubElementType(name) { @NotNull @Override public GoVarSpec createPsi(@NotNull GoVarSpecStub stub) { return new GoShortVarDeclarationImpl(stub, this); } }; if ("RECV_STATEMENT".equals(name)) return new GoVarSpecStubElementType(name) { @NotNull @Override public GoVarSpec createPsi(@NotNull GoVarSpecStub stub) { return new GoRecvStatementImpl(stub, this); } }; if ("RANGE_CLAUSE".equals(name)) return new GoVarSpecStubElementType(name) { @NotNull @Override public GoVarSpec createPsi(@NotNull GoVarSpecStub stub) { return new GoRangeClauseImpl(stub, this); } }; if ("VAR_DEFINITION".equals(name)) return new GoVarDefinitionStubElementType(name); if ("LABEL_DEFINITION".equals(name)) return new GoLabelDefinitionStubElementType(name); if ("PARAMETERS".equals(name)) return new GoParametersStubElementType(name); if ("SIGNATURE".equals(name)) return new GoSignatureStubElementType(name); if ("PARAMETER_DECLARATION".equals(name)) return new GoParameterDeclarationStubElementType(name); if ("RESULT".equals(name)) return new GoResultStubElementType(name); Class c = TYPES.get(name); if (c != null) { return new GoTypeStubElementType(name) { @NotNull @Override public GoType createPsi(@NotNull GoTypeStub stub) { try { //noinspection unchecked return (GoType)ReflectionUtil.createInstance(c.getConstructor(stub.getClass(), IStubElementType.class), stub, this); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } }; } throw new RuntimeException("Unknown element type: " + name); } } ================================================ FILE: src/com/goide/stubs/GoFieldDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoFieldDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoFieldDefinitionStub extends GoNamedStub { public GoFieldDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoFieldDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoFileStub.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.GoFileElementType; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.goide.stubs.types.GoPackageClauseStubElementType; import com.intellij.psi.stubs.PsiFileStubImpl; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.tree.IStubFileElementType; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFileStub extends PsiFileStubImpl { private final StringRef myBuildFlags; public GoFileStub(@NotNull GoFile file) { this(file, StringRef.fromNullableString(file.getBuildFlags())); } public GoFileStub(@Nullable GoFile file, StringRef buildFlags) { super(file); myBuildFlags = buildFlags; } @NotNull @Override public IStubFileElementType getType() { return GoFileElementType.INSTANCE; } @Nullable public String getBuildFlags() { return myBuildFlags.getString(); } @Nullable public StubElement getPackageClauseStub() { return findChildStubByType(GoPackageClauseStubElementType.INSTANCE); } @Nullable public String getPackageName() { StubElement stub = getPackageClauseStub(); return stub instanceof GoPackageClauseStub ? ((GoPackageClauseStub)stub).getName() : null; } } ================================================ FILE: src/com/goide/stubs/GoFunctionDeclarationStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoFunctionDeclaration; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoFunctionDeclarationStub extends GoFunctionOrMethodDeclarationStub { public GoFunctionDeclarationStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoFunctionDeclarationStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoFunctionOrMethodDeclarationStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; abstract public class GoFunctionOrMethodDeclarationStub extends GoNamedStub { protected GoFunctionOrMethodDeclarationStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } protected GoFunctionOrMethodDeclarationStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoImportSpecStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoImportSpec; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoImportSpecStub extends GoNamedStub { @Nullable private final StringRef myAliasRef; @NotNull private final StringRef myPathRef; private final boolean myIsDot; public GoImportSpecStub(StubElement parent, IStubElementType elementType, @Nullable String alias, @NotNull String path, boolean isDot) { super(parent, elementType, (String)null, false); myAliasRef = StringRef.fromString(alias); myPathRef = StringRef.fromString(path); myIsDot = isDot; } @Nullable public String getAlias() { return myAliasRef != null ? myAliasRef.getString() : null; } @NotNull public String getPath() { return myPathRef.getString(); } public boolean isDot() { return myIsDot; } @Override public String getName() { return getAlias(); } } ================================================ FILE: src/com/goide/stubs/GoLabelDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoLabelDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoLabelDefinitionStub extends GoNamedStub { public GoLabelDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoLabelDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoMethodDeclarationStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoMethodDeclaration; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.Nullable; public class GoMethodDeclarationStub extends GoFunctionOrMethodDeclarationStub { private final StringRef myTypeName; public GoMethodDeclarationStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic, StringRef typeName) { super(parent, elementType, name, isPublic); myTypeName = typeName; } public GoMethodDeclarationStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic, String typeName) { super(parent, elementType, name, isPublic); myTypeName = StringRef.fromString(typeName); } @Nullable public String getTypeName() { return myTypeName == null ? null : myTypeName.getString(); } } ================================================ FILE: src/com/goide/stubs/GoMethodSpecStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoMethodSpec; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoMethodSpecStub extends GoNamedStub { private final int myArity; public GoMethodSpecStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic, int arity) { super(parent, elementType, name, isPublic); myArity = arity; } public GoMethodSpecStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic, int arity) { super(parent, elementType, name, isPublic); myArity = arity; } public int getArity() { return myArity; } } ================================================ FILE: src/com/goide/stubs/GoNamedStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoNamedElement; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.NamedStubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; abstract public class GoNamedStub extends NamedStubBase { private final boolean myIsPublic; public GoNamedStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name); myIsPublic = isPublic; } public GoNamedStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name); myIsPublic = isPublic; } public boolean isPublic() { return myIsPublic; } @Override public String toString() { String name = getName(); String str = super.toString(); return StringUtil.isEmpty(name) ? str : str + ": " + name; } } ================================================ FILE: src/com/goide/stubs/GoPackageClauseStub.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoPackageClause; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoPackageClauseStub extends StubBase { private final String myName; public GoPackageClauseStub(StubElement parent, IStubElementType elementType, String name) { super(parent, elementType); myName = name; } public GoPackageClauseStub(StubElement stub, IStubElementType elementType, StringRef ref) { super(stub, elementType); myName = ref != null ? ref.getString() : null; } public String getName() { return myName; } } ================================================ FILE: src/com/goide/stubs/GoParamDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoParamDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoParamDefinitionStub extends GoNamedStub { public GoParamDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoParamDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoParameterDeclarationStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoParameterDeclaration; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoParameterDeclarationStub extends StubWithText { private final boolean myVariadic; public GoParameterDeclarationStub(StubElement parent, IStubElementType elementType, StringRef ref, boolean variadic) { super(parent, elementType, ref); myVariadic = variadic; } public GoParameterDeclarationStub(StubElement parent, IStubElementType elementType, String text, boolean variadic) { this(parent, elementType, StringRef.fromString(text), variadic); } public boolean isVariadic() { return myVariadic; } } ================================================ FILE: src/com/goide/stubs/GoParametersStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoParameters; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoParametersStub extends StubWithText { public GoParametersStub(StubElement parent, IStubElementType elementType, StringRef ref) { super(parent, elementType, ref); } public GoParametersStub(StubElement parent, IStubElementType elementType, String text) { this(parent, elementType, StringRef.fromString(text)); } } ================================================ FILE: src/com/goide/stubs/GoReceiverStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoReceiver; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoReceiverStub extends GoNamedStub { public GoReceiverStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoReceiverStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoResultStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoResult; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoResultStub extends StubWithText { public GoResultStub(StubElement parent, IStubElementType elementType, StringRef ref) { super(parent, elementType, ref); } public GoResultStub(StubElement parent, IStubElementType elementType, String text) { this(parent, elementType, StringRef.fromString(text)); } } ================================================ FILE: src/com/goide/stubs/GoSignatureStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoSignature; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoSignatureStub extends StubWithText { public GoSignatureStub(StubElement parent, IStubElementType elementType, StringRef ref) { super(parent, elementType, ref); } public GoSignatureStub(StubElement parent, IStubElementType elementType, String text) { this(parent, elementType, StringRef.fromString(text)); } } ================================================ FILE: src/com/goide/stubs/GoTypeSpecStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoTypeSpec; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoTypeSpecStub extends GoNamedStub { public GoTypeSpecStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoTypeSpecStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoTypeStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoType; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoTypeStub extends StubWithText { public GoTypeStub(StubElement parent, IStubElementType elementType, StringRef ref) { super(parent, elementType, ref); } public GoTypeStub(StubElement parent, IStubElementType elementType, String text) { this(parent, elementType, StringRef.fromString(text)); } } ================================================ FILE: src/com/goide/stubs/GoVarDefinitionStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoVarDefinition; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; public class GoVarDefinitionStub extends GoNamedStub { public GoVarDefinitionStub(StubElement parent, IStubElementType elementType, StringRef name, boolean isPublic) { super(parent, elementType, name, isPublic); } public GoVarDefinitionStub(StubElement parent, IStubElementType elementType, String name, boolean isPublic) { super(parent, elementType, name, isPublic); } } ================================================ FILE: src/com/goide/stubs/GoVarSpecStub.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.psi.GoVarSpec; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; public class GoVarSpecStub extends StubBase { public GoVarSpecStub(StubElement parent, IStubElementType elementType) { super(parent, elementType); } } ================================================ FILE: src/com/goide/stubs/StubWithText.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.Nullable; abstract public class StubWithText extends StubBase implements TextHolder { @Nullable private final StringRef myText; protected StubWithText(StubElement parent, IStubElementType elementType, @Nullable StringRef ref) { super(parent, elementType); myText = ref; } @Override @Nullable public String getText() { return myText == null ? null : myText.getString(); } } ================================================ FILE: src/com/goide/stubs/TextHolder.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import org.jetbrains.annotations.Nullable; public interface TextHolder { @Nullable String getText(); } ================================================ FILE: src/com/goide/stubs/index/GoAllPrivateNamesIndex.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoNamedElement; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; public class GoAllPrivateNamesIndex extends StringStubIndexExtension { public static final StubIndexKey ALL_PRIVATE_NAMES = StubIndexKey.createIndexKey("go.all.private.name"); @Override public int getVersion() { return GoFileElementType.VERSION; } @NotNull @Override public StubIndexKey getKey() { return ALL_PRIVATE_NAMES; } } ================================================ FILE: src/com/goide/stubs/index/GoAllPublicNamesIndex.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoNamedElement; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; public class GoAllPublicNamesIndex extends StringStubIndexExtension { public static final StubIndexKey ALL_PUBLIC_NAMES = StubIndexKey.createIndexKey("go.all.name"); @Override public int getVersion() { return GoFileElementType.VERSION; } @NotNull @Override public StubIndexKey getKey() { return ALL_PUBLIC_NAMES; } } ================================================ FILE: src/com/goide/stubs/index/GoFunctionIndex.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoFunctionDeclaration; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.util.Processor; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class GoFunctionIndex extends StringStubIndexExtension { public static final StubIndexKey KEY = StubIndexKey.createIndexKey("go.function"); @Override public int getVersion() { return GoFileElementType.VERSION + 3; } @NotNull @Override public StubIndexKey getKey() { return KEY; } @NotNull public static Collection find(@NotNull String name, @NotNull Project project, @Nullable GlobalSearchScope scope, @Nullable IdFilter idFilter) { return StubIndex.getElements(KEY, name, project, scope, idFilter, GoFunctionDeclaration.class); } public static boolean process(@NotNull String name, @NotNull Project project, @Nullable GlobalSearchScope scope, @Nullable IdFilter idFilter, @NotNull Processor processor) { return StubIndex.getInstance().processElements(KEY, name, project, scope, idFilter, GoFunctionDeclaration.class, processor); } } ================================================ FILE: src/com/goide/stubs/index/GoIdFilter.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.runconfig.testing.GoTestFinder; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.VirtualFileWithId; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.BitSet; public class GoIdFilter extends IdFilter { public static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.DefaultFileNavigationContributor"); private static final Key> PRODUCTION_FILTER = Key.create("PRODUCTION"); private static final Key> TESTS_FILTER = Key.create("TESTS"); private final BitSet myIdSet; private GoIdFilter(@NotNull BitSet idSet) { myIdSet = idSet; } @Override public boolean containsFileId(int id) { return id >= 0 && myIdSet.get(id); } public static IdFilter getProductionFilter(@NotNull Project project) { return createIdFilter(project, PRODUCTION_FILTER, file -> !file.isDirectory() && !GoTestFinder.isTestFile(file)); } public static IdFilter getTestsFilter(@NotNull Project project) { return createIdFilter(project, TESTS_FILTER, file -> !file.isDirectory() && GoTestFinder.isTestFile(file)); } private static IdFilter createIdFilter(@NotNull Project project, @NotNull Key> cacheKey, @NotNull Condition filterCondition) { return CachedValuesManager.getManager(project).getCachedValue(project, cacheKey, () -> { BitSet bitSet = new BitSet(); ContentIterator iterator = fileOrDir -> { if (filterCondition.value(fileOrDir)) { addToBitSet(bitSet, fileOrDir); } ProgressManager.checkCanceled(); return true; }; FileBasedIndex.getInstance().iterateIndexableFiles(iterator, project, null); return CachedValueProvider.Result.create(new GoIdFilter(bitSet), ProjectRootManager.getInstance(project), VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS); }, false); } @Nullable public static IdFilter getFilesFilter(@NotNull GlobalSearchScope scope) { if (scope instanceof GlobalSearchScope.FilesScope) { BitSet bitSet = new BitSet(); for (VirtualFile file : (GlobalSearchScope.FilesScope)scope) { addToBitSet(bitSet, file); } return new GoIdFilter(bitSet); } return null; } private static void addToBitSet(@NotNull BitSet set, @NotNull VirtualFile file) { if (file instanceof VirtualFileWithId) { int id = ((VirtualFileWithId)file).getId(); if (id < 0) id = -id; // workaround for encountering invalid files, see EA-49915, EA-50599 set.set(id); } } } ================================================ FILE: src/com/goide/stubs/index/GoMethodFingerprintIndex.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoMethodSpec; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GoMethodFingerprintIndex extends StringStubIndexExtension { public static final StubIndexKey KEY = StubIndexKey.createIndexKey("go.method.fingerprint"); @Override public int getVersion() { return GoFileElementType.VERSION + 1; } @NotNull @Override public StubIndexKey getKey() { return KEY; } public static Collection find(@NotNull String name, @NotNull Project project, GlobalSearchScope scope) { return StubIndex.getElements(KEY, name, project, scope, GoMethodSpec.class); } } ================================================ FILE: src/com/goide/stubs/index/GoMethodIndex.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoMethodDeclaration; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.util.Processor; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class GoMethodIndex extends StringStubIndexExtension { public static final StubIndexKey KEY = StubIndexKey.createIndexKey("go.method"); @Override public int getVersion() { return GoFileElementType.VERSION + 2; } @NotNull @Override public StubIndexKey getKey() { return KEY; } public static Collection find(@NotNull String name, @NotNull Project project, @Nullable GlobalSearchScope scope, @Nullable IdFilter idFilter) { return StubIndex.getElements(KEY, name, project, scope, idFilter, GoMethodDeclaration.class); } public static boolean process(@NotNull String name, @NotNull Project project, @Nullable GlobalSearchScope scope, @Nullable IdFilter idFilter, @NotNull Processor processor) { return StubIndex.getInstance().processElements(KEY, name, project, scope, idFilter, GoMethodDeclaration.class, processor); } } ================================================ FILE: src/com/goide/stubs/index/GoPackagesIndex.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoFile; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; public class GoPackagesIndex extends StringStubIndexExtension { public static final StubIndexKey KEY = StubIndexKey.createIndexKey("go.packages"); @Override public int getVersion() { return GoFileElementType.VERSION + 2; } @NotNull @Override public StubIndexKey getKey() { return KEY; } } ================================================ FILE: src/com/goide/stubs/index/GoTypesIndex.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.index; import com.goide.GoFileElementType; import com.goide.psi.GoTypeSpec; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.util.indexing.IdFilter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class GoTypesIndex extends StringStubIndexExtension { public static final StubIndexKey KEY = StubIndexKey.createIndexKey("go.type.name"); @Override public int getVersion() { return GoFileElementType.VERSION + 2; } @NotNull @Override public StubIndexKey getKey() { return KEY; } @NotNull public static Collection find(@NotNull String name, @NotNull Project project, @Nullable GlobalSearchScope scope, @Nullable IdFilter idFilter) { return StubIndex.getElements(KEY, name, project, scope, idFilter, GoTypeSpec.class); } } ================================================ FILE: src/com/goide/stubs/types/GoAnonymousFieldDefinitionStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoAnonymousFieldDefinition; import com.goide.psi.impl.GoAnonymousFieldDefinitionImpl; import com.goide.stubs.GoAnonymousFieldDefinitionStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoAnonymousFieldDefinitionStubElementType extends GoNamedStubElementType { public GoAnonymousFieldDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoAnonymousFieldDefinition createPsi(@NotNull GoAnonymousFieldDefinitionStub stub) { return new GoAnonymousFieldDefinitionImpl(stub, this); } @NotNull @Override public GoAnonymousFieldDefinitionStub createStub(@NotNull GoAnonymousFieldDefinition psi, StubElement parentStub) { return new GoAnonymousFieldDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoAnonymousFieldDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoAnonymousFieldDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoAnonymousFieldDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } } ================================================ FILE: src/com/goide/stubs/types/GoConstDefinitionStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoConstDefinition; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.impl.GoConstDefinitionImpl; import com.goide.stubs.GoConstDefinitionStub; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayFactory; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoConstDefinitionStubElementType extends GoNamedStubElementType { public static final GoConstDefinition[] EMPTY_ARRAY = new GoConstDefinition[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoConstDefinition[count]; public GoConstDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoConstDefinition createPsi(@NotNull GoConstDefinitionStub stub) { return new GoConstDefinitionImpl(stub, this); } @NotNull @Override public GoConstDefinitionStub createStub(@NotNull GoConstDefinition psi, StubElement parentStub) { return new GoConstDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoConstDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoConstDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoConstDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { return super.shouldCreateStub(node) && PsiTreeUtil.getParentOfType(node.getPsi(), GoFunctionOrMethodDeclaration.class) == null; } } ================================================ FILE: src/com/goide/stubs/types/GoConstSpecStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoConstSpec; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.impl.GoConstSpecImpl; import com.goide.stubs.GoConstSpecStub; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayFactory; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoConstSpecStubElementType extends GoStubElementType { public static final GoConstSpec[] EMPTY_ARRAY = new GoConstSpec[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoConstSpec[count]; public GoConstSpecStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoConstSpec createPsi(@NotNull GoConstSpecStub stub) { return new GoConstSpecImpl(stub, this); } @NotNull @Override public GoConstSpecStub createStub(@NotNull GoConstSpec psi, StubElement parentStub) { String join = StringUtil.join(psi.getExpressionList(), PsiElement::getText, ";"); return new GoConstSpecStub(parentStub, this, StringRef.fromString(join)); } @Override public void serialize(@NotNull GoConstSpecStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getExpressionsText()); } @Override public boolean shouldCreateStub(ASTNode node) { return super.shouldCreateStub(node) && PsiTreeUtil.getParentOfType(node.getPsi(), GoFunctionOrMethodDeclaration.class) == null; } @NotNull @Override public GoConstSpecStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoConstSpecStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoFieldDefinitionStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoFieldDefinition; import com.goide.psi.impl.GoFieldDefinitionImpl; import com.goide.stubs.GoFieldDefinitionStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoFieldDefinitionStubElementType extends GoNamedStubElementType { public GoFieldDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoFieldDefinition createPsi(@NotNull GoFieldDefinitionStub stub) { return new GoFieldDefinitionImpl(stub, this); } @NotNull @Override public GoFieldDefinitionStub createStub(@NotNull GoFieldDefinition psi, StubElement parentStub) { return new GoFieldDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoFieldDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoFieldDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoFieldDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } } ================================================ FILE: src/com/goide/stubs/types/GoFunctionDeclarationStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoNamedElement; import com.goide.psi.impl.GoFunctionDeclarationImpl; import com.goide.stubs.GoFunctionDeclarationStub; import com.goide.stubs.index.GoFunctionIndex; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.ArrayFactory; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; public class GoFunctionDeclarationStubElementType extends GoNamedStubElementType { public static final GoFunctionDeclaration[] EMPTY_ARRAY = new GoFunctionDeclaration[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoFunctionDeclaration[count]; private static final ArrayList> EXTRA_KEYS = ContainerUtil.newArrayList(GoFunctionIndex.KEY); public GoFunctionDeclarationStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoFunctionDeclaration createPsi(@NotNull GoFunctionDeclarationStub stub) { return new GoFunctionDeclarationImpl(stub, this); } @NotNull @Override public GoFunctionDeclarationStub createStub(@NotNull GoFunctionDeclaration psi, StubElement parentStub) { return new GoFunctionDeclarationStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoFunctionDeclarationStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoFunctionDeclarationStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoFunctionDeclarationStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @NotNull @Override protected Collection> getExtraIndexKeys() { return EXTRA_KEYS; } } ================================================ FILE: src/com/goide/stubs/types/GoImportSpecStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoImportSpec; import com.goide.psi.impl.GoImportSpecImpl; import com.goide.stubs.GoImportSpecStub; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.ArrayFactory; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoImportSpecStubElementType extends GoNamedStubElementType { public static final GoImportSpec[] EMPTY_ARRAY = new GoImportSpec[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoImportSpec[count]; public GoImportSpecStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoImportSpec createPsi(@NotNull GoImportSpecStub stub) { return new GoImportSpecImpl(stub, this); } @NotNull @Override public GoImportSpecStub createStub(@NotNull GoImportSpec psi, StubElement parentStub) { return new GoImportSpecStub(parentStub, this, psi.getAlias(), psi.getPath(), psi.isDot()); } @Override public void serialize(@NotNull GoImportSpecStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeUTFFast(StringUtil.notNullize(stub.getAlias())); dataStream.writeUTFFast(stub.getPath()); dataStream.writeBoolean(stub.isDot()); } @NotNull @Override public GoImportSpecStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoImportSpecStub(parentStub, this, StringUtil.nullize(dataStream.readUTFFast()), dataStream.readUTFFast(), dataStream.readBoolean()); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { return true; } } ================================================ FILE: src/com/goide/stubs/types/GoLabelDefinitionStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoLabelDefinition; import com.goide.psi.impl.GoLabelDefinitionImpl; import com.goide.stubs.GoLabelDefinitionStub; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoLabelDefinitionStubElementType extends GoNamedStubElementType { public GoLabelDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoLabelDefinition createPsi(@NotNull GoLabelDefinitionStub stub) { return new GoLabelDefinitionImpl(stub, this); } @NotNull @Override public GoLabelDefinitionStub createStub(@NotNull GoLabelDefinition psi, StubElement parentStub) { return new GoLabelDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoLabelDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { return false; // todo } @NotNull @Override public GoLabelDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoLabelDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } } ================================================ FILE: src/com/goide/stubs/types/GoMethodDeclarationStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoMethodDeclaration; import com.goide.psi.GoTypeReferenceExpression; import com.goide.psi.impl.GoMethodDeclarationImpl; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.stubs.GoFileStub; import com.goide.stubs.GoMethodDeclarationStub; import com.goide.stubs.index.GoMethodIndex; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.ArrayFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; public class GoMethodDeclarationStubElementType extends GoNamedStubElementType { public static final GoMethodDeclaration[] EMPTY_ARRAY = new GoMethodDeclaration[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoMethodDeclaration[count]; public GoMethodDeclarationStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoMethodDeclaration createPsi(@NotNull GoMethodDeclarationStub stub) { return new GoMethodDeclarationImpl(stub, this); } @Nullable @Override public GoMethodDeclarationStub createStub(@NotNull GoMethodDeclaration psi, StubElement parentStub) { return new GoMethodDeclarationStub(parentStub, this, psi.getName(), psi.isPublic(), calcTypeText(psi)); } @Override public void serialize(@NotNull GoMethodDeclarationStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); dataStream.writeName(stub.getTypeName()); } @NotNull @Override public GoMethodDeclarationStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoMethodDeclarationStub(parentStub, this, dataStream.readName(), dataStream.readBoolean(), dataStream.readName()); } @Override public void indexStub(@NotNull GoMethodDeclarationStub stub, @NotNull IndexSink sink) { super.indexStub(stub, sink); String typeName = stub.getTypeName(); if (!StringUtil.isEmpty(typeName)) { StubElement parent = stub.getParentStub(); if (parent instanceof GoFileStub) { String packageName = ((GoFileStub)parent).getPackageName(); if (!StringUtil.isEmpty(typeName)) { sink.occurrence(GoMethodIndex.KEY, packageName + "." + typeName); } } } } @Nullable public static String calcTypeText(@NotNull GoMethodDeclaration psi) { GoTypeReferenceExpression reference = GoPsiImplUtil.getTypeReference(psi.getReceiverType()); return reference != null ? reference.getIdentifier().getText() : null; } } ================================================ FILE: src/com/goide/stubs/types/GoMethodSpecStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoMethodSpec; import com.goide.psi.impl.GoMethodSpecImpl; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.stubs.GoMethodSpecStub; import com.goide.stubs.index.GoMethodFingerprintIndex; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoMethodSpecStubElementType extends GoNamedStubElementType { public GoMethodSpecStubElementType(@NotNull String name) { super(name); } @Override public void indexStub(@NotNull GoMethodSpecStub stub, @NotNull IndexSink sink) { super.indexStub(stub, sink); String name = stub.getName(); int arity = stub.getArity(); if (name != null && arity >= 0) { sink.occurrence(GoMethodFingerprintIndex.KEY, name + "/" + arity); } } @NotNull @Override public GoMethodSpec createPsi(@NotNull GoMethodSpecStub stub) { return new GoMethodSpecImpl(stub, this); } @NotNull @Override public GoMethodSpecStub createStub(@NotNull GoMethodSpec psi, StubElement parentStub) { int arity = GoPsiImplUtil.getArity(psi.getSignature()); return new GoMethodSpecStub(parentStub, this, psi.getName(), psi.isPublic(), arity); } @Override public void serialize(@NotNull GoMethodSpecStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); dataStream.writeVarInt(stub.getArity()); } @NotNull @Override public GoMethodSpecStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoMethodSpecStub(parentStub, this, dataStream.readName(), dataStream.readBoolean(), dataStream.readVarInt()); } } ================================================ FILE: src/com/goide/stubs/types/GoNamedStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoNamedElement; import com.goide.stubs.GoFileStub; import com.goide.stubs.GoNamedStub; import com.goide.stubs.index.GoAllPrivateNamesIndex; import com.goide.stubs.index.GoAllPublicNamesIndex; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Collections; public abstract class GoNamedStubElementType, T extends GoNamedElement> extends GoStubElementType { public GoNamedStubElementType(@NonNls @NotNull String debugName) { super(debugName); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { if (!super.shouldCreateStub(node)) return false; PsiElement psi = node.getPsi(); return psi instanceof GoNamedElement && StringUtil.isNotEmpty(((GoNamedElement)psi).getName()); } @Override public void indexStub(@NotNull S stub, @NotNull IndexSink sink) { String name = stub.getName(); if (shouldIndex() && StringUtil.isNotEmpty(name)) { String packageName = null; StubElement parent = stub.getParentStub(); while (parent != null) { if (parent instanceof GoFileStub) { packageName = ((GoFileStub)parent).getPackageName(); break; } parent = parent.getParentStub(); } String indexingName = StringUtil.isNotEmpty(packageName) ? packageName + "." + name : name; if (stub.isPublic()) { sink.occurrence(GoAllPublicNamesIndex.ALL_PUBLIC_NAMES, indexingName); } else { sink.occurrence(GoAllPrivateNamesIndex.ALL_PRIVATE_NAMES, indexingName); } for (StubIndexKey key : getExtraIndexKeys()) { sink.occurrence(key, name); } } } protected boolean shouldIndex() { return true; } @NotNull protected Collection> getExtraIndexKeys() { return Collections.emptyList(); } } ================================================ FILE: src/com/goide/stubs/types/GoPackageClauseStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoPackageClause; import com.goide.psi.impl.GoPackageClauseImpl; import com.goide.stubs.GoPackageClauseStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoPackageClauseStubElementType extends GoStubElementType { public static final GoPackageClauseStubElementType INSTANCE = new GoPackageClauseStubElementType(); private GoPackageClauseStubElementType() { super("PACKAGE_CLAUSE"); } @NotNull @Override public GoPackageClause createPsi(@NotNull GoPackageClauseStub stub) { return new GoPackageClauseImpl(stub, this); } @NotNull @Override public GoPackageClauseStub createStub(@NotNull GoPackageClause psi, StubElement parentStub) { return new GoPackageClauseStub(parentStub, this, psi.getName()); } @Override public void serialize(@NotNull GoPackageClauseStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); } @NotNull @Override public GoPackageClauseStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoPackageClauseStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoParamDefinitionStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoParamDefinition; import com.goide.psi.impl.GoParamDefinitionImpl; import com.goide.stubs.GoParamDefinitionStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoParamDefinitionStubElementType extends GoNamedStubElementType { public GoParamDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoParamDefinition createPsi(@NotNull GoParamDefinitionStub stub) { return new GoParamDefinitionImpl(stub, this); } @NotNull @Override public GoParamDefinitionStub createStub(@NotNull GoParamDefinition psi, StubElement parentStub) { return new GoParamDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoParamDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoParamDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoParamDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @Override protected boolean shouldIndex() { return false; } } ================================================ FILE: src/com/goide/stubs/types/GoParameterDeclarationStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoParameterDeclaration; import com.goide.psi.impl.GoParameterDeclarationImpl; import com.goide.stubs.GoParameterDeclarationStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoParameterDeclarationStubElementType extends GoStubElementType { public GoParameterDeclarationStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoParameterDeclaration createPsi(@NotNull GoParameterDeclarationStub stub) { return new GoParameterDeclarationImpl(stub, this); } @NotNull @Override public GoParameterDeclarationStub createStub(@NotNull GoParameterDeclaration psi, StubElement parentStub) { return new GoParameterDeclarationStub(parentStub, this, psi.getText(), psi.isVariadic()); } @Override public void serialize(@NotNull GoParameterDeclarationStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getText()); dataStream.writeBoolean(stub.isVariadic()); } @NotNull @Override public GoParameterDeclarationStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoParameterDeclarationStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } } ================================================ FILE: src/com/goide/stubs/types/GoParametersStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoParameters; import com.goide.psi.impl.GoParametersImpl; import com.goide.stubs.GoParametersStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoParametersStubElementType extends GoStubElementType { public GoParametersStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoParameters createPsi(@NotNull GoParametersStub stub) { return new GoParametersImpl(stub, this); } @NotNull @Override public GoParametersStub createStub(@NotNull GoParameters psi, StubElement parentStub) { return new GoParametersStub(parentStub, this, psi.getText()); } @Override public void serialize(@NotNull GoParametersStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getText()); } @NotNull @Override public GoParametersStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoParametersStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoReceiverStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoReceiver; import com.goide.psi.impl.GoReceiverImpl; import com.goide.stubs.GoReceiverStub; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoReceiverStubElementType extends GoNamedStubElementType { public GoReceiverStubElementType(@NotNull String name) { super(name); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { return true; } @NotNull @Override public GoReceiver createPsi(@NotNull GoReceiverStub stub) { return new GoReceiverImpl(stub, this); } @NotNull @Override public GoReceiverStub createStub(@NotNull GoReceiver psi, StubElement parentStub) { return new GoReceiverStub(parentStub, this, StringUtil.notNullize(psi.getName()), psi.isPublic()); } @Override public void serialize(@NotNull GoReceiverStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoReceiverStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoReceiverStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @Override protected boolean shouldIndex() { return false; } } ================================================ FILE: src/com/goide/stubs/types/GoResultStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoResult; import com.goide.psi.impl.GoResultImpl; import com.goide.stubs.GoResultStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoResultStubElementType extends GoStubElementType { public GoResultStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoResult createPsi(@NotNull GoResultStub stub) { return new GoResultImpl(stub, this); } @NotNull @Override public GoResultStub createStub(@NotNull GoResult psi, StubElement parentStub) { return new GoResultStub(parentStub, this, psi.getText()); } @Override public void serialize(@NotNull GoResultStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getText()); } @NotNull @Override public GoResultStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoResultStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoSignatureStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoSignature; import com.goide.psi.impl.GoSignatureImpl; import com.goide.stubs.GoSignatureStub; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoSignatureStubElementType extends GoStubElementType { public GoSignatureStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoSignature createPsi(@NotNull GoSignatureStub stub) { return new GoSignatureImpl(stub, this); } @NotNull @Override public GoSignatureStub createStub(@NotNull GoSignature psi, StubElement parentStub) { return new GoSignatureStub(parentStub, this, psi.getText()); } @Override public void serialize(@NotNull GoSignatureStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getText()); } @NotNull @Override public GoSignatureStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoSignatureStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoStubElementType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.GoLanguage; import com.goide.psi.GoBlock; import com.goide.psi.GoCompositeElement; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public abstract class GoStubElementType, T extends GoCompositeElement> extends IStubElementType { public GoStubElementType(@NonNls @NotNull String debugName) { super(debugName, GoLanguage.INSTANCE); } @Override @NotNull public String getExternalId() { return "go." + super.toString(); } @Override public void indexStub(@NotNull S stub, @NotNull IndexSink sink) { } @Override public boolean shouldCreateStub(ASTNode node) { return super.shouldCreateStub(node) && shouldCreateStubInBlock(node); } protected boolean shouldCreateStubInBlock(ASTNode node) { return PsiTreeUtil.getParentOfType(node.getPsi(), GoBlock.class) == null; } } ================================================ FILE: src/com/goide/stubs/types/GoTypeSpecStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoNamedElement; import com.goide.psi.GoTypeSpec; import com.goide.psi.impl.GoTypeSpecImpl; import com.goide.stubs.GoTypeSpecStub; import com.goide.stubs.index.GoTypesIndex; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubIndexKey; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.ArrayFactory; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Collection; public class GoTypeSpecStubElementType extends GoNamedStubElementType { public static final GoTypeSpec[] EMPTY_ARRAY = new GoTypeSpec[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoTypeSpec[count]; public GoTypeSpecStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoTypeSpec createPsi(@NotNull GoTypeSpecStub stub) { return new GoTypeSpecImpl(stub, this); } @NotNull @Override public GoTypeSpecStub createStub(@NotNull GoTypeSpec psi, StubElement parentStub) { return new GoTypeSpecStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoTypeSpecStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoTypeSpecStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoTypeSpecStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @NotNull @Override protected Collection> getExtraIndexKeys() { return ContainerUtil.list(GoTypesIndex.KEY); } @Override protected boolean shouldCreateStubInBlock(ASTNode node) { return true; } } ================================================ FILE: src/com/goide/stubs/types/GoTypeStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoType; import com.goide.psi.GoTypeSpec; import com.goide.stubs.GoTypeStub; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; public abstract class GoTypeStubElementType extends GoStubElementType { protected GoTypeStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoTypeStub createStub(@NotNull GoType psi, StubElement parentStub) { return new GoTypeStub(parentStub, this, psi.getText()); } @Override public void serialize(@NotNull GoTypeStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getText()); } @Override protected boolean shouldCreateStubInBlock(ASTNode node) { return PsiTreeUtil.getParentOfType(node.getPsi(), GoTypeSpec.class) != null || super.shouldCreateStubInBlock(node); } @NotNull @Override public GoTypeStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoTypeStub(parentStub, this, dataStream.readName()); } } ================================================ FILE: src/com/goide/stubs/types/GoVarDefinitionStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoVarDefinition; import com.goide.psi.impl.GoVarDefinitionImpl; import com.goide.stubs.GoVarDefinitionStub; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayFactory; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoVarDefinitionStubElementType extends GoNamedStubElementType { public static final GoVarDefinition[] EMPTY_ARRAY = new GoVarDefinition[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoVarDefinition[count]; public GoVarDefinitionStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoVarDefinition createPsi(@NotNull GoVarDefinitionStub stub) { return new GoVarDefinitionImpl(stub, this); } @NotNull @Override public GoVarDefinitionStub createStub(@NotNull GoVarDefinition psi, StubElement parentStub) { return new GoVarDefinitionStub(parentStub, this, psi.getName(), psi.isPublic()); } @Override public void serialize(@NotNull GoVarDefinitionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); dataStream.writeBoolean(stub.isPublic()); } @NotNull @Override public GoVarDefinitionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoVarDefinitionStub(parentStub, this, dataStream.readName(), dataStream.readBoolean()); } @Override public boolean shouldCreateStub(@NotNull ASTNode node) { return super.shouldCreateStub(node) && PsiTreeUtil.getParentOfType(node.getPsi(), GoFunctionOrMethodDeclaration.class) == null; } } ================================================ FILE: src/com/goide/stubs/types/GoVarSpecStubElementType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs.types; import com.goide.GoTypes; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoVarSpec; import com.goide.psi.impl.GoVarSpecImpl; import com.goide.stubs.GoVarSpecStub; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ArrayFactory; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoVarSpecStubElementType extends GoStubElementType { public static final GoVarSpec[] EMPTY_ARRAY = new GoVarSpec[0]; public static final ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new GoVarSpec[count]; public GoVarSpecStubElementType(@NotNull String name) { super(name); } @NotNull @Override public GoVarSpec createPsi(@NotNull GoVarSpecStub stub) { return new GoVarSpecImpl(stub, this); } @NotNull @Override public GoVarSpecStub createStub(@NotNull GoVarSpec psi, StubElement parentStub) { return new GoVarSpecStub(parentStub, this); } @Override public boolean shouldCreateStub(ASTNode node) { return super.shouldCreateStub(node) && node.getElementType() == GoTypes.VAR_SPEC && PsiTreeUtil.getParentOfType(node.getPsi(), GoFunctionOrMethodDeclaration.class) == null; } @Override public void serialize(@NotNull GoVarSpecStub stub, @NotNull StubOutputStream dataStream) throws IOException { } @NotNull @Override public GoVarSpecStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { return new GoVarSpecStub(parentStub, this); } } ================================================ FILE: src/com/goide/template/GoEverywhereContextType.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.template; import com.goide.GoConstants; import com.goide.GoTypes; import com.intellij.codeInsight.template.EverywhereContextType; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; import org.jetbrains.annotations.NotNull; public class GoEverywhereContextType extends GoLiveTemplateContextType { protected GoEverywhereContextType() { super("GO", GoConstants.GO, EverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return !(element instanceof PsiComment || element instanceof LeafPsiElement && ((LeafPsiElement)element).getElementType() == GoTypes.STRING); } } ================================================ FILE: src/com/goide/template/GoFieldNameMacro.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.template; import com.goide.psi.GoFieldDeclaration; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.codeInsight.template.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Set; public class GoFieldNameMacro extends Macro { @Override public String getName() { return "fieldName"; } @Override public String getPresentableName() { return "fieldName()"; } @Nullable @Override public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) { String name = ContainerUtil.getFirstItem(fieldNames(context)); return StringUtil.isNotEmpty(name) ? new TextResult(name) : null; } @Nullable @Override public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) { return ContainerUtil.map2Array(fieldNames(context), LookupElement.class, LookupElementBuilder::create); } @Override public boolean isAcceptableInContext(TemplateContextType context) { return context instanceof GoLiveTemplateContextType.Tag || context instanceof GoLiveTemplateContextType.TagLiteral; } private static Set fieldNames(ExpressionContext context) { PsiElement psiElement = context != null ? context.getPsiElementAtStartOffset() : null; GoFieldDeclaration fieldDeclaration = PsiTreeUtil.getNonStrictParentOfType(psiElement, GoFieldDeclaration.class); if (fieldDeclaration == null) { return Collections.emptySet(); } return ContainerUtil.map2LinkedSet(fieldDeclaration.getFieldDefinitionList(), PsiNamedElement::getName); } } ================================================ FILE: src/com/goide/template/GoLiveTemplateContextType.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.template; import com.goide.GoLanguage; import com.goide.GoTypes; import com.goide.highlighting.GoSyntaxHighlighter; import com.goide.psi.*; import com.intellij.codeInsight.template.TemplateContextType; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; abstract public class GoLiveTemplateContextType extends TemplateContextType { protected GoLiveTemplateContextType(@NotNull @NonNls String id, @NotNull String presentableName, @Nullable Class baseContextType) { super(id, presentableName, baseContextType); } @Override public boolean isInContext(@NotNull PsiFile file, int offset) { if (PsiUtilCore.getLanguageAtOffset(file, offset).isKindOf(GoLanguage.INSTANCE)) { PsiElement psiElement = ObjectUtils.notNull(file.findElementAt(offset), file); if (!acceptLeaf()) { psiElement = getFirstCompositeElement(psiElement); } return psiElement != null && isInContext(psiElement); } return false; } protected boolean acceptLeaf() { return false; } @Nullable public static PsiElement prevVisibleLeafOrNewLine(PsiElement element) { PsiElement prevLeaf = element; while ((prevLeaf = PsiTreeUtil.prevLeaf(prevLeaf)) != null) { if (prevLeaf instanceof PsiComment || prevLeaf instanceof PsiErrorElement) { continue; } if (prevLeaf instanceof PsiWhiteSpace) { if (prevLeaf.textContains('\n')) { return prevLeaf; } continue; } break; } return prevLeaf; } @Nullable private static PsiElement getFirstCompositeElement(@Nullable PsiElement at) { if (at instanceof PsiComment || at instanceof LeafPsiElement && ((LeafPsiElement)at).getElementType() == GoTypes.STRING) return at; PsiElement result = at; while (result != null && (result instanceof PsiWhiteSpace || result.getNode().getChildren(null).length == 0)) { result = result.getParent(); } return result; } protected abstract boolean isInContext(@NotNull PsiElement element); @Override public SyntaxHighlighter createHighlighter() { return new GoSyntaxHighlighter(); } public static class File extends GoLiveTemplateContextType { protected File() { super("GO_FILE", "File", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { if (element instanceof PsiComment || element instanceof GoPackageClause) { return false; } return element instanceof GoFile || element.getParent() instanceof GoFile && !(element instanceof GoTopLevelDeclaration); } } public static class Type extends GoLiveTemplateContextType { protected Type() { super("GO_TYPE", "Type", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return element instanceof GoType; } } public static class Block extends GoLiveTemplateContextType { protected Block() { super("GO_BLOCK", "Block", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return (element instanceof GoLeftHandExprList || element instanceof GoSimpleStatement) && PsiTreeUtil.getParentOfType(element, GoBlock.class) != null; } } public static class Expression extends GoLiveTemplateContextType { protected Expression() { super("GO_EXPRESSION", "Expression", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return element instanceof GoExpression; } } public static class Tag extends GoLiveTemplateContextType { protected Tag() { super("GO_TAG", "Tag", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { if (element.getNode().getElementType() == GoTypes.IDENTIFIER) { if (isInsideFieldTypeDeclaration(element)) { return true; } if (isInsideFieldTypeDeclaration(prevVisibleLeafOrNewLine(element))) { return true; } } return false; } private static boolean isInsideFieldTypeDeclaration(@Nullable PsiElement element) { if (element != null) { PsiElement parent = element.getParent(); if (parent instanceof GoTypeReferenceExpression) { return PsiTreeUtil.skipParentsOfType(parent, GoType.class) instanceof GoFieldDeclaration; } } return false; } @Override protected boolean acceptLeaf() { return true; } } public static class TagLiteral extends GoLiveTemplateContextType { protected TagLiteral() { super("GO_TAG_LITERAL", "Tag literal", GoEverywhereContextType.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return element instanceof GoStringLiteral && element.getParent() instanceof GoTag; } } public static class Statement extends GoLiveTemplateContextType { protected Statement() { super("GO_STATEMENT", "Statement", GoEverywhereContextType.class); } public static boolean onStatementBeginning(@NotNull PsiElement psiElement) { PsiElement prevLeaf = prevVisibleLeafOrNewLine(psiElement); if (prevLeaf == null) { return false; } if (prevLeaf instanceof PsiWhiteSpace) { return true; } IElementType type = prevLeaf.getNode().getElementType(); return type == GoTypes.SEMICOLON || type == GoTypes.LBRACE || type == GoTypes.RBRACE || type == GoTypes.COLON; } @Override protected boolean isInContext(@NotNull PsiElement element) { if (element instanceof PsiComment) { return false; } PsiElement parent = element.getParent(); if (parent instanceof PsiErrorElement || parent instanceof GoExpression) { parent = parent.getParent(); } return (parent instanceof GoStatement || parent instanceof GoLeftHandExprList || parent instanceof GoBlock) && onStatementBeginning(element); } @Override protected boolean acceptLeaf() { return true; } } } ================================================ FILE: src/com/goide/template/GoLiveTemplatesProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.template; import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoLiveTemplatesProvider implements DefaultLiveTemplatesProvider { @NotNull @Override public String[] getDefaultLiveTemplateFiles() { return new String[]{"/liveTemplates/go", "/liveTemplates/goTags"}; } @Nullable @Override public String[] getHiddenLiveTemplateFiles() { return new String[]{"/liveTemplates/goHidden"}; } } ================================================ FILE: src/com/goide/tree/ExportabilityComparator.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.tree; import com.goide.psi.GoNamedElement; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import java.util.Comparator; public class ExportabilityComparator implements Comparator { public static final Comparator INSTANCE = new ExportabilityComparator(); @Override public int compare(@NotNull Object descriptor1, @NotNull Object descriptor2) { int accessLevel1 = getAccessLevel(descriptor1); int accessLevel2 = getAccessLevel(descriptor2); return accessLevel2 - accessLevel1; } private static int getAccessLevel(@NotNull Object element) { if (element instanceof GoStructureViewFactory.Element) { PsiElement value = ((GoStructureViewFactory.Element)element).getValue(); if (value instanceof GoNamedElement && ((GoNamedElement)value).isPublic()) return 1; } return -1; } } ================================================ FILE: src/com/goide/tree/ExportabilitySorter.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.tree; import com.intellij.icons.AllIcons; import com.intellij.ide.util.treeView.smartTree.ActionPresentation; import com.intellij.ide.util.treeView.smartTree.Sorter; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Comparator; public class ExportabilitySorter implements Sorter { public static final Sorter INSTANCE = new ExportabilitySorter(); private static final ActionPresentation PRESENTATION = new ActionPresentation() { @Override @NotNull public String getText() { return "Sort by Exportability"; } @Override public String getDescription() { return null; } @Override public Icon getIcon() { return AllIcons.ObjectBrowser.VisibilitySort; } }; @NonNls private static final String ID = "EXPORTABILITY_SORTER"; @Override @NotNull public Comparator getComparator() { return ExportabilityComparator.INSTANCE; } @Override public boolean isVisible() { return true; } @Override @NotNull public ActionPresentation getPresentation() { return PRESENTATION; } @Override @NotNull public String getName() { return ID; } } ================================================ FILE: src/com/goide/tree/GoPrivateMembersFilter.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.tree; import com.goide.psi.GoNamedElement; import com.intellij.ide.util.treeView.smartTree.ActionPresentation; import com.intellij.ide.util.treeView.smartTree.ActionPresentationData; import com.intellij.ide.util.treeView.smartTree.Filter; import com.intellij.ide.util.treeView.smartTree.TreeElement; import com.intellij.psi.PsiElement; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; public class GoPrivateMembersFilter implements Filter { private final static String PRIVATE_MEMBERS_FILTER_TEXT = "Show Private Members"; @Override public boolean isVisible(TreeElement treeNode) { if (treeNode instanceof GoStructureViewFactory.Element) { PsiElement psiElement = ((GoStructureViewFactory.Element)treeNode).getValue(); return !(psiElement instanceof GoNamedElement) || ((GoNamedElement)psiElement).isPublic(); } return true; } @Override public boolean isReverted() { return true; } @NotNull @Override public ActionPresentation getPresentation() { return new ActionPresentationData(PRIVATE_MEMBERS_FILTER_TEXT, null, PlatformIcons.PRIVATE_ICON); } @NotNull @Override public String getName() { return PRIVATE_MEMBERS_FILTER_TEXT; } } ================================================ FILE: src/com/goide/tree/GoStructureViewFactory.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.tree; import com.goide.GoIcons; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.sdk.GoPackageUtil; import com.intellij.ide.structureView.*; import com.intellij.ide.structureView.impl.common.PsiTreeElementBase; import com.intellij.ide.util.ActionShortcutProvider; import com.intellij.ide.util.FileStructureNodeProvider; import com.intellij.ide.util.treeView.smartTree.*; import com.intellij.lang.PsiStructureViewFactory; import com.intellij.openapi.actionSystem.Shortcut; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.StubBasedPsiElement; import com.intellij.psi.SyntaxTraverser; import com.intellij.psi.stubs.StubElement; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Collections; import java.util.List; public class GoStructureViewFactory implements PsiStructureViewFactory { @Nullable @Override public StructureViewBuilder getStructureViewBuilder(@NotNull PsiFile psiFile) { return new TreeBasedStructureViewBuilder() { @NotNull @Override public StructureViewModel createStructureViewModel(@Nullable Editor editor) { return new Model(psiFile, editor); } @Override public boolean isRootNodeShown() { return false; } }; } public static class Model extends StructureViewModelBase implements StructureViewModel.ElementInfoProvider { private static final List PROVIDERS = ContainerUtil.newSmartList(new TreeElementFileStructureNodeProvider()); Model(@NotNull PsiFile file, @Nullable Editor editor) { super(file, editor, new Element(file)); withSuitableClasses(GoFile.class, GoNamedElement.class) .withSorters(ExportabilitySorter.INSTANCE, Sorter.ALPHA_SORTER); } @NotNull @Override public Filter[] getFilters() { return new Filter[]{new GoPrivateMembersFilter()}; } @Override public boolean isAlwaysShowsPlus(StructureViewTreeElement structureViewTreeElement) { return false; } @Override public boolean isAlwaysLeaf(StructureViewTreeElement structureViewTreeElement) { return false; } @NotNull @Override public Collection getNodeProviders() { return PROVIDERS; } private static class TreeElementFileStructureNodeProvider implements FileStructureNodeProvider, ActionShortcutProvider { public static final String ID = "Show package structure"; @NotNull @Override public ActionPresentation getPresentation() { return new ActionPresentationData(ID, null, GoIcons.PACKAGE); } @NotNull @Override public String getName() { return ID; } @NotNull @Override public Collection provideNodes(@NotNull TreeElement node) { PsiElement psi = node instanceof Element ? ((Element)node).getElement() : null; if (psi instanceof GoFile) { GoFile orig = (GoFile)psi; List result = ContainerUtil.newSmartList(); for (GoFile f : GoPackageUtil.getAllPackageFiles(orig)) { if (f != orig) { ContainerUtil.addAll(result, new Element(f).getChildren()); } } return result; } return Collections.emptyList(); } @NotNull @Override public String getCheckBoxText() { return ID; } @NotNull @Override public Shortcut[] getShortcut() { throw new IncorrectOperationException("see getActionIdForShortcut()"); } @NotNull @Override public String getActionIdForShortcut() { return "FileStructurePopup"; } } } public static class Element extends PsiTreeElementBase { public Element(@NotNull PsiElement e) { super(e); } @NotNull @Override public Collection getChildrenBase() { List result = ContainerUtil.newArrayList(); PsiElement element = getElement(); if (element instanceof GoFile) { for (GoTypeSpec o : ((GoFile)element).getTypes()) result.add(new Element(o)); for (GoConstDefinition o : ((GoFile)element).getConstants()) result.add(new Element(o)); for (GoVarDefinition o : ((GoFile)element).getVars()) result.add(new Element(o)); for (GoFunctionDeclaration o : ((GoFile)element).getFunctions()) result.add(new Element(o)); for (GoMethodDeclaration o : ((GoFile)element).getMethods()) { GoType type = o.getReceiverType(); GoTypeReferenceExpression e = GoPsiImplUtil.getTypeReference(type); PsiElement resolve = e != null ? e.resolve() : null; if (resolve == null) { result.add(new Element(o)); } } } else if (element instanceof GoTypeSpec) { GoTypeSpec typeSpec = (GoTypeSpec)element; GoType type = typeSpec.getSpecType().getType(); for (GoMethodDeclaration m : typeSpec.getMethods()) result.add(new Element(m)); if (type instanceof GoStructType) { for (GoFieldDeclaration field : ((GoStructType)type).getFieldDeclarationList()) { for (GoFieldDefinition definition : field.getFieldDefinitionList()) result.add(new Element(definition)); GoAnonymousFieldDefinition anon = field.getAnonymousFieldDefinition(); if (anon != null) result.add(new Element(anon)); } } else if (type instanceof GoInterfaceType) { for (GoMethodSpec m : ((GoInterfaceType)type).getMethodSpecList()) result.add(new Element(m)); } } else if (element instanceof GoFunctionOrMethodDeclaration) { StubElement stub = ((StubBasedPsiElement)element).getStub(); Iterable list = stub != null ? GoPsiTreeUtil.getStubChildrenOfTypeAsList(element, GoTypeSpec.class) : SyntaxTraverser.psiTraverser(((GoFunctionOrMethodDeclaration)element).getBlock()).filter(GoTypeSpec.class); for (GoTypeSpec s : list) { result.add(new Element(s)); } } return result; } @Nullable @Override public String getPresentableText() { String textInner = getPresentationTextInner(); return textInner != null ? textInner.replaceAll("\\(\\n", "(").replaceAll("\\n\\)", ")") : null; } @Nullable private String getPresentationTextInner() { PsiElement element = getElement(); if (element == null) { return null; } String separator = ": "; if (element instanceof GoFile) { return ((GoFile)element).getName(); } if (element instanceof GoNamedSignatureOwner) { GoSignature signature = ((GoNamedSignatureOwner)element).getSignature(); String signatureText = signature != null ? signature.getText() : ""; String name = ((GoNamedSignatureOwner)element).getName(); return StringUtil.notNullize(name) + signatureText; } if (element instanceof GoTypeSpec) { GoType type = ((GoTypeSpec)element).getSpecType().getType(); String appendix = type instanceof GoStructType || type instanceof GoInterfaceType ? "" : separator + GoPsiImplUtil.getText(type); return ((GoTypeSpec)element).getName() + appendix; } if (element instanceof GoNamedElement) { GoType type = null; try { type = ((GoNamedElement)element).getGoType(null); } catch (IndexNotReadyException ignored) { } String typeText = type == null || element instanceof GoAnonymousFieldDefinition ? "" : separator + GoPsiImplUtil.getText(type); return ((GoNamedElement)element).getName() + typeText; } Logger.getInstance(GoStructureViewFactory.class).error("Cannot get presentation for " + element.getClass().getName()); return null; } } } ================================================ FILE: src/com/goide/ui/ProjectTutorialNotification.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.ui; import com.goide.GoConstants; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.components.ApplicationComponent; import org.jetbrains.annotations.NotNull; public class ProjectTutorialNotification implements ApplicationComponent { private static final String GO_PROJECT_TUTORIAL_NOTIFICATION_SHOWN = "go.tutorial.project.notification.shown"; @Override public void initComponent() { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); boolean wasDisplayed; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (propertiesComponent) { wasDisplayed = propertiesComponent.getBoolean(GO_PROJECT_TUTORIAL_NOTIFICATION_SHOWN, false); propertiesComponent.setValue(GO_PROJECT_TUTORIAL_NOTIFICATION_SHOWN, true); } if (wasDisplayed) return; Notifications.Bus.notify(GoConstants.GO_NOTIFICATION_GROUP.createNotification("Learn how to setup a new Go project", "Please visit our " + "wiki page" + " to learn how to setup a new Go project", NotificationType.INFORMATION, NotificationListener.URL_OPENING_LISTENER)); } @Override public void disposeComponent() { } @NotNull @Override public String getComponentName() { return getClass().getName(); } } ================================================ FILE: src/com/goide/usages/GoFileStructureGroupRuleProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.usages; import com.goide.psi.GoFunctionOrMethodDeclaration; import com.goide.psi.GoNamedElement; import com.goide.psi.GoTypeSpec; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.usages.PsiElementUsageGroupBase; import com.intellij.usages.impl.FileStructureGroupRuleProvider; import com.intellij.usages.rules.PsiElementUsage; import com.intellij.usages.rules.UsageGroupingRule; import org.jetbrains.annotations.Nullable; public class GoFileStructureGroupRuleProvider implements FileStructureGroupRuleProvider { public static final UsageGroupingRule USAGE_GROUPING_RULE = usage -> { PsiElement psiElement = usage instanceof PsiElementUsage ? ((PsiElementUsage)usage).getElement() : null; GoNamedElement topmostElement = PsiTreeUtil.getParentOfType(psiElement, GoTypeSpec.class, GoFunctionOrMethodDeclaration.class); if (topmostElement != null) { return new PsiElementUsageGroupBase<>(topmostElement); } return null; }; @Nullable @Override public UsageGroupingRule getUsageGroupingRule(Project project) { return USAGE_GROUPING_RULE; } } ================================================ FILE: src/com/goide/usages/GoFindUsagesProvider.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.usages; import com.goide.GoParserDefinition; import com.goide.GoTypes; import com.goide.lexer.GoLexer; import com.goide.psi.*; import com.intellij.lang.HelpID; import com.intellij.lang.cacheBuilder.DefaultWordsScanner; import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.lang.findUsages.FindUsagesProvider; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.TokenSet; import com.intellij.usageView.UsageViewLongNameLocation; import com.intellij.usageView.UsageViewShortNameLocation; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFindUsagesProvider implements FindUsagesProvider { @Nullable @Override public WordsScanner getWordsScanner() { return new DefaultWordsScanner(new GoLexer(), TokenSet.create(GoTypes.IDENTIFIER), GoParserDefinition.COMMENTS, GoParserDefinition.STRING_LITERALS); } @Override public boolean canFindUsagesFor(@NotNull PsiElement element) { if (element instanceof GoImportSpec) { GoImportSpec importSpec = (GoImportSpec)element; return importSpec.getAlias() != null && !importSpec.isDot() && !importSpec.isForSideEffects(); } return element instanceof GoNamedElement; } @Nullable @Override public String getHelpId(@NotNull PsiElement psiElement) { return HelpID.FIND_OTHER_USAGES; } @NotNull @Override public String getType(@NotNull PsiElement element) { if (element instanceof GoMethodDeclaration) return "method"; if (element instanceof GoFunctionDeclaration) return "function"; if (element instanceof GoConstDefinition || element instanceof GoConstDeclaration) return "constant"; if (element instanceof GoVarDefinition || element instanceof GoVarDeclaration) return "variable"; if (element instanceof GoParamDefinition) return "parameter"; if (element instanceof GoFieldDefinition) return "field"; if (element instanceof GoAnonymousFieldDefinition) return "anonymous field"; if (element instanceof GoTypeSpec || element instanceof GoTypeDeclaration) return "type"; if (element instanceof GoImportDeclaration) return "import"; if (element instanceof GoImportSpec) return "import alias"; if (element instanceof GoReceiver) return "receiver"; if (element instanceof GoMethodSpec) return "method specification"; if (element instanceof GoLabelDefinition) return "label"; if (element instanceof GoPackageClause) return "package statement"; // should be last if (element instanceof GoStatement) return "statement"; if (element instanceof GoTopLevelDeclaration) return "declaration"; if (element instanceof GoCommClause || element instanceof GoCaseClause) return "case"; return ""; } @NotNull @Override public String getDescriptiveName(@NotNull PsiElement element) { return ElementDescriptionUtil.getElementDescription(element, UsageViewLongNameLocation.INSTANCE); } @NotNull @Override public String getNodeText(@NotNull PsiElement element, boolean useFullName) { return ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE); } } ================================================ FILE: src/com/goide/usages/GoReadWriteAccessDetector.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.usages; import com.goide.psi.*; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoReadWriteAccessDetector extends ReadWriteAccessDetector { @Override public boolean isReadWriteAccessible(@Nullable PsiElement e) { return e instanceof GoVarDefinition || e instanceof GoConstDefinition || e instanceof GoParamDefinition || e instanceof GoReceiver || e instanceof GoFieldDefinition; } @Override public boolean isDeclarationWriteAccess(@Nullable PsiElement e) { return e instanceof GoVarDefinition || e instanceof GoConstDefinition; } @NotNull @Override public Access getReferenceAccess(@Nullable PsiElement referencedElement, @NotNull PsiReference reference) { return getExpressionAccess(reference.getElement()); } @NotNull @Override public Access getExpressionAccess(@Nullable PsiElement e) { if (e instanceof GoFieldName) { return e.getParent() instanceof GoKey ? Access.Write : Access.Read; } GoReferenceExpression referenceExpression = PsiTreeUtil.getNonStrictParentOfType(e, GoReferenceExpression.class); return referenceExpression != null ? referenceExpression.getReadWriteAccess() : Access.Read; } } ================================================ FILE: src/com/goide/util/GoBuildMatcher.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoConstants; import com.goide.psi.GoFile; import com.goide.sdk.GoSdkUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.regex.Pattern; /** * @see "$GOROOT/src/go/build/build.go" and relevant functions */ public class GoBuildMatcher { private static final Pattern WHITESPACES = Pattern.compile("\\s+"); @NotNull private final GoTargetSystem myTarget; public GoBuildMatcher(@NotNull GoTargetSystem target) { myTarget = target; } public boolean matchFile(@NotNull PsiFile file) { return matchFile(file, true); } /** * @param checkBuildFlags should be false for directly used files: go run gen.go */ private boolean matchFile(@NotNull PsiFile file, boolean checkBuildFlags) { if (!(file instanceof GoFile)) { // TODO support .c, .cpp and other return false; } if (((GoFile)file).hasCPathImport() && myTarget.cgoEnabled != ThreeState.YES) return false; return match(file.getName(), ((GoFile)file).getBuildFlags(), checkBuildFlags); } private boolean match(@NotNull String fileName, @Nullable String buildFlags, boolean checkBuildFlags) { if (!matchFileName(fileName)) return false; if (!checkBuildFlags || buildFlags == null) return true; for (String line : StringUtil.split(buildFlags, "|")) { if (!matchBuildFlagsLine(line)) return false; } return true; } private boolean matchBuildFlagsLine(@NotNull String line) { for (String tag : WHITESPACES.split(line)) { if (matchBuildFlag(tag)) return true; } return false; } public boolean matchBuildFlag(@NotNull String name) { if (name.isEmpty()) return false; if (StringUtil.containsChar(name, ',')) { // comma separated list for (String tag : StringUtil.split(name, ",")) { if (!matchBuildFlag(tag)) { return false; } } return true; } // bad syntax, reject always if (name.startsWith("!!")) return false; // negation if (name.startsWith("!")) return !matchBuildFlag(name.substring(1)); if (matchOS(name)) return true; if (GoConstants.KNOWN_COMPILERS.contains(name)) { return myTarget.compiler == null || name.equals(myTarget.compiler); } if (GoConstants.KNOWN_VERSIONS.contains(name)) { return myTarget.goVersion == null || GoSdkUtil.compareVersions(myTarget.goVersion, StringUtil.trimStart(name, "go")) >= 0; } if ("cgo".equals(name)) { return myTarget.cgoEnabled == ThreeState.YES; } return myTarget.supportsFlag(name); } public boolean matchFileName(@NotNull String fileName) { String name = StringUtil.substringAfter(fileName, "_"); if (StringUtil.isEmpty(name)) { return true; } name = StringUtil.trimEnd(FileUtil.getNameWithoutExtension(name), GoConstants.TEST_SUFFIX); List parts = StringUtil.split(name, "_"); int n = parts.size(); if (n >= 2 && GoConstants.KNOWN_OS.contains(parts.get(n - 2)) && GoConstants.KNOWN_ARCH.contains(parts.get(n - 1))) { if (!myTarget.arch.equals(parts.get(n - 1))) { return false; } return matchOS(parts.get(n - 2)); } if (n >= 1) { if (GoConstants.KNOWN_OS.contains(parts.get(n - 1))) { return matchOS(parts.get(n - 1)); } if (GoConstants.KNOWN_ARCH.contains(parts.get(n - 1))) { return myTarget.arch.equals(parts.get(n - 1)); } } return true; } private boolean matchOS(@NotNull String name) { if (myTarget.os.equals(name) || myTarget.arch.equals(name)) { return true; } return GoConstants.LINUX_OS.equals(name) && GoConstants.ANDROID_OS.equals(myTarget.os); } } ================================================ FILE: src/com/goide/util/GoExecutor.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoConstants; import com.goide.project.GoModuleSettings; import com.goide.runconfig.GoConsoleFilter; import com.goide.runconfig.GoRunUtil; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionHelper; import com.intellij.execution.ExecutionModes; import com.intellij.execution.RunContentExecutor; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.configurations.PtyCommandLine; import com.intellij.execution.process.*; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.util.Consumer; import com.intellij.util.EnvironmentUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.Map; public class GoExecutor { private static final Logger LOGGER = Logger.getInstance(GoExecutor.class); @NotNull private final Map myExtraEnvironment = ContainerUtil.newHashMap(); @NotNull private final ParametersList myParameterList = new ParametersList(); @NotNull private final ProcessOutput myProcessOutput = new ProcessOutput(); @NotNull private final Project myProject; @Nullable private Boolean myVendoringEnabled; @Nullable private final Module myModule; @Nullable private String myGoRoot; @Nullable private String myGoPath; @Nullable private String myEnvPath; @Nullable private String myWorkDirectory; private boolean myShowOutputOnError; private boolean myShowNotificationsOnError; private boolean myShowNotificationsOnSuccess; private boolean myShowGoEnvVariables = true; private GeneralCommandLine.ParentEnvironmentType myParentEnvironmentType = GeneralCommandLine.ParentEnvironmentType.CONSOLE; private boolean myPtyDisabled; @Nullable private String myExePath; @Nullable private String myPresentableName; private OSProcessHandler myProcessHandler; private final Collection myProcessListeners = ContainerUtil.newArrayList(); private GoExecutor(@NotNull Project project, @Nullable Module module) { myProject = project; myModule = module; } public static GoExecutor in(@NotNull Project project, @Nullable Module module) { return module != null ? in(module) : in(project); } @NotNull private static GoExecutor in(@NotNull Project project) { return new GoExecutor(project, null) .withGoRoot(GoSdkService.getInstance(project).getSdkHomePath(null)) .withGoPath(GoSdkUtil.retrieveGoPath(project, null)) .withGoPath(GoSdkUtil.retrieveEnvironmentPathForGo(project, null)); } @NotNull public static GoExecutor in(@NotNull Module module) { Project project = module.getProject(); ThreeState vendoringEnabled = GoModuleSettings.getInstance(module).getVendoringEnabled(); return new GoExecutor(project, module) .withGoRoot(GoSdkService.getInstance(project).getSdkHomePath(module)) .withGoPath(GoSdkUtil.retrieveGoPath(project, module)) .withEnvPath(GoSdkUtil.retrieveEnvironmentPathForGo(project, module)) .withVendoring(vendoringEnabled != ThreeState.UNSURE ? vendoringEnabled.toBoolean() : null); } @NotNull public GoExecutor withPresentableName(@Nullable String presentableName) { myPresentableName = presentableName; return this; } @NotNull public GoExecutor withExePath(@Nullable String exePath) { myExePath = exePath; return this; } @NotNull public GoExecutor withWorkDirectory(@Nullable String workDirectory) { myWorkDirectory = workDirectory; return this; } @NotNull public GoExecutor withGoRoot(@Nullable String goRoot) { myGoRoot = goRoot; return this; } @NotNull public GoExecutor withGoPath(@Nullable String goPath) { myGoPath = goPath; return this; } @NotNull public GoExecutor withEnvPath(@Nullable String envPath) { myEnvPath = envPath; return this; } @NotNull public GoExecutor withVendoring(@Nullable Boolean enabled) { myVendoringEnabled = enabled; return this; } public GoExecutor withProcessListener(@NotNull ProcessListener listener) { myProcessListeners.add(listener); return this; } @NotNull public GoExecutor withExtraEnvironment(@NotNull Map environment) { myExtraEnvironment.putAll(environment); return this; } @NotNull public GoExecutor withPassParentEnvironment(boolean passParentEnvironment) { myParentEnvironmentType = passParentEnvironment ? GeneralCommandLine.ParentEnvironmentType.CONSOLE : GeneralCommandLine.ParentEnvironmentType.NONE; return this; } @NotNull public GoExecutor withParameterString(@NotNull String parameterString) { myParameterList.addParametersString(parameterString); return this; } @NotNull public GoExecutor withParameters(@NotNull String... parameters) { myParameterList.addAll(parameters); return this; } public GoExecutor showGoEnvVariables(boolean show) { myShowGoEnvVariables = show; return this; } @NotNull public GoExecutor showOutputOnError() { myShowOutputOnError = true; return this; } @NotNull public GoExecutor disablePty() { myPtyDisabled = true; return this; } @NotNull public GoExecutor showNotifications(boolean onError, boolean onSuccess) { myShowNotificationsOnError = onError; myShowNotificationsOnSuccess = onSuccess; return this; } public boolean execute() { Logger.getInstance(getClass()).assertTrue(!ApplicationManager.getApplication().isDispatchThread(), "It's bad idea to run external tool on EDT"); Logger.getInstance(getClass()).assertTrue(myProcessHandler == null, "Process has already run with this executor instance"); Ref result = Ref.create(false); GeneralCommandLine commandLine = null; try { commandLine = createCommandLine(); GeneralCommandLine finalCommandLine = commandLine; myProcessHandler = new KillableColoredProcessHandler(finalCommandLine, true) { @Override public void startNotify() { if (myShowGoEnvVariables) { GoRunUtil.printGoEnvVariables(finalCommandLine, this); } super.startNotify(); } }; GoHistoryProcessListener historyProcessListener = new GoHistoryProcessListener(); myProcessHandler.addProcessListener(historyProcessListener); for (ProcessListener listener : myProcessListeners) { myProcessHandler.addProcessListener(listener); } CapturingProcessAdapter processAdapter = new CapturingProcessAdapter(myProcessOutput) { @Override public void processTerminated(@NotNull ProcessEvent event) { super.processTerminated(event); boolean success = event.getExitCode() == 0 && myProcessOutput.getStderr().isEmpty(); boolean nothingToShow = myProcessOutput.getStdout().isEmpty() && myProcessOutput.getStderr().isEmpty(); boolean cancelledByUser = (event.getExitCode() == -1 || event.getExitCode() == 2) && nothingToShow; result.set(success); if (success) { if (myShowNotificationsOnSuccess) { showNotification("Finished successfully", NotificationType.INFORMATION); } } else if (cancelledByUser) { if (myShowNotificationsOnError) { showNotification("Interrupted", NotificationType.WARNING); } } else if (myShowOutputOnError) { ApplicationManager.getApplication().invokeLater(() -> showOutput(myProcessHandler, historyProcessListener)); } } }; myProcessHandler.addProcessListener(processAdapter); myProcessHandler.startNotify(); ExecutionModes.SameThreadMode sameThreadMode = new ExecutionModes.SameThreadMode(getPresentableName()); ExecutionHelper.executeExternalProcess(myProject, myProcessHandler, sameThreadMode, commandLine); LOGGER.debug("Finished `" + getPresentableName() + "` with result: " + result.get()); return result.get(); } catch (ExecutionException e) { if (myShowOutputOnError) { ExecutionHelper.showErrors(myProject, Collections.singletonList(e), getPresentableName(), null); } if (myShowNotificationsOnError) { showNotification(StringUtil.notNullize(e.getMessage(), "Unknown error, see logs for details"), NotificationType.ERROR); } String commandLineInfo = commandLine != null ? commandLine.getCommandLineString() : "not constructed"; LOGGER.debug("Finished `" + getPresentableName() + "` with an exception. Commandline: " + commandLineInfo, e); return false; } } public void executeWithProgress(boolean modal) { //noinspection unchecked executeWithProgress(modal, Consumer.EMPTY_CONSUMER); } public void executeWithProgress(boolean modal, @NotNull Consumer consumer) { ProgressManager.getInstance().run(new Task.Backgroundable(myProject, getPresentableName(), true) { private boolean doNotStart; @Override public void onCancel() { doNotStart = true; ProcessHandler handler = getProcessHandler(); if (handler != null) { handler.destroyProcess(); } } @Override public boolean shouldStartInBackground() { return !modal; } @Override public boolean isConditionalModal() { return modal; } @Override public void run(@NotNull ProgressIndicator indicator) { if (doNotStart || myProject == null || myProject.isDisposed()) { return; } indicator.setIndeterminate(true); consumer.consume(execute()); } }); } @Nullable public ProcessHandler getProcessHandler() { return myProcessHandler; } private void showNotification(@NotNull String message, NotificationType type) { ApplicationManager.getApplication().invokeLater(() -> { String title = getPresentableName(); Notifications.Bus.notify(GoConstants.GO_EXECUTION_NOTIFICATION_GROUP.createNotification(title, message, type, null), myProject); }); } private void showOutput(@NotNull OSProcessHandler originalHandler, @NotNull GoHistoryProcessListener historyProcessListener) { if (myShowOutputOnError) { BaseOSProcessHandler outputHandler = new KillableColoredProcessHandler(originalHandler.getProcess(), null); RunContentExecutor runContentExecutor = new RunContentExecutor(myProject, outputHandler) .withTitle(getPresentableName()) .withActivateToolWindow(myShowOutputOnError) .withFilter(new GoConsoleFilter(myProject, myModule, myWorkDirectory != null ? VfsUtilCore.pathToUrl(myWorkDirectory) : null)); Disposer.register(myProject, runContentExecutor); runContentExecutor.run(); historyProcessListener.apply(outputHandler); } if (myShowNotificationsOnError) { showNotification("Failed to run", NotificationType.ERROR); } } @NotNull public GeneralCommandLine createCommandLine() throws ExecutionException { if (myGoRoot == null) { throw new ExecutionException("Sdk is not set or Sdk home path is empty for module"); } GeneralCommandLine commandLine = !myPtyDisabled && PtyCommandLine.isEnabled() ? new PtyCommandLine() : new GeneralCommandLine(); commandLine.setExePath(ObjectUtils.notNull(myExePath, GoSdkService.getGoExecutablePath(myGoRoot))); commandLine.getEnvironment().putAll(myExtraEnvironment); commandLine.getEnvironment().put(GoConstants.GO_ROOT, StringUtil.notNullize(myGoRoot)); commandLine.getEnvironment().put(GoConstants.GO_PATH, StringUtil.notNullize(myGoPath)); if (myVendoringEnabled != null) { commandLine.getEnvironment().put(GoConstants.GO_VENDORING_EXPERIMENT, myVendoringEnabled ? "1" : "0"); } Collection paths = ContainerUtil.newArrayList(); ContainerUtil.addIfNotNull(paths, StringUtil.nullize(commandLine.getEnvironment().get(GoConstants.PATH), true)); ContainerUtil.addIfNotNull(paths, StringUtil.nullize(EnvironmentUtil.getValue(GoConstants.PATH), true)); ContainerUtil.addIfNotNull(paths, StringUtil.nullize(myEnvPath, true)); commandLine.getEnvironment().put(GoConstants.PATH, StringUtil.join(paths, File.pathSeparator)); commandLine.withWorkDirectory(myWorkDirectory); commandLine.addParameters(myParameterList.getList()); commandLine.withParentEnvironmentType(myParentEnvironmentType); commandLine.withCharset(CharsetToolkit.UTF8_CHARSET); return commandLine; } @NotNull private String getPresentableName() { return ObjectUtils.notNull(myPresentableName, "go"); } } ================================================ FILE: src/com/goide/util/GoHistoryProcessListener.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessHandler; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import java.util.concurrent.ConcurrentLinkedQueue; public class GoHistoryProcessListener extends ProcessAdapter { private final ConcurrentLinkedQueue> myHistory = new ConcurrentLinkedQueue<>(); @Override public void onTextAvailable(ProcessEvent event, Key outputType) { myHistory.add(Pair.create(event, outputType)); } public void apply(ProcessHandler listener) { for (Pair pair : myHistory) { listener.notifyTextAvailable(pair.getFirst().getText(), pair.getSecond()); } } } ================================================ FILE: src/com/goide/util/GoPathResolveScope.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.sdk.GoSdkService; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoPathResolveScope extends GlobalSearchScope { @Nullable private final VirtualFile myReferenceFile; @NotNull private final GoPathScopeHelper myScopeHelper; public static GlobalSearchScope create(@NotNull Project project, @Nullable Module module, @Nullable PsiElement context) { VirtualFile referenceFile = context != null ? context.getContainingFile().getVirtualFile() : null; return new GoPathResolveScope(project, referenceFile, GoPathScopeHelper.fromReferenceFile(project, module, referenceFile)); } private GoPathResolveScope(@NotNull Project project, @Nullable VirtualFile referenceFile, @NotNull GoPathScopeHelper scopeHelper) { super(project); myScopeHelper = scopeHelper; myReferenceFile = referenceFile; } @Override public boolean contains(@NotNull VirtualFile declarationFile) { VirtualFile declarationDirectory = declarationFile.isDirectory() ? declarationFile : declarationFile.getParent(); if (declarationDirectory == null) { return false; } if (myReferenceFile != null && declarationDirectory.equals(myReferenceFile.getParent())) { return true; } return myScopeHelper.couldBeReferenced(declarationFile, myReferenceFile); } @Override public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) { return 0; } @Override public boolean isSearchInModuleContent(@NotNull Module aModule) { return GoSdkService.getInstance(ObjectUtils.assertNotNull(getProject())).isGoModule(aModule); } @Override public boolean isSearchInLibraries() { return true; } } ================================================ FILE: src/com/goide/util/GoPathScopeHelper.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoConstants; import com.goide.project.GoVendoringUtil; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.sdk.GoSdkService; import com.goide.sdk.GoSdkUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Set; public class GoPathScopeHelper { @NotNull private final Set myRoots; @Nullable private final VirtualFile mySdkHome; private final boolean mySupportsInternalPackages; private final boolean mySupportsSdkInternalPackages; private final boolean myVendoringEnabled; public static GoPathScopeHelper fromReferenceFile(@NotNull Project project, @Nullable Module module, @Nullable VirtualFile referenceFile) { VirtualFile sdkHome = GoSdkUtil.getSdkSrcDir(project, module); String sdkVersion = GoSdkService.getInstance(project).getSdkVersion(module); boolean supportsInternalPackages = GoVendoringUtil.supportsInternalPackages(sdkVersion); boolean supportsSdkInternalPackages = GoVendoringUtil.supportsSdkInternalPackages(sdkVersion); boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module); Set sourceRoots = vendoringEnabled ? GoSdkUtil.getVendoringAwareSourcesPathsToLookup(project, module, referenceFile) : GoSdkUtil.getSourcesPathsToLookup(project, module); return new GoPathScopeHelper(sourceRoots, sdkHome, supportsInternalPackages, supportsSdkInternalPackages, vendoringEnabled); } private GoPathScopeHelper(@NotNull Set roots, @Nullable VirtualFile sdkHome, boolean supportsInternalPackages, boolean supportsSdkInternalPackages, boolean vendoringEnabled) { myRoots = roots; mySdkHome = sdkHome; mySupportsInternalPackages = supportsInternalPackages; mySupportsSdkInternalPackages = supportsSdkInternalPackages; myVendoringEnabled = vendoringEnabled; } public boolean couldBeReferenced(@NotNull VirtualFile declarationFile, @Nullable VirtualFile referenceFile) { VirtualFile declarationDirectory = declarationFile.getParent(); if (declarationDirectory == null) { return true; } if (ApplicationManager.getApplication().isUnitTestMode() && myRoots.contains(declarationDirectory)) { return true; } String importPath = GoSdkUtil.getRelativePathToRoots(declarationDirectory, myRoots); if (importPath == null) { return false; } if (importPath.isEmpty()) { return true; } VirtualFile referenceDirectory = referenceFile != null ? referenceFile.getParent() : null; if (referenceDirectory != null) { if (myVendoringEnabled && GoSdkUtil.isUnreachableVendoredPackage(declarationDirectory, referenceDirectory, myRoots)) { return false; } boolean declarationIsInSdk = mySdkHome != null && VfsUtilCore.isAncestor(mySdkHome, declarationDirectory, false); if (mySupportsInternalPackages || mySupportsSdkInternalPackages && declarationIsInSdk) { if (GoSdkUtil.isUnreachableInternalPackage(declarationDirectory, referenceDirectory, myRoots)) { return false; } } if (declarationIsInSdk && GoSdkUtil.findParentDirectory(declarationDirectory, myRoots, GoConstants.TESTDATA_NAME) != null) { return false; } else { boolean referenceIsInSdk = mySdkHome != null && VfsUtilCore.isAncestor(mySdkHome, referenceDirectory, false); if (referenceIsInSdk) { return false; } } } return GoPsiImplUtil.allowed(declarationFile, referenceFile) && !isShadowedImportPath(declarationDirectory, importPath, myRoots); } private static boolean isShadowedImportPath(@NotNull VirtualFile targetDirectory, @NotNull String targetImportPath, @NotNull Collection roots) { assert targetDirectory.isDirectory(); for (VirtualFile root : roots) { VirtualFile realDirectoryToResolve = root.findFileByRelativePath(targetImportPath); if (realDirectoryToResolve != null) { return !targetDirectory.equals(realDirectoryToResolve); } } return false; } @NotNull public Set getRoots() { return myRoots; } public boolean isVendoringEnabled() { return myVendoringEnabled; } } ================================================ FILE: src/com/goide/util/GoPathUseScope.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.psi.GoFile; import com.goide.psi.GoImportSpec; import com.goide.psi.GoNamedElement; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.psi.impl.imports.GoImportReferenceSet; import com.goide.sdk.GoPackageUtil; import com.goide.sdk.GoSdkService; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.Set; public class GoPathUseScope extends GlobalSearchScope { public static GlobalSearchScope create(@NotNull PsiElement declarationContext, boolean filterByImportList) { if (declarationContext instanceof GoNamedElement && ((GoNamedElement)declarationContext).isBlank()) { return GlobalSearchScope.EMPTY_SCOPE; } PsiFile declarationPsiFile = declarationContext.getContainingFile(); if (!(declarationPsiFile instanceof GoFile)) { return GlobalSearchScope.fileScope(declarationPsiFile); } if (GoPsiImplUtil.isBuiltinFile(declarationPsiFile)) { return GlobalSearchScope.allScope(declarationContext.getProject()); } VirtualFile declarationFile = declarationPsiFile.getVirtualFile(); if (declarationFile == null || declarationFile.getParent() == null) { return GlobalSearchScope.fileScope(declarationPsiFile); } return new GoPathUseScope(declarationPsiFile.getProject(), declarationFile, filterByImportList); } @NotNull private final VirtualFile myDeclarationFile; private final boolean myFilterByImportList; private GoPathUseScope(@NotNull Project project, @NotNull VirtualFile declarationFile, boolean filterByImportList) { super(project); myDeclarationFile = declarationFile; myFilterByImportList = filterByImportList; } @Override public boolean contains(@NotNull VirtualFile referenceFile) { VirtualFile referenceDirectory = referenceFile.isDirectory() ? referenceFile : referenceFile.getParent(); if (referenceDirectory == null) { return false; } VirtualFile declarationDirectory = myDeclarationFile.getParent(); if (referenceDirectory.equals(declarationDirectory)) { return true; } Project project = ObjectUtils.assertNotNull(getProject()); PsiManager psiManager = PsiManager.getInstance(project); PsiFile referencePsiFile = psiManager.findFile(referenceFile); Module module = referencePsiFile != null ? ModuleUtilCore.findModuleForPsiElement(referencePsiFile) : null; GoPathScopeHelper scopeHelper = GoPathScopeHelper.fromReferenceFile(project, module, referenceFile); if (!scopeHelper.couldBeReferenced(myDeclarationFile, referenceFile)) { return false; } if (!myFilterByImportList) { return true; } if (!(referencePsiFile instanceof GoFile)) { // it's some injection or cross-reference, so we cannot check its imports return true; } PsiFile declarationPsiFile = psiManager.findFile(myDeclarationFile); if (declarationPsiFile instanceof GoFile) { String importPath = ((GoFile)declarationPsiFile).getImportPath(scopeHelper.isVendoringEnabled()); Map importedPackagesMap = ((GoFile)referencePsiFile).getImportedPackagesMap(); if (importedPackagesMap.containsKey(importPath)) { return true; } if (hasRelativeImportOfTargetPackage(importedPackagesMap.keySet(), referenceDirectory, declarationDirectory)) { return true; } for (GoFile packageFile : GoPackageUtil.getAllPackageFiles(referencePsiFile.getContainingDirectory(), null)) { if (packageFile != referencePsiFile && referencePsiFile.getOriginalFile() != packageFile) { Map packagesMap = packageFile.getImportedPackagesMap(); if (packagesMap.containsKey(importPath)) { return true; } if (hasRelativeImportOfTargetPackage(packagesMap.keySet(), referenceDirectory, declarationDirectory)) { return true; } } } } return false; } private static boolean hasRelativeImportOfTargetPackage(@NotNull Set paths, @NotNull VirtualFile referenceDirectory, @NotNull VirtualFile declarationDirectory) { for (String pathString : paths) { if (GoImportReferenceSet.isRelativeImport(pathString)) { VirtualFile file = referenceDirectory.findFileByRelativePath(pathString); if (declarationDirectory.equals(file)) { return true; } } } return false; } @Override public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) { return 0; } @Override public boolean isSearchInModuleContent(@NotNull Module aModule) { return GoSdkService.getInstance(ObjectUtils.assertNotNull(getProject())).isGoModule(aModule); } @Override public boolean isSearchInLibraries() { return false; } } ================================================ FILE: src/com/goide/util/GoStringLiteralEscaper.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.psi.GoStringLiteral; import com.intellij.openapi.util.TextRange; import com.intellij.psi.LiteralTextEscaper; import org.jetbrains.annotations.NotNull; import java.util.Locale; public class GoStringLiteralEscaper extends LiteralTextEscaper { private int[] outSourceOffsets; public GoStringLiteralEscaper(@NotNull GoStringLiteral host) { super(host); } @Override public boolean decode(@NotNull TextRange rangeInsideHost, @NotNull StringBuilder outChars) { TextRange.assertProperRange(rangeInsideHost); String subText = rangeInsideHost.substring(myHost.getText()); if (myHost.getRawString() != null) { outChars.append(subText); return true; } return parseStringCharacters(subText, outChars); } @Override public int getOffsetInHost(int offsetInDecoded, @NotNull TextRange rangeInsideHost) { TextRange.assertProperRange(rangeInsideHost); if (myHost.getRawString() != null) { int offset = offsetInDecoded; offset += rangeInsideHost.getStartOffset(); return offset > rangeInsideHost.getEndOffset() ? -1 : offset; } int result = offsetInDecoded < outSourceOffsets.length ? outSourceOffsets[offsetInDecoded] : -1; if (result == -1) return -1; return (result <= rangeInsideHost.getLength() ? result : rangeInsideHost.getLength()) + rangeInsideHost.getStartOffset(); } /** * Escapes the specified string in accordance with https://golang.org/ref/spec#Rune_literals * * @param chars * @param outChars */ public static void escapeString(@NotNull String chars, @NotNull StringBuilder outChars) { int index = 0; while (index < chars.length()) { int c = chars.codePointAt(index); switch (c) { case (char)7: outChars.append("\\a"); break; case '\b': outChars.append("\\b"); break; case '\f': outChars.append("\\f"); break; case '\n': outChars.append("\\n"); break; case '\r': outChars.append("\\r"); break; case '\t': outChars.append("\\t"); break; case (char)0x0b: outChars.append("\\v"); break; case '\\': outChars.append("\\\\"); break; case '\'': outChars.append("\\'"); break; case '"': outChars.append("\\\""); break; default: switch (Character.getType(c)) { case Character.CONTROL: case Character.PRIVATE_USE: case Character.UNASSIGNED: if (c <= 0xffff) { outChars.append("\\u").append(String.format(Locale.US, "%04X", c)); } else { outChars.append("\\U").append(String.format(Locale.US, "%08X", c)); } break; default: outChars.appendCodePoint(c); } } index += Character.charCount(c); } } private boolean parseStringCharacters(String chars, StringBuilder outChars) { outSourceOffsets = new int[chars.length() + 1]; outSourceOffsets[chars.length()] = -1; if (chars.indexOf('\\') < 0) { outChars.append(chars); for (int i = 0; i < outSourceOffsets.length; i++) { outSourceOffsets[i] = i; } return true; } int index = 0; while (index < chars.length()) { char c = chars.charAt(index++); outSourceOffsets[outChars.length()] = index - 1; outSourceOffsets[outChars.length() + 1] = index; if (c != '\\') { outChars.append(c); continue; } if (index == chars.length()) return false; c = chars.charAt(index++); switch (c) { case 'a': outChars.append((char)7); break; case 'b': outChars.append('\b'); break; case 'f': outChars.append('\f'); break; case 'n': outChars.append('\n'); break; case 'r': outChars.append('\r'); break; case 't': outChars.append('\t'); break; case 'v': outChars.append((char)0x0b); break; case '\\': outChars.append('\\'); break; case '\'': outChars.append('\''); break; case '"': outChars.append('"'); break; case '\n': outChars.append('\n'); break; // octal case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { char startC = c; int v = (int)c - '0'; if (index < chars.length()) { c = chars.charAt(index++); if ('0' <= c && c <= '7') { v <<= 3; v += c - '0'; if (startC <= '3' && index < chars.length()) { c = chars.charAt(index++); if ('0' <= c && c <= '7') { v <<= 3; v += c - '0'; } else { index--; } } } else { index--; } } outChars.append((char)v); } break; // hex case 'x': if (index + 2 <= chars.length()) { try { int v = Integer.parseInt(chars.substring(index, index + 2), 16); outChars.append((char)v); index += 2; } catch (Exception e) { return false; } } else { return false; } break; // little unicode case 'u': if (index + 4 <= chars.length()) { try { int v = Integer.parseInt(chars.substring(index, index + 4), 16); c = chars.charAt(index); if (c == '+' || c == '-') return false; outChars.append((char)v); index += 4; } catch (Exception e) { return false; } } else { return false; } break; // big unicode case 'U': if (index + 8 <= chars.length()) { try { int v = Integer.parseInt(chars.substring(index, index + 8), 16); c = chars.charAt(index); if (c == '+' || c == '-') return false; outChars.append((char)v); index += 8; } catch (Exception e) { return false; } } else { return false; } break; default: return false; } outSourceOffsets[outChars.length()] = index; } return true; } @Override public boolean isOneLine() { return true; } } ================================================ FILE: src/com/goide/util/GoTargetSystem.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.goide.sdk.GoSdkService; import com.intellij.openapi.module.Module; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ArrayUtil; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Set; public class GoTargetSystem { private static final String GAE_BUILD_FLAG = "appengine"; @NotNull public final String os; @NotNull public final String arch; @Nullable public final String goVersion; @Nullable public final String compiler; @NotNull public final ThreeState cgoEnabled; private final Set customFlags = ContainerUtil.newHashSet(); public GoTargetSystem(@NotNull String os, @NotNull String arch, @Nullable String goVersion, @Nullable String compiler, @NotNull ThreeState cgoEnabled, @NotNull String... customFlags) { this.os = os; this.arch = arch; this.goVersion = goVersion; this.compiler = compiler; this.cgoEnabled = cgoEnabled; Collections.addAll(this.customFlags, customFlags); } public boolean supportsFlag(@NotNull String flag) { return customFlags.contains(flag); } @NotNull public static GoTargetSystem forModule(@NotNull Module module) { return CachedValuesManager.getManager(module.getProject()).getCachedValue(module, () -> { GoBuildTargetSettings settings = GoModuleSettings.getInstance(module).getBuildTargetSettings(); String os = realValue(settings.os, GoUtil.systemOS()); String arch = realValue(settings.arch, GoUtil.systemArch()); ThreeState cgo = settings.cgo == ThreeState.UNSURE ? GoUtil.systemCgo(os, arch) : settings.cgo; String moduleSdkVersion = GoSdkService.getInstance(module.getProject()).getSdkVersion(module); String[] customFlags = GoSdkService.getInstance(module.getProject()).isAppEngineSdk(module) ? ArrayUtil.prepend(GAE_BUILD_FLAG, settings.customFlags) : settings.customFlags; String compiler = GoBuildTargetSettings.ANY_COMPILER.equals(settings.compiler) ? null : settings.compiler; GoTargetSystem result = new GoTargetSystem(os, arch, realValue(settings.goVersion, moduleSdkVersion), compiler, cgo, customFlags); return CachedValueProvider.Result.create(result, settings); }); } @Contract("_,null->!null") private static String realValue(@NotNull String value, @Nullable String defaultValue) { return GoBuildTargetSettings.DEFAULT.equals(value) ? defaultValue : value; } } ================================================ FILE: src/com/goide/util/GoUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoConstants; import com.goide.project.GoExcludedPathsSettings; import com.goide.psi.*; import com.goide.psi.impl.GoPsiImplUtil; import com.goide.runconfig.testing.GoTestFinder; import com.goide.sdk.GoPackageUtil; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.DelegatingGlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoUtil { private static final String PLUGIN_ID = "ro.redeul.google.go"; private GoUtil() {} public static boolean matchedForModuleBuildTarget(@NotNull PsiFile file, @Nullable Module module) { return module == null || new GoBuildMatcher(GoTargetSystem.forModule(module)).matchFile(file); } public static boolean isExcludedFile(@NotNull GoFile file) { return CachedValuesManager.getCachedValue(file, () -> { String importPath = file.getImportPath(false); GoExcludedPathsSettings excludedSettings = GoExcludedPathsSettings.getInstance(file.getProject()); return CachedValueProvider.Result.create(importPath != null && excludedSettings.isExcluded(importPath), file, excludedSettings); }); } @NotNull public static String systemOS() { // TODO android? dragonfly nacl? netbsd openbsd plan9 if (SystemInfo.isMac) { return "darwin"; } if (SystemInfo.isFreeBSD) { return "freebsd"; } if (SystemInfo.isLinux) { return GoConstants.LINUX_OS; } if (SystemInfo.isSolaris) { return "solaris"; } if (SystemInfo.isWindows) { return "windows"; } return "unknown"; } @NotNull public static String systemArch() { if (SystemInfo.is64Bit) { return GoConstants.AMD64; } if (SystemInfo.isWindows) { String arch = System.getenv("PROCESSOR_ARCHITECTURE"); String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432"); return arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? GoConstants.AMD64 : "386"; } if (SystemInfo.is32Bit) { return "386"; } return "unknown"; } @NotNull public static ThreeState systemCgo(@NotNull String os, @NotNull String arch) { return GoConstants.KNOWN_CGO.contains(os + "/" + arch) ? ThreeState.YES : ThreeState.NO; } public static boolean fileToIgnore(@NotNull String fileName) { return StringUtil.startsWithChar(fileName, '_') || StringUtil.startsWithChar(fileName, '.'); } public static GlobalSearchScope goPathUseScope(@NotNull PsiElement context, boolean filterByImportList) { return GoPathUseScope.create(context, filterByImportList); } public static GlobalSearchScope goPathResolveScope(@NotNull PsiElement context) { // it's important to ask module on file, otherwise module won't be found for elements in libraries files [zolotov] Module module = ModuleUtilCore.findModuleForPsiElement(context.getContainingFile()); return GoPathResolveScope.create(context.getProject(), module, context); } public static GlobalSearchScope goPathResolveScope(@NotNull Module module, @Nullable PsiElement context) { return GoPathResolveScope.create(module.getProject(), module, context); } @NotNull public static GlobalSearchScope moduleScope(@NotNull Module module) { return GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module).uniteWith(module.getModuleContentWithDependenciesScope()); } @NotNull public static GlobalSearchScope moduleScopeWithoutLibraries(@NotNull Project project, @Nullable Module module) { return module != null ? GlobalSearchScope.moduleWithDependenciesScope(module).uniteWith(module.getModuleContentWithDependenciesScope()) : GlobalSearchScope.projectScope(project); } @NotNull @SuppressWarnings("ConstantConditions") public static IdeaPluginDescriptor getPlugin() { return PluginManager.getPlugin(PluginId.getId(PLUGIN_ID)); } /** * isReferenceTo optimization. Before complex checking via resolve we can say for sure that element * can't be a reference to given declaration in following cases:
    * – Blank definitions can't be used as value, so this method return false for all named elements with '_' name
    * – GoLabelRef can't be resolved to anything but GoLabelDefinition
    * – GoTypeReferenceExpression (not from receiver type) can't be resolved to anything but GoTypeSpec or GoImportSpec
    * – Definition is private and reference in different package
    */ public static boolean couldBeReferenceTo(@NotNull PsiElement definition, @NotNull PsiElement reference) { if (definition instanceof PsiDirectory && reference instanceof GoReferenceExpressionBase) return true; if (reference instanceof GoLabelRef && !(definition instanceof GoLabelDefinition)) return false; if (reference instanceof GoTypeReferenceExpression && !(definition instanceof GoTypeSpec || definition instanceof GoImportSpec)) { return false; } PsiFile definitionFile = definition.getContainingFile(); PsiFile referenceFile = reference.getContainingFile(); // todo: zolotov, are you sure? cross refs, for instance? if (!(definitionFile instanceof GoFile) || !(referenceFile instanceof GoFile)) return false; boolean inSameFile = definitionFile.isEquivalentTo(referenceFile); if (inSameFile) return true; if (inSamePackage(referenceFile, definitionFile)) return true; return !(reference instanceof GoNamedElement && !((GoNamedElement)reference).isPublic()); } public static boolean inSamePackage(@NotNull PsiFile firstFile, @NotNull PsiFile secondFile) { PsiDirectory containingDirectory = firstFile.getContainingDirectory(); if (containingDirectory == null || !containingDirectory.equals(secondFile.getContainingDirectory())) { return false; } if (firstFile instanceof GoFile && secondFile instanceof GoFile) { String referencePackage = ((GoFile)firstFile).getPackageName(); String definitionPackage = ((GoFile)secondFile).getPackageName(); return referencePackage != null && referencePackage.equals(definitionPackage); } return true; } @NotNull public static String suggestPackageForDirectory(@Nullable PsiDirectory directory) { String packageName = GoPsiImplUtil.getLocalPackageName(directory != null ? directory.getName() : ""); for (String p : GoPackageUtil.getAllPackagesInDirectory(directory, null, true)) { if (!GoConstants.MAIN.equals(p)) { return p; } } return packageName; } public static class ExceptTestsScope extends DelegatingGlobalSearchScope { public ExceptTestsScope(@NotNull GlobalSearchScope baseScope) { super(baseScope); } @Override public boolean contains(@NotNull VirtualFile file) { return !GoTestFinder.isTestFile(file) && super.contains(file); } } public static class TestsScope extends DelegatingGlobalSearchScope { public TestsScope(@NotNull GlobalSearchScope baseScope) { super(baseScope); } @Override public boolean contains(@NotNull VirtualFile file) { return GoTestFinder.isTestFile(file) && super.contains(file); } } public static class ExceptChildOfDirectory extends DelegatingGlobalSearchScope { @NotNull private final VirtualFile myParent; @Nullable private final String myAllowedPackageInExcludedDirectory; public ExceptChildOfDirectory(@NotNull VirtualFile parent, @NotNull GlobalSearchScope baseScope, @Nullable String allowedPackageInExcludedDirectory) { super(baseScope); myParent = parent; myAllowedPackageInExcludedDirectory = allowedPackageInExcludedDirectory; } @Override public boolean contains(@NotNull VirtualFile file) { if (myParent.equals(file.getParent())) { if (myAllowedPackageInExcludedDirectory == null) { return false; } Project project = getProject(); PsiFile psiFile = project != null ? PsiManager.getInstance(project).findFile(file) : null; if (!(psiFile instanceof GoFile)) { return false; } if (!myAllowedPackageInExcludedDirectory.equals(((GoFile)psiFile).getPackageName())) { return false; } } return super.contains(file); } } } ================================================ FILE: testData/colorHighlighting/builtinFunctions.go ================================================ package main func main() { println("demo") } ================================================ FILE: testData/colorHighlighting/funcAndMethod.go ================================================ package main type inner interface { Inner() string } type ( de interface { Demo() inner } dem struct{} ) func (a dem) Demo() inner { return error("demo") } func main() { b := dem{} b.Demo().Inner() } ================================================ FILE: testData/colorHighlighting/label.go ================================================ package main func test() int { foo: for { continue foo break foo goto foo } foo := 10 return foo } ================================================ FILE: testData/colorHighlighting/octAndHex.go ================================================ package main var a int = 0112 var b int = 0x112 var c int = 0Xabf112 ================================================ FILE: testData/colorHighlighting/receiver.go ================================================ package main func (ps PublicStruct) PublicFunc() { } ================================================ FILE: testData/colorHighlighting/simple.go ================================================ package main import `fmt` func main() { fmt.Println("Hello") } ================================================ FILE: testData/colorHighlighting/structFields.go ================================================ package main type type1 struct { var1 int } func main() { struct1 := type1{var1: 1} println(struct1.var1) } ================================================ FILE: testData/colorHighlighting/types.go ================================================ package main type ( PublicInterface interface { PublicFunc() int privateFunc() int } private interface { PublicFunc() int privateFunc() int } PublicStruct struct { PublicField int privateField int } privateStruct struct { PublicField int privateField int } demoInt int type Bla int32 func (b *Bla) Method1() {} ) ================================================ FILE: testData/completion/addSpaceAfterKeyword.go ================================================ package main func main() { defe } ================================================ FILE: testData/completion/addSpaceAfterKeyword_after.go ================================================ package main func main() { defer } ================================================ FILE: testData/completion/blockKeywords.go ================================================ package main func main() { } ================================================ FILE: testData/completion/blockKeywordsInsideCaseStatement.go ================================================ package main func main() { switch a { case 1: } } ================================================ FILE: testData/completion/blockKeywordsInsideOneLineFunction.go ================================================ package main func main() { } ================================================ FILE: testData/completion/chanKeyword.go ================================================ package foo var c, c1, c2, c3, c4 ch ================================================ FILE: testData/completion/chanKeyword_2.go ================================================ package foo func findMarker(c <- int) int { } ================================================ FILE: testData/completion/chanKeyword_2_after.go ================================================ package foo func findMarker(c <- int) int { } ================================================ FILE: testData/completion/chanKeyword_3.go ================================================ package foo var c, c1, c2, c3, c4 (ch) ================================================ FILE: testData/completion/chanKeyword_3_after.go ================================================ package foo var c, c1, c2, c3, c4 (chan ) ================================================ FILE: testData/completion/chanKeyword_after.go ================================================ package foo var c, c1, c2, c3, c4 chan ================================================ FILE: testData/completion/doNotCompleteKeywordsInsideConstSpec.go ================================================ package foo const a = ================================================ FILE: testData/completion/doNotCompleteKeywordsInsideSelectorExpression.go ================================================ package main type demo struct{} func (d demo) FuncA() demo { return d } func (d demo) FuncB() demo { return d } func main() { a := demo{} a.FuncA()..FuncB() } ================================================ FILE: testData/completion/doNotRunAutoImportCompletionAfterDot.go ================================================ package main type str struct {} func (a str) Demo() str { return str{} } func main() { a := str{} b := a.Demo().D } ================================================ FILE: testData/completion/doNotRunAutoImportCompletionAfterDotAndSpace.go ================================================ package main type str struct {} func (a str) Demo() str { return str{} } func main() { a := str{} b := a.Demo(). D } ================================================ FILE: testData/completion/doNotRunAutoImportCompletionAfterDotAndSpace_after.go ================================================ package main type str struct {} func (a str) Demo() str { return str{} } func main() { a := str{} b := a.Demo(). Demo() } ================================================ FILE: testData/completion/doNotRunAutoImportCompletionAfterDot_after.go ================================================ package main type str struct {} func (a str) Demo() str { return str{} } func main() { a := str{} b := a.Demo().Demo() } ================================================ FILE: testData/completion/elseKeyword.go ================================================ package foo func bar() { if 1 < 2 { } els } ================================================ FILE: testData/completion/elseKeywordRegression.go ================================================ package main func main() { m := "" if m == "" { } m.e } ================================================ FILE: testData/completion/elseKeyword_after.go ================================================ package foo func bar() { if 1 < 2 { } else } ================================================ FILE: testData/completion/expressionCaseKeywordCompletion.go ================================================ package foo func hi() { var a = 1 switch a { case 1: println(1) return nil cas } } ================================================ FILE: testData/completion/expressionCaseKeywordCompletion_after.go ================================================ package foo func hi() { var a = 1 switch a { case 1: println(1) return nil case : } } ================================================ FILE: testData/completion/expressionDefaultKeywordCompletion.go ================================================ package foo func hi() { var a = 1 switch a { case 1: println(1) return nil defa } } ================================================ FILE: testData/completion/expressionDefaultKeywordCompletion_after.go ================================================ package foo func hi() { var a = 1 switch a { case 1: println(1) return nil default: } } ================================================ FILE: testData/completion/expressionKeywords.go ================================================ package main func main() { println(&) } ================================================ FILE: testData/completion/forStatementKeywords.go ================================================ package foo func bar() { for 1 { } } ================================================ FILE: testData/completion/forStatementKeywordsDoNotInsertSpace.go ================================================ package foo func bar() { for 1 { continu } } ================================================ FILE: testData/completion/forStatementKeywordsDoNotInsertSpace_after.go ================================================ package foo func bar() { for 1 { continue } } ================================================ FILE: testData/completion/forStatementKeywordsInsideFuncLit.go ================================================ package foo func bar() { for 1 { func() { } } } ================================================ FILE: testData/completion/functionAsFunctionArgument.go ================================================ package main func main() { println(fun) } ================================================ FILE: testData/completion/functionAsFunctionArgument_after.go ================================================ package main func main() { println(func() {}) } ================================================ FILE: testData/completion/functionAsVariableValue.go ================================================ package main func main() { a := fun } ================================================ FILE: testData/completion/functionAsVariableValue_after.go ================================================ package main func main() { a := func() {} } ================================================ FILE: testData/completion/functionInDefer.go ================================================ package main func main() { defer fu } ================================================ FILE: testData/completion/functionInDefer_after.go ================================================ package main func main() { defer func() {} } ================================================ FILE: testData/completion/functionInGo.go ================================================ package main func main() { go fu } ================================================ FILE: testData/completion/functionInGo_after.go ================================================ package main func main() { go func() {} } ================================================ FILE: testData/completion/ifKeywordAfterElse.go ================================================ package foo func bar() { if 1 < 2 { } else i } ================================================ FILE: testData/completion/ifKeywordAfterElse_after.go ================================================ package foo func bar() { if 1 < 2 { } else if { } } ================================================ FILE: testData/completion/interfaceKeywordAsFunctionParameter.go ================================================ package foo func function(interf) { } ================================================ FILE: testData/completion/interfaceKeywordAsFunctionParameter_after.go ================================================ package foo func function(interface{}) { } ================================================ FILE: testData/completion/localFunctionInDifferentFiles.go ================================================ package test func hello(c Context){ c.red } ================================================ FILE: testData/completion/localFunctionInDifferentFiles_after.go ================================================ package test func hello(c Context){ c.redirect() } ================================================ FILE: testData/completion/localFunctionInDifferentFiles_context.go ================================================ package test type Context struct { Errors []string } func (c Context) redirect() { } ================================================ FILE: testData/completion/mapKeyword.go ================================================ package foo var c, c1, c2, c3, c4 ma ================================================ FILE: testData/completion/mapKeywordInsertHandler.go ================================================ package foo var c, c1, c2, c3, c4 (ma) ================================================ FILE: testData/completion/mapKeywordInsertHandlerDoNotInsertBrackets.go ================================================ package foo var c, c1, c2, c3, c4 (ma) ================================================ FILE: testData/completion/mapKeywordInsertHandlerDoNotInsertBrackets_after.go ================================================ package foo var c, c1, c2, c3, c4 (map[]) ================================================ FILE: testData/completion/mapKeywordInsertHandler_after.go ================================================ package foo var c, c1, c2, c3, c4 (map[]) ================================================ FILE: testData/completion/mapKeyword_2.go ================================================ package foo var c, c1, c2, c3, c4 (ma) ================================================ FILE: testData/completion/mapKeyword_2_after.go ================================================ package foo var c, c1, c2, c3, c4 (map[]) ================================================ FILE: testData/completion/mapKeyword_after.go ================================================ package foo var c, c1, c2, c3, c4 map[] ================================================ FILE: testData/completion/packageKeyword.go ================================================ func main() { } ================================================ FILE: testData/completion/packageKeywordInEmptyFile.go ================================================ ================================================ FILE: testData/completion/packageKeywordInEmptyFile_after.go ================================================ package ================================================ FILE: testData/completion/packageKeyword_after.go ================================================ package func main() { } ================================================ FILE: testData/completion/rangeKeyword_1.go ================================================ package main func main() { a := 1 for a = ran } ================================================ FILE: testData/completion/rangeKeyword_1_after.go ================================================ package main func main() { a := 1 for a = range } ================================================ FILE: testData/completion/rangeKeyword_2.go ================================================ package main func main() { for b := ran } ================================================ FILE: testData/completion/rangeKeyword_2_after.go ================================================ package main func main() { for b := range } ================================================ FILE: testData/completion/rangeKeyword_3.go ================================================ package main func main() { for ran } ================================================ FILE: testData/completion/rangeKeyword_3_after.go ================================================ package main func main() { for range } ================================================ FILE: testData/completion/selectKeywordInsertHandler.go ================================================ package foo func bar() { selec } ================================================ FILE: testData/completion/selectKeywordInsertHandler_after.go ================================================ package foo func bar() { select { } } ================================================ FILE: testData/completion/structKeywordAsFunctionParameter.go ================================================ package foo func function(struc) { } ================================================ FILE: testData/completion/structKeywordAsFunctionParameter_after.go ================================================ package foo func function(struct{}) { } ================================================ FILE: testData/completion/topLevelKeywords.go ================================================ // comment // comment package main func main() { } ================================================ FILE: testData/completion/topLevelKeywords_2.go ================================================ package src var name = 2 func main() { } ================================================ FILE: testData/completion/typeCaseKeywordCompletion.go ================================================ package foo func bar(p interface{}) string { switch _ := p.(type) { case error: return nil ca } return "" } ================================================ FILE: testData/completion/typeCaseKeywordCompletion_after.go ================================================ package foo func bar(p interface{}) string { switch _ := p.(type) { case error: return nil case : } return "" } ================================================ FILE: testData/completion/typeDefaultKeywordCompletion.go ================================================ package foo func bar(p interface{}) string { switch _ := p.(type) { case error: return nil defa } return "" } ================================================ FILE: testData/completion/typeDefaultKeywordCompletion_after.go ================================================ package foo func bar(p interface{}) string { switch _ := p.(type) { case error: return nil default: } return "" } ================================================ FILE: testData/completion/typeKeywordDoNotInsertBraces.go ================================================ package foo type Bar interf { } ================================================ FILE: testData/completion/typeKeywordDoNotInsertBraces_after.go ================================================ package foo type Bar interface { } ================================================ FILE: testData/completion/typeKeywordInsertBraces.go ================================================ package foo type Bar interf ================================================ FILE: testData/completion/typeKeywordInsertBraces_after.go ================================================ package foo type Bar interface { } ================================================ FILE: testData/completion/typeKeywords.go ================================================ package foo; type Bar ================================================ FILE: testData/completion/typeKeywordsInsideParentheses.go ================================================ package foo; type Bar () ================================================ FILE: testData/coverage/coverage.out ================================================ mode: count coverage.go:20.56,21.14 1 1 coverage.go:24.2,24.50 1 1 coverage.go:21.14,23.3 1 0 coverage.go:29.23,30.19 1 9 coverage2.go:33.2,39.10 3 9 coverage2.go:30.19,32.3 1 0 coverage2.go:43.56,45.14 2 1 withoutHits.go:30.19,32.3 1 0 merging.go:20.56,21.14 1 1 merging.go:24.2,24.50 1 1 merging.go:21.14,23.3 1 0 merging.go:29.23,30.19 1 9 ================================================ FILE: testData/coverage/coverage_for_merge.out ================================================ mode: count merging.go:20.56,21.14 1 1 merging.go:24.2,24.50 2 0 merging.go:21.14,23.3 1 1 merging.go:29.23,30.19 1 0 merging.go:31.23,32.19 1 0 ================================================ FILE: testData/doc/commentEndsWithIndentedBlock_after.txt ================================================

    Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

    	1. Replace multiple slashes with a single slash.
    	2. Eliminate each . path name element (the current directory).
    	3. Eliminate each inner .. path name element (the parent directory)
    	   along with the non-.. element that precedes it.
    
    
    	4. Eliminate .. elements that begin a rooted path:
    	   that is, replace "/.." by "/" at the beginning of a path.

    ================================================ FILE: testData/doc/commentEndsWithIndentedBlock_source.txt ================================================ Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done: 1. Replace multiple slashes with a single slash. 2. Eliminate each . path name element (the current directory). 3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it. 4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path. ================================================ FILE: testData/doc/constants.go ================================================ package a type FooBar string const ( x FooBar = "something" ) func foo(FooBar) {} func _() { foo(x) } ================================================ FILE: testData/doc/constants.txt ================================================ const x
    FooBar = "something" ===== const x FooBar = "something" ===== No urls ===== No local urls ================================================ FILE: testData/doc/escape.go ================================================ package a; func _() {Replace()} // If n < 0, there is no limit on the number of replacements. func Replace(s, old, new string, n int) string {return s} ================================================ FILE: testData/doc/escape.txt ================================================ func Replace(s string, old string, new string, n int) string

    If n < 0, there is no limit on the number of replacements.

    ===== func Replace(s string, old string, new string, n int) string ===== https://godoc.org/#Replace ===== No local urls ================================================ FILE: testData/doc/escapeReturnValues.go ================================================ package a; func _() {Replace()} // If n < 0, there is no limit on the number of replacements. func Replace(s, old, new string, n int) <-chan string {return s} ================================================ FILE: testData/doc/escapeReturnValues.txt ================================================ func Replace(s string, old string, new string, n int) <-chan string

    If n < 0, there is no limit on the number of replacements.

    ===== func Replace(s string, old string, new string, n int) <-chan string ===== https://godoc.org/#Replace ===== No local urls ================================================ FILE: testData/doc/fieldDeclaration.go ================================================ package main // Demo1 struct thigy type Demo1 struct { Field1 string Field2 string } ================================================ FILE: testData/doc/fieldDeclaration.txt ================================================ ===== No navigation info ===== No urls ===== No local urls ================================================ FILE: testData/doc/fprintln.go ================================================ package a; import "fmt"; func foo() {fmt.Fprintln("Hello")} ================================================ FILE: testData/doc/fprintln.txt ================================================ func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

    Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

    ===== func Fprintln(w io.Writer, a ...interface{}) (n int, err error) ===== https://godoc.org/fmt#Fprintln ===== No local urls ================================================ FILE: testData/doc/functionType.go ================================================ package main func main() { foo() } func foo(i int, f func(s string, u uint32)) (f func(s string, u uint32)) { } ================================================ FILE: testData/doc/functionType.txt ================================================ func foo(i int, f func (s string, u uint32)) (f func (s string, u uint32)) ===== func foo(i int, f func (s string, u uint32)) (f func (s string, u uint32)) ===== https://godoc.org/#foo ===== No local urls ================================================ FILE: testData/doc/indentedBlock_after.txt ================================================

    Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:

    	1. Replace multiple slashes with a single slash.
    	2. Eliminate each . path name element (the current directory).
    	3. Eliminate each inner .. path name element (the parent directory)
    	   along with the non-.. element that precedes it.
    
    
    	4. Eliminate .. elements that begin a rooted path:
    	   that is, replace "/.." by "/" at the beginning of a path.

    The returned path ends in a slash only if it is the root "/".

    ================================================ FILE: testData/doc/indentedBlock_source.txt ================================================ Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done: 1. Replace multiple slashes with a single slash. 2. Eliminate each . path name element (the current directory). 3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it. 4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path. The returned path ends in a slash only if it is the root "/". ================================================ FILE: testData/doc/links_after.txt ================================================

    If the result of this process is an empty string, Clean returns the string ".".

    See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” http://plan9.bell-labs.com/sys/doc/lexnames.html

    ================================================ FILE: testData/doc/links_source.txt ================================================ If the result of this process is an empty string, Clean returns the string ".". See also Rob Pike, ``Lexical File Names in Plan 9 or Getting Dot-Dot Right,'' http://plan9.bell-labs.com/sys/doc/lexnames.html ================================================ FILE: testData/doc/method.go ================================================ package main import `os` func _() { var file, _ = os.Open("name") file.Name() } ================================================ FILE: testData/doc/method.txt ================================================ func Name() string

    Name returns the name of the file as presented to Open.

    ===== func Name() string ===== https://godoc.org/os#File.Name ===== No local urls ================================================ FILE: testData/doc/multiBlockDoc_after.txt ================================================

    MultiBlock func comment

    Second block Second block

    Third block

    ================================================ FILE: testData/doc/multiBlockDoc_source.txt ================================================ MultiBlock func comment Second block Second block Third block ================================================ FILE: testData/doc/multilineTypeListDefinition.go ================================================ package a; import "docs"; func foo() {docs.MultiType()} ================================================ FILE: testData/doc/multilineTypeListDefinition.txt ================================================ func MultiType(demo interface{}, err error) ([]interface{}, error)

    MultiType is a function like all other functions

    ===== func MultiType(demo interface{}, err error) ([]interface{}, error) ===== https://godoc.org/docs#MultiType ===== No local urls ================================================ FILE: testData/doc/multilineVariable_1.go ================================================ package main import "docs" func main() { println(docs.InnerVariable_1) } ================================================ FILE: testData/doc/multilineVariable_1.txt ================================================ var InnerVariable_1 int

    InnerVariable_1

    ===== var InnerVariable_1 int ===== No urls ===== No local urls ================================================ FILE: testData/doc/multilineVariable_2.go ================================================ package main import "docs" func main() { println(docs.InnerVariable_2) } ================================================ FILE: testData/doc/multilineVariable_2.txt ================================================ var InnerVariable_2 int

    InnerVariable_2

    ===== var InnerVariable_2 int ===== No urls ===== No local urls ================================================ FILE: testData/doc/multilineVariable_3.go ================================================ package main import "docs" func main() { println(docs.InnerVariable_3) } ================================================ FILE: testData/doc/multilineVariable_3.txt ================================================ var InnerVariable_3 int

    InnerVariable_3

    ===== var InnerVariable_3 int ===== No urls ===== No local urls ================================================ FILE: testData/doc/multilineVariable_4.go ================================================ package main import "docs" func main() { println(docs.InnerVariable_4) } ================================================ FILE: testData/doc/multilineVariable_4.txt ================================================ var InnerVariable_4 int

    InnerVariable_4

    ===== var InnerVariable_4 int ===== No urls ===== No local urls ================================================ FILE: testData/doc/multilineVariable_5.go ================================================ package main import "docs" func main() { println(docs.InnerVariable_5) } ================================================ FILE: testData/doc/multilineVariable_5.txt ================================================ var InnerVariable_5 int

    Global comment

    ===== var InnerVariable_5 int ===== No urls ===== No local urls ================================================ FILE: testData/doc/package.go ================================================ package a; import "io" ================================================ FILE: testData/doc/package.txt ================================================ Package io

    import "io"

    Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.

    Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.

    ===== No navigation info ===== https://godoc.org/io ===== io ================================================ FILE: testData/doc/packageOnImportAlias.go ================================================ package a; import myIO "io"; func _() { myIO.EOF(); } ================================================ FILE: testData/doc/packageOnImportAlias.txt ================================================ Package io

    import "io"

    Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.

    Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.

    ===== No navigation info ===== https://godoc.org/io ===== No local urls ================================================ FILE: testData/doc/packageOnQualifier.go ================================================ package a; import "io"; func _() { io.EOF(); } ================================================ FILE: testData/doc/packageOnQualifier.txt ================================================ Package io

    import "io"

    Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.

    Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.

    ===== No navigation info ===== https://godoc.org/io ===== io ================================================ FILE: testData/doc/packageWithDoc.go ================================================ package a; import "fmt" ================================================ FILE: testData/doc/packageWithDoc.txt ================================================ Package fmt

    import "fmt"

    Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

    ===== No navigation info ===== https://godoc.org/fmt ===== fmt ================================================ FILE: testData/doc/parameter.go ================================================ package main func function(foo string) { println(foo) } ================================================ FILE: testData/doc/parameter.txt ================================================ var foo string ===== var foo string ===== No urls ===== No local urls ================================================ FILE: testData/doc/pointer.go ================================================ package main type S struct {} func main() { foo := new(S) foo } ================================================ FILE: testData/doc/pointer.txt ================================================ var foo *S = new(S) ===== var foo *S = new(S) ===== No urls ===== No local urls ================================================ FILE: testData/doc/println.go ================================================ package a; import "fmt"; func foo() {fmt.Println} ================================================ FILE: testData/doc/println.txt ================================================ func Println(a ...interface{}) (n int, err error)

    Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.

    ===== func Println(a ...interface{}) (n int, err error) ===== https://godoc.org/fmt#Println ===== No local urls ================================================ FILE: testData/doc/quotedStrings_after.txt ================================================

    Escape comment text for HTML. If nice is set, also turn “ into &ldquo; and ” into &rdquo;.

       Escape comment text for HTML. If nice is set,
       also turn `` into &ldquo; and '' into &rdquo;.

    ================================================ FILE: testData/doc/quotedStrings_source.txt ================================================ Escape comment text for HTML. If nice is set, also turn `` into “ and '' into ”. Escape comment text for HTML. If nice is set, also turn `` into “ and '' into ”. ================================================ FILE: testData/doc/receiver.go ================================================ package main type a int func (foo a) method() { println(foo) } ================================================ FILE: testData/doc/receiver.txt ================================================ var foo a ===== var foo a ===== No urls ===== No local urls ================================================ FILE: testData/doc/resultParameter.go ================================================ package main func function() (foo string) { println(foo) } ================================================ FILE: testData/doc/resultParameter.txt ================================================ var foo string ===== var foo string ===== No urls ===== No local urls ================================================ FILE: testData/doc/signature.go ================================================ package a; func _() {Foo()} // If n < 0, there is no limit on the number of replacements. func Foo(a map[int]*string, b (string), c string, int) (<-chan string, int) {return c} ================================================ FILE: testData/doc/signature.txt ================================================ func Foo(a map[int]*string, b (string), c string, int) (<-chan string, int)

    If n < 0, there is no limit on the number of replacements.

    ===== func Foo(a map[int]*string, b (string), c string, int) (<-chan string, int) ===== https://godoc.org/#Foo ===== No local urls ================================================ FILE: testData/doc/specType.go ================================================ package main func main() { client := &MyType{} _, err := client.Foo() println(err) } type MyType struct { MyField int } func (c *MyType) Foo() (resp *MyType, err error) { return c, error("error") } ================================================ FILE: testData/doc/specType.txt ================================================ var client MyType = &MyType{} ===== var client MyType = &MyType{} ===== No urls ===== No local urls ================================================ FILE: testData/doc/struct.go ================================================ package main var st struct { x int64 y int ) func Test() { st = nil } ================================================ FILE: testData/doc/struct.txt ================================================ var st struct {x int64; y int} ===== var st struct {x int64; y int} ===== No urls ===== No local urls ================================================ FILE: testData/doc/structWithAnon.go ================================================ package main var st struct { int64 int *string ) func Test() { st = nil } ================================================ FILE: testData/doc/structWithAnon.txt ================================================ var st struct {int64; int; *string} ===== var st struct {int64; int; *string} ===== No urls ===== No local urls ================================================ FILE: testData/doc/typeInnerDefinitionWithoutComment.go ================================================ package main // my comment type ( // my inner comment MyType1 int64 MyType2 int64 ) func Test(t MyType2) { } ================================================ FILE: testData/doc/typeInnerDefinitionWithoutComment.txt ================================================ type MyType2

    my comment

    ===== type MyType2 ===== https://godoc.org/#MyType2 ===== #main.MyType2 ================================================ FILE: testData/doc/typeResultDefinition.go ================================================ package a; import "docs"; func foo() {docs.TypeResult()} ================================================ FILE: testData/doc/typeResultDefinition.txt ================================================ func TypeResult(s string) string

    TypeResult func comment

    ===== func TypeResult(s string) string ===== https://godoc.org/docs#TypeResult ===== No local urls ================================================ FILE: testData/doc/typeSpec.go ================================================ package main // my comment type MyType int64 func Test(t MyType) { } ================================================ FILE: testData/doc/typeSpec.txt ================================================ type MyType

    my comment

    ===== type MyType ===== https://godoc.org/#MyType ===== #main.MyType ================================================ FILE: testData/doc/typeTopDefinition.go ================================================ package main // my comment type ( // my inner comment MyType1 int64 MyType2 int64 ) func Test(t MyType1) { } ================================================ FILE: testData/doc/typeTopDefinition.txt ================================================ type MyType1

    my inner comment

    ===== type MyType1 ===== https://godoc.org/#MyType1 ===== #main.MyType1 ================================================ FILE: testData/doc/varShortDefinition.go ================================================ package main func main() { client := &MyType{} _, err := client.Foo() println(err) } type MyType struct { MyField int } func (c *MyType) Foo() (resp *MyType, err error) { return c, error("error") } ================================================ FILE: testData/doc/varShortDefinition.txt ================================================ var err error ===== var err error ===== No urls ===== No local urls ================================================ FILE: testData/doc/variable.go ================================================ package a; // test var an = 1; func foo() {an} ================================================ FILE: testData/doc/variable.txt ================================================ var an int = 1

    test

    ===== var an int = 1 ===== No urls ===== No local urls ================================================ FILE: testData/doc/variableInSwitch.go ================================================ package main type Foo struct {} func _() { var err interface{} switch err := err.(type) { case Foo: println(err) } } ================================================ FILE: testData/doc/variableInSwitch.txt ================================================ var err Foo = err ===== var err Foo = err ===== No urls ===== No local urls ================================================ FILE: testData/editor/statement-mover/anonymousFunction-afterDown.go ================================================ package main func _() { if { A(func() { }) } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/anonymousFunction-afterUp.go ================================================ package main func _() { A(func() { }) if { } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/anonymousFunction.go ================================================ package main func _() { A(func() { }) if { } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/anonymousFunctionAtAssignment-afterDown.go ================================================ package main func a() { if { var _ func() = func() { } } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/anonymousFunctionAtAssignment-afterUp.go ================================================ package main func a() { var _ func() = func() { } if { } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/anonymousFunctionAtAssignment.go ================================================ package main func a() { var _ func() = func() { } if { } } func A(func()) {} ================================================ FILE: testData/editor/statement-mover/functionDeclaration-afterDown.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/functionDeclaration-afterUp.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/functionDeclaration.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/functionDeclarationWithFewTopLevelDeclarations-afterUp.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/functionDeclarationWithFewTopLevelDeclarations.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/functionDeclarationWithFewTopLevelDeclarationsDown-afterDown.go ================================================ package main import() func _() { } func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/functionDeclarationWithFewTopLevelDeclarationsDown.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/import-afterUp.go ================================================ package main import( "fmt" ) import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/import.go ================================================ package main import() import( "fmt" ) func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/importDown-afterDown.go ================================================ package main import() import( "fmt" ) func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/importDown.go ================================================ package main import() import( "fmt" ) func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/importWithCaretAtImportString-afterDown.go ================================================ package main import( "fmt" ) ================================================ FILE: testData/editor/statement-mover/importWithCaretAtImportString-afterUp.go ================================================ package main import( "fmt" ) ================================================ FILE: testData/editor/statement-mover/importWithCaretAtImportString.go ================================================ package main import( "fmt" ) ================================================ FILE: testData/editor/statement-mover/importWithCaretAtLastImport-afterUp.go ================================================ package main import( "fmt" ) import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/importWithCaretAtLastImport.go ================================================ package main import() import( "fmt" ) func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/insertedStatement-afterUp.go ================================================ package main func main() { var a int if false { } if true { } } ================================================ FILE: testData/editor/statement-mover/insertedStatement.go ================================================ package main func main() { var a int if true { if false { } } } ================================================ FILE: testData/editor/statement-mover/insertedStatementDown-afterDown.go ================================================ package main func main() { var a int if true { } if false { } } ================================================ FILE: testData/editor/statement-mover/insertedStatementDown.go ================================================ package main func main() { var a int if true { if false { } } } ================================================ FILE: testData/editor/statement-mover/package-afterDown.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/package-afterUp.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/package.go ================================================ package main import() func main() { var a int if true { } } func _() { } ================================================ FILE: testData/editor/statement-mover/simpleStatement-afterDown.go ================================================ package main func main() { if true { var a int } } ================================================ FILE: testData/editor/statement-mover/simpleStatement-afterUp.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/simpleStatement.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/statementInEndOfBlock-afterDown.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/statementInEndOfBlock-afterUp.go ================================================ package main func main() { if true { } var a int } ================================================ FILE: testData/editor/statement-mover/statementInEndOfBlock.go ================================================ package main func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/twoFunc-afterDown.go ================================================ package main import() func main() { var a int if true { } } func _() { } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/twoFunc-afterUp.go ================================================ package main import() func _() { } func asd() int { return 1 } func main() { var a int if true { } } ================================================ FILE: testData/editor/statement-mover/twoFunc.go ================================================ package main import() func main() { var a int if true { } } func _() { } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/twoStatements-afterUp.go ================================================ package main import() func main() { var a int if true { } else { } var k string if false { } } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/twoStatements.go ================================================ package main import() func main() { var a int if true { } else { } var k string if false { } } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/twoStatementsDown-afterDown.go ================================================ package main import() func main() { var a int if false { if true { } else { } var k string } } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/twoStatementsDown.go ================================================ package main import() func main() { var a int if true { } else { } var k string if false { } } func asd() int { return 1 } ================================================ FILE: testData/editor/statement-mover/varSpecTopLevelDeclaration-afterDown.go ================================================ package main var ( a int ) ================================================ FILE: testData/editor/statement-mover/varSpecTopLevelDeclaration.go ================================================ package main var ( a int ) ================================================ FILE: testData/folding/compositeLiteral.go ================================================ package foo type de struct { field1 []int field2 string field3 int } func demo() { d := de{ field1: []int{1, 2, 3}, field2: "string", field3: 1, } _ = d } ================================================ FILE: testData/folding/constDeclaration.go ================================================ package foo const ( demo = 1 dem = "2" ) ================================================ FILE: testData/folding/emptyImportList.go ================================================ package foo func main() { } ================================================ FILE: testData/folding/forStatement.go ================================================ package foo func main() { for { println() } sum := 0 for i := 0; i < 10; i++ { sum += i } } ================================================ FILE: testData/folding/ifStatement.go ================================================ package foo func main() { if (true) { println() } else { println() } } ================================================ FILE: testData/folding/importList.go ================================================ package src import "test" import ( "test" "package/path" "fmt" "encoding/binary") import "other" func main() { } ================================================ FILE: testData/folding/importListWithJustSingleImportKeyword.go ================================================ package src import func main() { } ================================================ FILE: testData/folding/importListWithNewLineAfterKeyword.go ================================================ package src import "test" import ( "test" "package/path" "fmt" "encoding/binary") import "other" func main() { } ================================================ FILE: testData/folding/importListWithOnlyThreeSymbolsToFold.go ================================================ package src import "C" func main() { } ================================================ FILE: testData/folding/importListWithoutSpaceBetweenKeywordAndParen.go ================================================ package src import( "test" "package/path" "fmt" "encoding/binary") import "test" import "other" func main() { } ================================================ FILE: testData/folding/importListWithoutSpaceBetweenKeywordAndString.go ================================================ package src import"other" import( "test" "package/path" "fmt" "encoding/binary") import "test" func main() { } ================================================ FILE: testData/folding/simple.go ================================================ package foo import ( "aaaa" "fmt" ) func test() { return 1 } func (i int) test() { return 1 } SomeMethod(func() { SomeOtherMethod(func() { return 1 }) }) type A struct { in int } type C interface { Foo() int } type D interface { } type T struct { } ================================================ FILE: testData/folding/switchSelectCaseStatement.go ================================================ package foo func main() { ch := make(chan int) select { case _ <- ch: println("demo") case _ <- ch: println("demo") println("demo") } switch true { case 1 == 2: println("demo") case 2 == 3: println("demo") println("demo") default: println("demo") println("demo") println("demo") } switch true { case 3 == 4: { println("demo") } default: println("demo") } } ================================================ FILE: testData/folding/typeDeclaration.go ================================================ package foo type ( demo struct{} dem struct{} ) ================================================ FILE: testData/folding/typeSwitchStatement.go ================================================ package main func main() { var a interface{} switch t := a.(type) { case S: println(t./*ref*/a) case D: break } } ================================================ FILE: testData/folding/varDeclaration.go ================================================ package foo var ( demo = 1 dem = "2" ) ================================================ FILE: testData/formatting/breakLines-after.go ================================================ package main import () import () import () import ( foo "io" foo "io" foo "io" foo "io" ) type Foo struct{} type Foo struct{ bar in } type Foo struct { bar in } type Foo struct { } type Foo struct { } type Foo struct { } type Foo struct { bar int bar int bar int bar int } type Foo interface{} type Foo interface{ bar() int } type Foo interface { } type Foo interface { } type Foo interface { } type Foo interface { bar() int bar() int bar() int bar() int } var () var () var () var () var ( foo int = 1 foo int = 1 foo int = 1 foo int = 1 ) const () const () const () const () const ( foo int = 1 foo int = 1 foo int = 1 foo int = 1 ) func foo() {} func foo() { } func foo() { } func foo() { } func foo() { println("bar") } func main() { println("Hello, playground") println("Hello, playground") println("Hello, playground") println("Hello, playground") println("Hello, playground") } func Hello(b int, a struct { i int j int j int j int }) Foo { return "hello" } func Hello3(b int, a struct { i int; j int }) Foo { return "hello" } func Hello2(interface { Foo }) { return "hello" } func (string) methodName() { } ================================================ FILE: testData/formatting/breakLines.go ================================================ package main import () import ( ) import ( ) import ( foo "io" foo "io" foo "io" foo "io" ) type Foo struct {} type Foo struct { bar in} type Foo struct { bar in} type Foo struct { } type Foo struct { } type Foo struct { } type Foo struct { bar int bar int bar int bar int } type Foo interface {} type Foo interface {bar() int} type Foo interface { } type Foo interface { } type Foo interface { } type Foo interface { bar() int bar() int bar() int bar() int } var () var ( ) var ( ) var ( ) var ( foo int = 1 foo int = 1 foo int = 1 foo int = 1 ) const () const ( ) const ( ) const ( ) const ( foo int = 1 foo int = 1 foo int = 1 foo int = 1 ) func foo() { } func foo() { } func foo() { } func foo() { } func foo() { println("bar") } func main() { println("Hello, playground") println("Hello, playground") println("Hello, playground") println("Hello, playground") println("Hello, playground") } func Hello(b int, a struct { i int j int j int j int }) Foo { return "hello" } func Hello3(b int, a struct { i int; j int }) Foo { return "hello" } func Hello2(interface { Foo }) { return "hello" } func (string) methodName() { } ================================================ FILE: testData/formatting/case2Enter-after.go ================================================ package main func main() { for { select { case 1: } } } ================================================ FILE: testData/formatting/case2Enter.go ================================================ package main func main() { for { select { case 1: } } } ================================================ FILE: testData/formatting/caseE-after.go ================================================ package manipulator func main() { switch expr { case } } ================================================ FILE: testData/formatting/caseE.go ================================================ package manipulator func main() { switch expr { cas } } ================================================ FILE: testData/formatting/caseEnter-after.go ================================================ package manipulator func main() { switch expr { case 1: } } ================================================ FILE: testData/formatting/caseEnter.go ================================================ package manipulator func main() { switch expr { case 1: } } ================================================ FILE: testData/formatting/commentIndentation-after.go ================================================ package main import ( // comment ) import ( // comment `asdasd` // comment `asdasd` ) const ( // comment ) const ( // comment a = 1 // comment b = 2 ) var ( // comment ) var ( // comment a int = 1 // comment b int = 1 ) type ( //comment ) type ( // comment a struct{} // comment b struct{} ) ================================================ FILE: testData/formatting/commentIndentation.go ================================================ package main import ( // comment ) import ( // comment `asdasd` // comment `asdasd` ) const ( // comment ) const ( // comment a = 1 // comment b = 2 ) var ( // comment ) var ( // comment a int = 1 // comment b int = 1 ) type ( //comment ) type ( // comment a struct{} // comment b struct{} ) ================================================ FILE: testData/formatting/constDeclaration-after.go ================================================ package constDeclarations const Hello int = 5 const ( Hello int = 4 ) const ( Hello int = 4 ) const ( Hello int = 3 ) const ( Hello int = 2 ) const ( Hello int = 2 ) const ( Hello int = 2 Hello2 int = 2 ) const ( Hello int = 2 Hello2 int = 2 ) const ( Hello int = 1 Hello2 int = 2 ) ================================================ FILE: testData/formatting/constDeclaration.go ================================================ package constDeclarations const Hello int = 5 const ( Hello int = 4 ) const ( Hello int = 4 ) const ( Hello int = 3 ) const ( Hello int = 2 ) const ( Hello int = 2) const (Hello int = 2 Hello2 int = 2 ) const (Hello int = 2 Hello2 int = 2) const ( Hello int = 1 Hello2 int = 2) ================================================ FILE: testData/formatting/elseStatement-after.go ================================================ package bar func main() { if (true) { } else { true } if {} else {} } ================================================ FILE: testData/formatting/elseStatement.go ================================================ package bar func main() { if (true) { }else{ true } if {} else {} } ================================================ FILE: testData/formatting/emptyStatementInForClause-after.go ================================================ package bar func main() { for position, positionReported := 0, false; ; position++ { } } ================================================ FILE: testData/formatting/emptyStatementInForClause.go ================================================ package bar func main() { for position,positionReported := 0,false;;position++ { } } ================================================ FILE: testData/formatting/expressionsContinuationIndent-after.go ================================================ package main func main() { s := "hello" + "World" + "!!!" b := Bla{} b.Method1().Method1(). Method1().Method1(). Method1() } ================================================ FILE: testData/formatting/expressionsContinuationIndent.go ================================================ package main func main() { s := "hello" + "World" + "!!!" b := Bla{} b.Method1().Method1(). Method1().Method1(). Method1() } ================================================ FILE: testData/formatting/simple-after.go ================================================ package main import "fmt" import "os" import . "database/sql" import ( "aaa" "bbb" ) const ( defaultBufSize = 4096 ) var ( ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune") ErrBufferFull = errors.New("bufio: buffer full") ErrNegativeCount = errors.New("bufio: negative count") ) func main(aaa string, rd io.Reader, error) (ok, ok) { b, ok := rd.(*Reader) fmt.Sprintln("Hello", "oghet") sql.DB() const aaa = iota var bbb = iota switch name { } go foo() for 1; 1; 1 { } if ascii85.Decode() { } return 1, 1 } var b = map[string]int{} func f(n int) { for i := 0; i < 10; i++ { fmt.Println(n, ":", i) } } func main() { go f(0) var input string fmt.Scanln(&input) } func main23() { i := 1 switch i { case 1: fmt.Print("1") fmt.Print("1") fmt.Print("1") fmt.Print("1") case 2: default: fmt.Println(1) } } func main() { select { case a <- 1: return a case a, ok := <-c3: break // default: return b } } func main() { tick := time.Tick(100 * time.Millisecond) boom := time.After(500 * time.Millisecond) example23123( "test", 1, ) for { select { case <-tick: fmt.Println("tick.") case <-boom: fmt.Println("Boom!") return default: fmt.Println(" .") time.Sleep(50 * time.Millisecond) } } response := make(chan *http.Response, 1) errors := make(chan *error) go func() { resp, err := http.Get("http://matt.aimonetti.net/") if err != nil { errors <- &err } response <- resp }() for { select { case r := <-response: fmt.Printf("%s", r.Body) return case err := <-errors: log.Fatal(err) case <-time.After(2000 * time.Millisecond): fmt.Println("Timed out!") return } } } type T struct { name []string // name of the object value, a, b int // its value } type x struct { x, y int // a u float32 // b _ float32 // c A1 *[]int // ca FFF func() // adsfasd X interface{} /* adsf*/ X1 interface{} /* adsf*/ } // comment // comment import "A" // comment type x a // comment var a int = 1 // comment const a = iota // comment func a() {} // comment func (p *int) Length() {} type ( Foo1 struct { a int } Foo2 struct { b int } F func(interface{}) interface{} ) func Test(p interface{}) error { switch p := p.(type) { // should be error: "p declared and not used" case error: return nil } return nil } type x struct { I1 interface{} I2 interface { } i1 interface{ x() int } i2 interface { x() int } S2 struct{} S1 struct { } s1 struct{ x int } s1 struct { x int } } type B1 struct{ a string } type B2 B1 func (b B2) method() B2 { return B2{} } func main() { b := B2{a: ""} b.method() } type ArrayType struct { Type Type } type ArrayType struct { Type Type } func zeroArray(t *Type) { at, _ := (*t).(*ArrayType) println(at.Type) println(at.Type.Size) } type ArrayType struct { Type Type } ================================================ FILE: testData/formatting/simple.go ================================================ package main import "fmt" import "os" import . "database/sql" import ("aaa" "bbb") const ( defaultBufSize = 4096 ) var ( ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune") ErrBufferFull = errors.New("bufio: buffer full") ErrNegativeCount = errors.New("bufio: negative count") ) func main (aaa string, rd io.Reader, error ) ( ok , ok) { b, ok := rd . ( * Reader ) fmt . Sprintln ( "Hello" , "oghet" ) sql.DB ( ) const aaa = iota var bbb = iota switch name { } go foo() for 1; 1; 1 { } if ascii85.Decode() { } return 1 , 1 } var b = map [ string ] int { } func f(n int) { for i := 0; i < 10; i++ { fmt.Println(n, ":", i) } } func main() { go f ( 0 ) var input string fmt . Scanln ( & input ) } func main23() { i := 1 switch i { case 1: fmt.Print("1") fmt.Print("1") fmt.Print("1") fmt.Print("1") case 2: default: fmt.Println(1) } } func main() { select { case a <- 1 : return a case a, ok := <-c3 : break // default:return b } } func main() { tick := time.Tick(100 * time.Millisecond) boom := time.After(500 * time.Millisecond) example23123( "test", 1, ) for { select { case <-tick: fmt.Println("tick.") case <-boom: fmt.Println("Boom!") return default: fmt.Println(" .") time.Sleep(50 * time.Millisecond) } } response := make( chan *http.Response, 1) errors := make(chan *error) go func() { resp, err := http.Get("http://matt.aimonetti.net/") if err != nil { errors <- &err } response <- resp }() for { select { case r := <- response: fmt.Printf("%s", r.Body) return case err := <-errors: log.Fatal(err) case <-time.After(2000 * time.Millisecond): fmt.Println("Timed out!") return } } } type T struct { name [ ]string // name of the object value, a, b int // its value } type x struct { x , y int // a u float32 // b _ float32 // c A1 * [ ]int // ca FFF func( ) // adsfasd X interface { } /* adsf*/ X1 interface { } /* adsf*/ } // comment // comment import "A" // comment type x a // comment var a int = 1 // comment const a = iota // comment func a() {} // comment func (p *int) Length() {} type ( Foo1 struct { a int } Foo2 struct { b int } F func(interface{}) interface{} ) func Test(p interface{}) error { switch p := p.(type) { // should be error: "p declared and not used" case error: return nil } return nil } type x struct { I1 interface{} I2 interface { } i1 interface { x() int } i2 interface { x() int } S2 struct{} S1 struct { } s1 struct{ x int } s1 struct { x int } } type B1 struct{ a string } type B2 B1 func (b B2) method() B2 { return B2{} } func main() { b := B2{a: ""} b.method() } type ArrayType struct { Type Type } type ArrayType struct { Type Type } func zeroArray(t *Type) { at, _ := (*t).(*ArrayType) println(at.Type) println(at.Type.Size) } type ArrayType struct { Type Type } ================================================ FILE: testData/formatting/spacesInArithmeticExpressions-after.go ================================================ package main func main() { var i = 1 i = i + 1 i = i * 1 i = i - 1 i = i || 1 i += i - 1 } ================================================ FILE: testData/formatting/spacesInArithmeticExpressions.go ================================================ package main func main() { var i=1 i=i+ 1 i=i*1 i=i-1 i=i||1 i+=i-1 } ================================================ FILE: testData/formatting/switchEnter-after.go ================================================ package manipulator func main() { switch expr { } } ================================================ FILE: testData/formatting/switchEnter.go ================================================ package manipulator func main() { switch expr {} } ================================================ FILE: testData/formatting/typeEnter-after.go ================================================ package manipulator type ( ) ================================================ FILE: testData/formatting/typeEnter.go ================================================ package manipulator type () ================================================ FILE: testData/formatting/varDeclaration-after.go ================================================ package varDeclarations var Hello int = 5 var ( Hello int = 4 ) var ( Hello int = 4 ) var ( Hello int = 3 ) var ( Hello int = 2 ) var ( Hello int = 2 ) var ( Hello int = 2 Hello2 int = 2 ) var ( Hello int = 2 Hello2 int = 2 ) var ( Hello int = 1 Hello2 int = 2 ) ================================================ FILE: testData/formatting/varDeclaration.go ================================================ package varDeclarations var Hello int = 5 var ( Hello int = 4 ) var ( Hello int = 4 ) var ( Hello int = 3 ) var ( Hello int = 2 ) var ( Hello int = 2) var (Hello int = 2 Hello2 int = 2 ) var (Hello int = 2 Hello2 int = 2) var ( Hello int = 1 Hello2 int = 2) ================================================ FILE: testData/highlighting/anonymousFieldDefinition.go ================================================ package main type MyType int var t struct { *int string []float64 map[int]int chan int64 *[]int32 *(uint) **float32 *struct{} } ================================================ FILE: testData/highlighting/assignToStructFieldInMap.go ================================================ package main type data struct { name string } func _() { type foo struct{ Name string } bad := map[string]foo{} for key := range bad { bad[key].Name = bad[key].Name + " Updated" } good := map[string]*foo{} for key := range good { good[key].Name = good[key].Name + " Updated" } } func main() { m := map[string]data{"x": {"one"}} m["x"].name = "two" n := []data{{"one"}} n[0].name = "two" p := [1]data{{"one"}} p[0].name = "two" } ================================================ FILE: testData/highlighting/assignUsages.go ================================================ package main func main() { sum1 := 0 sum1 = 10 var sum = 0 sum = 10 var sum3 = 0 sum3 += 10 sum4 := 0 sum4 += 10 var i int f(func() { i = 0; println("test") }) } func f(m func()) { m() } func foo() (int, int) { return 4, 5 } func returnTwo() (int, int) { return 1, 2 } func _() { a, b := ((returnTwo())) _, _ = a, b } func _() { a, b := (returnTwo()), 1 _, _ = a, b } func _() { x := foo(), foo() y = foo(), foo() } ================================================ FILE: testData/highlighting/assignmentToReceiver.go ================================================ package demo import "fmt" type demo struct { Val int } func (d *demo) change() { d = nil d.myVal() } func (d *demo) myVal() { fmt.Printf("my val: %#v\n", d) } func (d demo) change2() { d = demo{} d.myVal() } func (d *demo) change3() { d.Val = 3 d.myVal() } func _() { d := &demo{} d.myVal() d.change() d.myVal() d.Val = 2 d.change2() d.myVal() d.change3() d.myVal() } ================================================ FILE: testData/highlighting/avoidDuplicatedUnusedImportReports.go ================================================ package main import `pack1` import `pack2` import `pack3` ================================================ FILE: testData/highlighting/backticks.go ================================================ package main; import `fmt` func main() { fmt.Println(`foo`) } ================================================ FILE: testData/highlighting/blankFields.go ================================================ package main type BlankFields struct { A uint32 _ int32 B float64 _ [4]int16 C byte _ [7]byte _ struct { f [8]float32 } } ================================================ FILE: testData/highlighting/blankImport.go ================================================ package main import ( _ "fmt" ) func main() { } ================================================ FILE: testData/highlighting/boxes.go ================================================ package main func Println(...interface{}) { } func main() { bigBox := &BigBox{} bigBox.BubbleGumsCount = 4 // correct... bigBox.SmallBox.AnyMagicItem = true // also correct v1:= bigBox.SmallBox v2:= (&BigBox{}).SmallBox //v3:= &BigBox{}.SmallBox // todo: should be an error A := v1.AnyMagicItem B := v2.Color() bigBox.AnyMagicItem = false || A + B Println(v1) // => 60 Println(v2) // => 60 Println(bigBox.Capacity()) // => 60 Println(bigBox.SmallBox.Capacity()) // => 20 Println(bigBox.SmallBox.Color()) // => "gray" Println(bigBox.Color()) // => "gray" } func (sb *SmallBox) Color() string { return "gray" } type SmallBox struct { BubbleGumsCount int AnyMagicItem bool } type BigBox struct { SmallBox } func (sb *SmallBox) Capacity() int { return 20 } func (bb *BigBox) Capacity() int { return bb.SmallBox.Capacity() * 3 } type string string type int int type bool bool const ( true, false = 0 == 0, 0 != 0 // Untyped bool. ) ================================================ FILE: testData/highlighting/break.go ================================================ package main import "fmt" func _() { for i := 0; i < 10; i++ { fmt.Printf("%d\n", i) f := func() { break } f() break } break if 1 > 0 { break } for i := 0; i < 10; i++ { defer func() { break }() go func() { break }() break } switch _ { default: _() case 0, 1, 2, 3: _(); break; case 4, 5, 6, 7: _() } select { case _ <- 0: break; case _ <- 1: } } ================================================ FILE: testData/highlighting/builtinFuncCalls.go ================================================ package main import "C" func foo(interface{}) {} type stringType string type mapType map[string]string func main() { foo(make()) foo(make(`notAType`)) foo(make(stringType)) foo(make([]stringType)) foo(make([]stringType, 2)) foo(make([]stringType, 2, 3)) foo(make([]stringType, 2, 3, 4)) x := "a" y := 4 foo(make([]stringType, x)) foo(make([]stringType, 4, "foo")) foo(make(<-chan int)) foo(make(chan int)) foo(make(chan int, 4)) foo(make(<-chan int, 4, 5)) foo(make(map[string]string)) foo(make(map[string]string, y)) type test uint32 foo(make([]int, test(4))) foo(make([]int, uint64(2))) type c uint32 type b c type a b type d []c type e d foo(make([]int32, a(2))) foo(make(e, a(4))) var xyz interface{} = 1 foo(make(chan int, xyz.(int))) i := C.int(1) foo(make([]*C.char, i)) foo(make(chan func(), 1.0)) foo(make(chan func(), 1e5)) foo(make(chan func(), '1')) foo(make(chan func(), true)) foo(make(chan func(), complex(17,4))) foo(make(chan func(), "1")) type someChan chan int type capChan someChan var capTest1 e var capTest2 a var capTest3 capChan var capTest4 int oldCh := (*(chan *[]byte))((nil)) if oldCh != nil && cap(*oldCh) != 0 { } foo(cap()) foo(cap(capTest1, capTest2)) foo(cap(capTest1)) foo(cap(capTest2)) foo(cap(capTest3)) foo(cap(capTest4)) foo(cap(map[string]struct{}{})) foo(cap(&[4]string{"a", "b", "c", "d"})) foo(cap([]string{})) } func _() { var x IntegerType = 3 println(x) } ================================================ FILE: testData/highlighting/cgotest.go ================================================ package main import ( "fmt" "unsafe" ) // struct x { // int y, z; // }; // // int sum(struct x a) { // return a.y + a.z; // } // /* typedef struct { int x; unsigned char y; char *name; } S; S* some_C_function_call() { return 0; } */ import "C" type X struct{ Y, Z int32 } var s C.struct_x var s1 *C.struct_x func main() { s2 := C.some_C_function_call() if (false) { fmt.Println(s2.x) fmt.Println(s2.x.y.y.wad.sd.asd.ad()) // todo[ignatov]: update test data with a valid sample } a := &X{5, 7} fmt.Println(s.y) fmt.Println(s1) fmt.Println(a, "->", C.sum(*((*C.struct_x)(unsafe.Pointer(a))))) cs := C.S{} fmt.Println(cs.x) fmt.Println(cs.y) fmt.Println(cs.name) } ================================================ FILE: testData/highlighting/chan.go ================================================ package main import "fmt" type Struct struct { String string } func GetChan() chan Struct { c := make(chan Struct, 1) c <- Struct{"foo"} close(c) return c } func main() { c := GetChan() for s := range c { println(s.String) } } type Neuron struct { ID int } type Signal struct { Value float64 ID string } func (s *Signal) IsNull() bool { if s.Value != 0 { return false } return true } type Dendrit chan *Signal func (d Dendrit) Sinops(n *Neuron) { for { select { case signal := <-d: if signal.IsNull() { // not found method continue } // Value not found also fmt.Printf("NID=%d\t<- %g (IN)\n", n.ID, signal.Value) default: continue } } } ================================================ FILE: testData/highlighting/check.go ================================================ package check import "fmt" func init() { fmt.TestStringer(nil) } ================================================ FILE: testData/highlighting/checkSamePackage_test.go ================================================ package check func init() { TestStringer(nil) } ================================================ FILE: testData/highlighting/check_test.go ================================================ package check import "fmt" func init() { fmt.TestStringer(nil) } ================================================ FILE: testData/highlighting/commentStart.go ================================================ // demo package commentstart type ( // help Hello struct{} // help Helloi interface{} ) // help type Helllo struct{} // help type Hellloi interface{} const ( // help Helloc = 3 ) // help const Hellloc, hellloc2 = 1, 2 var ( // help Hello1, Hellow1 int ) // help var Hello2 int // Helllo func (a Helllo) Hellllo() { _ = Hello1 _ = Hellow1 _ = Hello2 } // Demo does things -> correct func Demo() { Demo2() } // Demo does other things -> incorrect func Demo2() { Demo() Demo3() Demo4() Demo5() Demo6() Demo7() Demo8() Demo9() } // Demo3 func Demo3() {} // A Demo4 does things -> correct func Demo4() {} // An Demo5 does things -> correct func Demo5() {} // The Demo6 does things -> correct func Demo6() {} // Demo7 does things -> correct // // Deprecated: use other thing func Demo7() {} // Demo8 does things -> correct // // Deprecated: use other thing func Demo8() {} // Demo does things -> correct // // Deprecated: use other thing // Demo9 demo func Demo9() {} ================================================ FILE: testData/highlighting/composite.go ================================================ package main import "fmt" type demo struct { Field string } func getMore() (_, _, _ *demo) { return &demo{"demo1"}, &demo{"demo2"}, &demo{"demo3"} } func main() { d1, d2, d3 := getMore() fmt.Printf("%s %s %d", d1.Field, d2.Field, d3.Field) } ================================================ FILE: testData/highlighting/consts.go ================================================ package main import "fmt" type T int type TT int const ( A , X, Y = T(iota), 1, T(1) ) const ( B = T(iota) C D TT = 1 ) func (t T) String() string { return "t" } func (t TT) AnotherString() string { return "tt" } func main() { fmt.Println(A.String()) fmt.Println(B.String()) fmt.Println(C.String()) fmt.Println(D.AnotherString()) } ================================================ FILE: testData/highlighting/continue.go ================================================ package main import "fmt" func _() { for i := 0; i < 10; i++ { fmt.Printf("%d\n", i) f := func() { continue } f() continue } continue if 1 > 0 { continue } for i := 0; i < 10; i++ { defer func() { continue }() go func() { continue }() continue } } ================================================ FILE: testData/highlighting/cyclicDefinition.go ================================================ package main var Foo1 = Foo1 const Bar1 = Bar1 var ( Foo int = 1 + Foo ) const ( Bar, Demo int = 1 + Bar + 1 + Bar, 1 ) func _() { _, _, _ = Foo, Bar, Demo } ================================================ FILE: testData/highlighting/deferGo.go ================================================ package demo func _() { defer recover() defer panic("ads") defer int(0) go recover() go panic("ads") go int(0) } ================================================ FILE: testData/highlighting/deferInLoop.go ================================================ package deferinloop func noop() {} type b int func (a b) meth() { for { defer noop() } } func _() { for { func (){ defer noop() }() } func (){ defer noop() }() for { switch 1 { case 2: defer noop(); } } defer noop(); for { defer noop() } } ================================================ FILE: testData/highlighting/doNotReportNonLastMultiResolvedImport.go ================================================ package main import "to_import/unique" import _ "to_import/shared" func main() { unique.Foo() } ================================================ FILE: testData/highlighting/embeddedInterfacePointer.go ================================================ package demo type ( demo interface {} demo2 interface {} dem struct { *demo demo2 } ) ================================================ FILE: testData/highlighting/equalinif.go ================================================ package equalinif func _() { a := 1 b := 2 if a = b { println("a = b") } else { println("a != b") } if a := b { println("a = b") } else { println("a != b") } if a = b; a != 1 { println("a = b") } else { println("a != b") } if a := b; a == 1 { println("a = b") } else { println("a != b") } } ================================================ FILE: testData/highlighting/exportedOwnDeclaration.go ================================================ package exportedowndeclaration const Hello1, hello2 = 1, 2 const Hello3, Hello4 = 3, 4 var Hello5, hello6 int var Hello7, Hello8 int var ( Hello9, Hello10 int Hello11, Hello12 int ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 } ================================================ FILE: testData/highlighting/fields.go ================================================ package main import ( "fmt" ) var unused int = 1 var langId = "es" func main() { lId := "es" _ = map[string]string{langId: "hola"} _ = map[string]string{lId: "hola"} _ = map[interface{}]string{foo1: "hola", } } func _() { type test struct { field1 string } field2 := "" _ = field2 _ = test{field2: ""} } func foo1() { } type Par []struct{ Key string Value string } func main1(i interface{}) { // it works t := i.(Par) _ = t[0].Key // it fails switch t := i.(type) { case Par: a := t _ = t[0].Key _ = a[0].Key } } type Some struct { field int } func prtMain() { ptr := &Some{1} _ = (*ptr).field } type User struct { ID int Name string } func main23() { members := []User{{ID: 2}, {ID: 3}} members2 := []*User{{ID: 2} } members3 := []*struct{ID int}{{ID: 2} } members4 := []*User{&User{ID: 2}, &User{ID: 3}} fmt.Println(len(members)) fmt.Println(len(members2)) fmt.Println(len(members3)) fmt.Println(len(members4)) } func main345() { type T1 string fmt.Println(T1("1")) } ================================================ FILE: testData/highlighting/fileRead.go ================================================ package main import ( "bufio" "fmt" "os" ) func check(e error) { if e != nil { panic(e) } } func main() { fmt.Println("Reading your file now") fileHandle, err := os.Open("/Path/to/your/file/fileName") check(err) defer fileHandle.Close() newReader := bufio.NewScanner(fileHandle) output := "" for newReader.Scan() { output += newReader.Text() } fmt.Println("The contents of the file =>", output) } ================================================ FILE: testData/highlighting/forRange.go ================================================ package main import ( "fmt" "time" ) func main() { var tick = 0 for range time.NewTicker(1 * time.Second).C { fmt.Println("Tick") tick++ if tick > 3 { break } } for _, _ = range "abc" { } for _ = range "abc" { } } type d_type [32]uintptr type Bits struct { a []uint64 b [3]uint64 c [3+3]uint64 d d_type } func _(a *Bits) { for i, x := range &a.a { fmt.Println(i) fmt.Println(x) } for i, x := range &a.b { fmt.Println(i) fmt.Println(x) } for i, x := range &a.c { fmt.Println(i) fmt.Println(x) } for i, x := range &a.d { fmt.Println(i) fmt.Println(x) } for i, x := range a2() { fmt.Println(i) fmt.Println(x) } } func a2() (value int, error int){ value, error = 2, 3 return } ================================================ FILE: testData/highlighting/funcCall.go ================================================ package mongo import "fmt" type Collection struct{} type CollectionLoaderInterface interface { MangoCollection(string) *Collection } func Collection(parent interface{},collection string) *Collection{ switch parent := parent.(type) { case CollectionLoaderInterface: return parent.MangoCollection(collection) } return nil } func main1(err error) { switch err.(type) { case nil: return } } type advSearch struct { Genres struct { Generals []string Thematics struct { Genres []string Missing bool } Demographics struct { Genres []string Missing bool } } } func search() bool { m := advSearch{} return m.Genres.Demographics.Missing } func g(a, b, _ int) (int, int) { return a, b } func f(_, _ int) { } func test() { f(g(1, 2, 3)) } func test2() (bool, string) { ch := make(chan string) var str string var isOpen bool select { case str = <-ch : case str, isOpen = <-ch: case s, ok := <-ch: str = s isOpen = ok case s := <-ch: str = s } return isOpen, str } func Test23() (err error) { var c chan int select { case err := (<-c): } return err } func Demo() error { return fmt.Errorf("err %s", "a") } func main() { var err error switch { case 1==2: err := Demo() panic(err) default: err = Demo() panic(err) } //panic(err) } func main2() { ch := make(chan string, 2) ch <- "first" ch <- "second" select { case a := <-ch: println(a) } var ( a int // marked as unused variable `a` ) select { case a = <-ch: println(a) } println(a) } type d struct{ A string } func (a *d) Func() (*d, error) { return a, nil } func de(x string) *d { return &d{A: x} } func demo23(a *d, _ error) string { return a.A } func main23() { _ = demo23(de("1").Func()) } func foo_m(_ int) { } func bar_m() (int, int) { return 0, 0 } func main127() { foo_m(bar_m()) } type AnInterface interface { MyMethod() error } type bar struct {} func (*bar) MyMethod() error { return nil } type mystruct struct {} func (x *mystruct) getAnInterface() AnInterface { return &bar{} } var getAnInterface = (*mystruct).getAnInterface func _() { fmt.Println(getAnInterface(&mystruct{}).MyMethod()) } type ( funcTiOn func() ([]string, Cmd) Cmd interface { Ini(keys map[string]string) } ) var ( funcs = []funcTiOn{} ) func _() { for idx := range funcs { _, handler := funcs[idx]() handler.Ini(map[string]string{}) } for _, val := range funcs { _, handler := val() handler.Ini(map[string]string{}) } } type Decoder func(p int) (size int) func (e Decoder) ConvertString(s string) string { return s } func NewDecoder(_ string) Decoder { return nil } func _() { dc := NewDecoder("GB18030") dc(1) fmt.Println(dc.ConvertString("abc123")) } type dnsNameTest struct { name string result bool } var dnsNameTests = []dnsNameTest{ {"_xmpp-server._tcp.google.com", true}, } func _() { for _, tc := range dnsNameTests { println(tc.name) println(tc.result) } // append loses return type dnsNameTests2 := append(dnsNameTests, []dnsNameTest{}) for _, tc := range dnsNameTests2 { println(tc.name) println(tc.result) } } ================================================ FILE: testData/highlighting/funcLiteral.go ================================================ package main import "fmt" type Mutex struct { state int32 sema uint32 } var a = func() Mutex { return Mutex{} }() func main() { fmt.Println(a.sema) } ================================================ FILE: testData/highlighting/funcType.go ================================================ package main type demoStr struct { Field string } type f func() *demoStr func DemoFunc() f { return func () *demoStr { return &demoStr{Field: "dmeo"} } } func main() { fun := DemoFunc() field := fun() _ = field.Field } type A struct { } func (self *A) chain() *A{ return self } func getAnA() (_ *A) { return &A{} } func _() { getAnA().chain() } func _(callback func() (interface{}, error)) { if _, err := callback(); err != nil { err.Error() } } func _(callback func() error) { if err := callback(); err != nil { err.Error() } } func _(fn func() (i int, e error)) { i, e := fn() print(i) print(e.Error()) } func _(fn func() (_ error)) { err := fn() err.Error() } func _(fn func() error) { err := fn() err.Error() } type TestStruct struct { SomeId int } type DataSlice []*TestStruct func _() { data := DataSlice{} for _, element := range *data { if element.SomeId > 20 { println("some text") } } } func FA() (int, string) { return 0, "abc" } func FB(_ int, _ string) { } func _() { FB(123, "abc") FB(FA()) } ================================================ FILE: testData/highlighting/functionTypes.go ================================================ package main import "fmt" type t struct { } func (t t) foo() { } func startConvert() (fin, fill t, e error) { return t{}, t{}, nil } func main() { a1, b1, e := startConvert() a1.foo() b1.foo() fmt.Println(e) } ================================================ FILE: testData/highlighting/gh2147.go ================================================ package main import "sync" type myMutex sync.Mutex var ( pathLock sync.RWMutex ) func _() { pathLock.RLock() defer pathLock.RUnlock() } func main() { var mtx myMutex mtx.Lock() mtx.Unlock() } ================================================ FILE: testData/highlighting/githubIssue2099.go ================================================ package main // Tests https://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues/2099. type Interf interface { Hello() } type demo interface { Interf Interf() } ================================================ FILE: testData/highlighting/importIgnoringDirectories.go ================================================ package test import `to_import/.name` import `to_import/_name` import `to_import/testdata` ================================================ FILE: testData/highlighting/importUsedAsName.go ================================================ package demo import "fmt" import _ "fmt" import iio "io" func _() { fmt.Println("demo") demo := true _, _ = iio.EOF, demo } func demo() (int, int) { return 1, 2 } func _() { fmt := "demo" iio := 1 _, _ = iio, fmt a, _ := demo() _ = a } ================================================ FILE: testData/highlighting/indexedStringAssign.go ================================================ package main func main() { var s string = "hello" s[0] = 0 for s[0] = range "asdf"{ } } ================================================ FILE: testData/highlighting/infiniteFor.go ================================================ package infiniteFor func _() { for { println("") } for i:=0; i<10; i++ { } for range []byte{} { } for i:=0; i<10; i++ { println("hello") } for { } } ================================================ FILE: testData/highlighting/init.go ================================================ package main func init() { println("Hello") } func main() { init() println(" world!") a{}.init() } func _() { var init = func() { println("HA") } init() println(" world!") } type a struct { } func (s a) init() { println("sa") } ================================================ FILE: testData/highlighting/innerTypesFromTestDataPackage.go ================================================ package main; import "to_import/testdata"; type Outer struct { *testdata.Reader }; func main() {} ================================================ FILE: testData/highlighting/interfaces.go ================================================ package main import "fmt" func main() { c := Parent{&Child{}, &impl{}} c.Get(1,1,1) // too many arguments in call to c.Get } type Parent struct { *Child Interface } type Child struct { Unimplemented } type Interface interface { Get(...int) } type impl struct { } func (r impl) Get(...int) { fmt.Println("HERE") } type Unimplemented interface { Get(s string) } ================================================ FILE: testData/highlighting/iota.go ================================================ package main const ( FooConst = iota BarConst ) var ( FooVar = iota ) func _() { const name = iota println(iota) iota := 123 println(iota) println(name) println(FooConst) println(BarConst) println(FooVar) } func main() { } ================================================ FILE: testData/highlighting/iota2.go ================================================ package main const iota = 2 func main() { println(iota) } ================================================ FILE: testData/highlighting/labels.go ================================================ package main func _() { invalid: outer: for { inner: for { break invalid break inner break outer } _: for { break _ } break invalid; break inner; break outer; func () { funcLit: for { break invalid; break inner; break outer; break funcLit; } } } } func _() { Label: if (false) { goto Label } func() { if (false) { goto Label } Label: }() } func _() { Label: if (false) { goto Label } func() { goto Label }() } ================================================ FILE: testData/highlighting/literalValues.go ================================================ package main type S struct { a int } func main() { _ = map[string]S{ "key": {a: 5}, } _ = map[string][]S{ "key": {{a: 5}}, } _ = map[string][][]S{ "key": {{{a: 5}}}, } _ = map[string][][][]S{ "key": {{{{a: 5}}}}, } } ================================================ FILE: testData/highlighting/mainWithWrongSignature.go ================================================ package main func main() { println("Hello") } func main(int) { } func main() int { } func main(int) int { } func main() () {} ================================================ FILE: testData/highlighting/methodExpr.go ================================================ package main import ( "fmt" ) type Vertex struct { X, Y float64 } func main() { v := Vertex{3, 4} fmt.Print(v.Abs()) } func (v *Vertex) Abs() float64 { return (*v).X * v.X + v.Y * v.Y } type T struct { a int } func (tv T) Mv(int) int { return 0 } // value receiver func (tp *T) Mp(float32) float32 { return 1 } // pointer receiver var t T func _() { t.Mv(7) T.Mv(t, 7) // todo: rework resolve for method expression (T).Mv(t, 7) f1 := T.Mv; f1(t, 7) f2 := (T).Mv; f2(t, 7) fmt.Println((*T).Mp()) fmt.Println((*T).Mv()) } type Type interface { Size() int64 } type ArrayType struct { Type Type } func (t ArrayType) Size() int64 { return 1 } func _(t *Type) { at, _ := (*t).(*ArrayType) println(at.Type) println(at.Type.Size()) } ================================================ FILE: testData/highlighting/methodOnNonLocalType.go ================================================ package demo2031 import ( "time" ) type Duration time.Duration func (_ *string) Demo() { } func (_ int) Demo() { } func (_ ScanState) Demo() { } func (_ *Duration) UnmarshalText(data []byte) (error) { _ = data return nil } ================================================ FILE: testData/highlighting/mismatch.go ================================================ package main type validate interface { validate() (bool, error) void() } func main() { var s validate err := s.validate() _ = err v := s.void() _ = v shortDeclarationWithoutExpressions := ; _ = shortDeclarationWithoutExpressions } ================================================ FILE: testData/highlighting/mixedNamedUnnamedParameters.go ================================================ package main func _(int1, string1, a1 error) (int, string, a error) { return 1, "a", nil } func _(int, string, error) (int, string, error) { return 1, "a", nil } func _(a1, b1 int, string, error) (a, b, int, string, error) { return 1, 2, "a", nil } type d int func (d) _(int1, string1, a1 error) (int, string, a error) { return 1, "a", nil } func (d) _(int, string, error) (int, string, error) { return 1, "a", nil } func (d) _(a1, b1 int, string, error) (a, b int, string, error) { return 1, 2, "a", nil } func main() { x := func(int1, string1, a1 error) (int, string, a error) { return 1, "a", nil } y := func(int, string, error) (int, string, error) { return 1, "a", nil } z := func(a1, b1 int, string, error) (a, b int, string, error) { return 1, 2, "a", nil } _, _, _ = x, y, z } ================================================ FILE: testData/highlighting/nil.go ================================================ package nil func nilAssign() { var a, b, c = 1, nil, 2 _, _, _ = a, b, c d, e, f := 1, nil, 2 _, _, _ = d, e, f const g, h, i = 1, nil, 2 _, _, _ = g, h, i } func nilVar() { var nil = 123 var a = nil _ = a } ================================================ FILE: testData/highlighting/placeholderCount.go ================================================ package placeholderCount import "fmt" import "log" import "testing" import "unsafe" import "C" const ( myFormatConst = "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d" myWrongFormatConst = "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d" ) func printf(string, ...int) { } var s string = "%d" const s1 = s1 const s2 = 1 func _(t *testing.T) { fmt.Printf(s, 1, 2) fmt.Printf(s1, 1, 2) fmt.Printf(s2, 1, 2) fmt.Errorf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Fprintf(nil, "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Fscanf(nil, "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Printf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Scanf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Sprintf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Sscanf(nil, "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) log.Fatalf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) log.Panicf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) log.Printf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, ) fmt.Printf("eq (as-is): %.3f%% score: %v offset: %v descr: [%v]\n", 3.14, 1, 1, "descr") fmt.Printf("a: %+v", 1) fmt.Printf("%-4d", 999) fmt.Printf("a: %%%+v", 1) fmt.Printf("a: %%%%+v", 1) fmt.Printf("#%02X%02X%02X", 1, 2, 3) fmt.Printf("#%02X%02X%02X", 1, 2, 3, 4) myFormatVar := "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d" log.Printf(myFormatVar, 1, 2, 3, 4, 5, 6, 7, 8, 9) myWrongFormatVar := "%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d" log.Printf(myWrongFormatVar, 1, 2, 3, 4, 5, 6, 7, 8) log.Printf(myFormatConst, 1, 2, 3, 4, 5, 6, 7, 8, 9) t.Errorf(myFormatConst, 1, 2, 3, 4, 5, 6, 7, 8, 9) t.Fatalf(myFormatConst, 1, 2, 3, 4, 5, 6, 7, 8, 9) t.Logf(myFormatConst, 1, 2, 3, 4, 5, 6, 7, 8, 9) t.Skipf(myFormatConst, 1, 2, 3, 4, 5, 6, 7, 8, 9) log.Printf(myWrongFormatConst, 1, 2, 3, 4, 5, 6, 7, 8) t.Errorf(myWrongFormatConst, 1, 2, 3, 4, 5, 6, 7, 8) t.Fatalf(myWrongFormatConst, 1, 2, 3, 4, 5, 6, 7, 8) t.Logf(myWrongFormatConst, 1, 2, 3, 4, 5, 6, 7, 8) t.Skipf(myWrongFormatConst, 1, 2, 3, 4, 5, 6, 7, 8) printf("%d", 1) printf("%[2]d %[1]d", 1, 2) printf("%[2]d %[1]d %d", 1, 2) printf("%[2]d %[1]d %[2]d", 1, 2) printf("%d") myNonFormatFunc := func () int { return 1 } log.Printf(myNonFormatFunc(), 1, 2, 3, 4, 5, 6, 7, 8, 9) log.Printf("%d %d %#[1]x %#x %2.f %d %2.2f %.f %.3f %[9]*.[2]*[3]f %d %f %#[1]x %#x %[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, ) fmt.Sprintf("%d") log.Printf("%d %d %#[1]x %#x %f %2.f %2.2f %.f %.3f %[3]*.[2]*[1]f %d %d %#[1]x %#x %*[2]d %v % d", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) fmt.Sprintf("%d", 1, 2) fmt.Print("%[2]*.[1]*[3]d", 2, 3, myNonFormatFunc) fmt.Print("%[2]*.[1]*[3]d", 2, 3, printf) fmt.Println("demo\n", 2, 3, myNonFormatFunc) fmt.Println("demo\n", 2, 3, printf) fmt.Print("demo\n", 2, 3, myNonFormatFunc) fmt.Print("demo\n", 2, 3, printf) type X struct{ Y, Z int32 } a := &X{5, 7} fmt.Println(a, "->", C.sum(*((*C.struct_x)(unsafe.Pointer(a))))) fmt.Sprintf("asdadad %O asdadad", "demo") fmt.Printf("%[0]d", 1) } func _(format string, args ...interface{}) { fmt.Fprintf(nil, "\nError: "+format+"\n", args...) } ================================================ FILE: testData/highlighting/placeholderCountVet.go ================================================ // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file contains tests for the printf checker. package testdata import ( "fmt" "math" "os" "unsafe" // just for test case printing unsafe.Pointer ) func UnsafePointerPrintfTest() { var up unsafe.Pointer fmt.Printf("%p, %x %X", up, up, up) } // Error methods that do not satisfy the Error interface and should be checked. type errorTest1 int func (errorTest1) Error(...interface{}) string { return "hi" } type errorTest2 int // Analogous to testing's *T type. func (errorTest2) Error(...interface{}) { } type errorTest3 int func (errorTest3) Error() { // No return value. } type errorTest4 int func (errorTest4) Error() int { // Different return type. return 3 } type errorTest5 int func (errorTest5) error() { // niladic; don't complain if no args (was bug) } // This function never executes, but it serves as a simple test for the program. // Test with make test. func PrintfTests() { var b bool var i int var r rune var s string var x float64 var p *int var imap map[int]int var fslice []float64 var c complex64 // Some good format/argtypes fmt.Printf("") fmt.Printf("%b %b %b", 3, i, x) fmt.Printf("%c %c %c %c", 3, i, 'x', r) fmt.Printf("%d %d %d", 3, i, imap) fmt.Printf("%e %e %e %e", 3e9, x, fslice, c) fmt.Printf("%E %E %E %E", 3e9, x, fslice, c) fmt.Printf("%f %f %f %f", 3e9, x, fslice, c) fmt.Printf("%F %F %F %F", 3e9, x, fslice, c) fmt.Printf("%g %g %g %g", 3e9, x, fslice, c) fmt.Printf("%G %G %G %G", 3e9, x, fslice, c) fmt.Printf("%b %b %b %b", 3e9, x, fslice, c) fmt.Printf("%o %o", 3, i) fmt.Printf("%p %p", p, nil) fmt.Printf("%q %q %q %q", 3, i, 'x', r) fmt.Printf("%s %s %s", "hi", s, []byte{65}) fmt.Printf("%t %t", true, b) fmt.Printf("%T %T", 3, i) fmt.Printf("%U %U", 3, i) fmt.Printf("%v %v", 3, i) fmt.Printf("%x %x %x %x", 3, i, "hi", s) fmt.Printf("%X %X %X %X", 3, i, "hi", s) fmt.Printf("%.*s %d %g", 3, "hi", 23, 2.3) fmt.Printf("%s", &stringerv) fmt.Printf("%v", &stringerv) fmt.Printf("%T", &stringerv) fmt.Printf("%v", notstringerv) fmt.Printf("%T", notstringerv) fmt.Printf("%q", stringerarrayv) fmt.Printf("%v", stringerarrayv) fmt.Printf("%s", stringerarrayv) fmt.Printf("%v", notstringerarrayv) fmt.Printf("%T", notstringerarrayv) fmt.Printf("%d", new(Formatter)) fmt.Printf("%*%", 2) // Ridiculous but allowed. fmt.Printf("%s", interface{}(nil)) // Nothing useful we can say. fmt.Printf("%g", 1+2i) // Some bad format/argTypes fmt.Printf("%b", "hi") // ERROR "arg .hi. for printf verb %b of wrong type" fmt.Printf("%t", c) // ERROR "arg c for printf verb %t of wrong type" fmt.Printf("%t", 1+2i) // ERROR "arg 1 \+ 2i for printf verb %t of wrong type" fmt.Printf("%c", 2.3) // ERROR "arg 2.3 for printf verb %c of wrong type" fmt.Printf("%d", 2.3) // ERROR "arg 2.3 for printf verb %d of wrong type" fmt.Printf("%e", "hi") // ERROR "arg .hi. for printf verb %e of wrong type" fmt.Printf("%E", true) // ERROR "arg true for printf verb %E of wrong type" fmt.Printf("%f", "hi") // ERROR "arg .hi. for printf verb %f of wrong type" fmt.Printf("%F", 'x') // ERROR "arg 'x' for printf verb %F of wrong type" fmt.Printf("%g", "hi") // ERROR "arg .hi. for printf verb %g of wrong type" fmt.Printf("%g", imap) // ERROR "arg imap for printf verb %g of wrong type" fmt.Printf("%G", i) // ERROR "arg i for printf verb %G of wrong type" fmt.Printf("%o", x) // ERROR "arg x for printf verb %o of wrong type" fmt.Printf("%p", 23) // ERROR "arg 23 for printf verb %p of wrong type" fmt.Printf("%q", x) // ERROR "arg x for printf verb %q of wrong type" fmt.Printf("%s", b) // ERROR "arg b for printf verb %s of wrong type" fmt.Printf("%s", byte(65)) // ERROR "arg byte\(65\) for printf verb %s of wrong type" fmt.Printf("%t", 23) // ERROR "arg 23 for printf verb %t of wrong type" fmt.Printf("%U", x) // ERROR "arg x for printf verb %U of wrong type" fmt.Printf("%x", nil) // ERROR "arg nil for printf verb %x of wrong type" fmt.Printf("%X", 2.3) // ERROR "arg 2.3 for printf verb %X of wrong type" fmt.Printf("%s", stringerv) // ERROR "arg stringerv for printf verb %s of wrong type" fmt.Printf("%t", stringerv) // ERROR "arg stringerv for printf verb %t of wrong type" fmt.Printf("%q", notstringerv) // ERROR "arg notstringerv for printf verb %q of wrong type" fmt.Printf("%t", notstringerv) // ERROR "arg notstringerv for printf verb %t of wrong type" fmt.Printf("%t", stringerarrayv) // ERROR "arg stringerarrayv for printf verb %t of wrong type" fmt.Printf("%t", notstringerarrayv) // ERROR "arg notstringerarrayv for printf verb %t of wrong type" fmt.Printf("%q", notstringerarrayv) // ERROR "arg notstringerarrayv for printf verb %q of wrong type" fmt.Printf("%d", Formatter(true)) // correct (the type is responsible for formatting) fmt.Printf("%s", nonemptyinterface) // correct (the dynamic type of nonemptyinterface may be a stringer) fmt.Printf("%.*s %d %g", 3, "hi", 23, 'x') // ERROR "arg 'x' for printf verb %g of wrong type" fmt.Println() // not an error fmt.Println("%s", "hi") // ERROR "possible formatting directive in Println call" fmt.Printf("%s", "hi", 3) // ERROR "wrong number of args for format in Printf call" _ = fmt.Sprintf("%"+("s"), "hi", 3) // ERROR "wrong number of args for format in Sprintf call" fmt.Printf("%s%%%d", "hi", 3) // correct fmt.Printf("%08s", "woo") // correct fmt.Printf("% 8s", "woo") // correct fmt.Printf("%.*d", 3, 3) // correct fmt.Printf("%.*d", 3, 3, 3, 3) // ERROR "wrong number of args for format in Printf call.*4 args" fmt.Printf("%.*d", "hi", 3) // ERROR "arg .hi. for \* in printf format not of type int" fmt.Printf("%.*d", i, 3) // correct fmt.Printf("%.*d", s, 3) // ERROR "arg s for \* in printf format not of type int" fmt.Printf("%*%", 0.22) // ERROR "arg 0.22 for \* in printf format not of type int" fmt.Printf("%q %q", multi()...) // ok fmt.Printf("%#q", `blah`) // ok printf("now is the time", "buddy") // ERROR "no formatting directive" Printf("now is the time", "buddy") // ERROR "no formatting directive" Printf("hi") // ok const format = "%s %s\n" Printf(format, "hi", "there") Printf(format, "hi") // ERROR "missing argument for Printf..%s..: format reads arg 2, have only 1" Printf("%s %d %.3v %q", "str", 4) // ERROR "missing argument for Printf..%.3v..: format reads arg 3, have only 2" f := new(stringer) f.Warn(0, "%s", "hello", 3) // ERROR "possible formatting directive in Warn call" f.Warnf(0, "%s", "hello", 3) // ERROR "wrong number of args for format in Warnf call" f.Warnf(0, "%r", "hello") // ERROR "unrecognized printf verb" f.Warnf(0, "%#s", "hello") // ERROR "unrecognized printf flag" Printf("d%", 2) // ERROR "missing verb at end of format string in Printf call" Printf("%d", percentDV) Printf("%d", &percentDV) Printf("%d", notPercentDV) // ERROR "arg notPercentDV for printf verb %d of wrong type" Printf("%d", ¬PercentDV) // ERROR "arg ¬PercentDV for printf verb %d of wrong type" Printf("%p", ¬PercentDV) // Works regardless: we print it as a pointer. Printf("%s", percentSV) Printf("%s", &percentSV) // Good argument reorderings. Printf("%[1]d", 3) Printf("%[1]*d", 3, 1) Printf("%[2]*[1]d", 1, 3) Printf("%[2]*.[1]*[3]d", 2, 3, 4) fmt.Fprintf(os.Stderr, "%[2]*.[1]*[3]d", 2, 3, 4) // Use Fprintf to make sure we count arguments correctly. // Bad argument reorderings. Printf("%[xd", 3) // ERROR "illegal syntax for printf argument index" Printf("%[x]d", 3) // ERROR "illegal syntax for printf argument index" Printf("%[3]*s", "hi", 2) // ERROR "missing argument for Printf.* reads arg 3, have only 2" _ = fmt.Sprintf("%[3]d", 2) // ERROR "missing argument for Sprintf.* reads arg 3, have only 1" Printf("%[2]*.[1]*[3]d", 2, "hi", 4) // ERROR "arg .hi. for \* in printf format not of type int" Printf("%[0]s", "arg1") // ERROR "index value \[0\] for Printf.*; indexes start at 1" Printf("%[0]d", 1) // ERROR "index value \[0\] for Printf.*; indexes start at 1" // Something that satisfies the error interface. var e error fmt.Println(e.Error()) // ok // Something that looks like an error interface but isn't, such as the (*T).Error method // in the testing package. var et1 errorTest1 fmt.Println(et1.Error()) // ERROR "no args in Error call" fmt.Println(et1.Error("hi")) // ok fmt.Println(et1.Error("%d", 3)) // ERROR "possible formatting directive in Error call" var et2 errorTest2 et2.Error() // ERROR "no args in Error call" et2.Error("hi") // ok, not an error method. et2.Error("%d", 3) // ERROR "possible formatting directive in Error call" var et3 errorTest3 et3.Error() // ok, not an error method. var et4 errorTest4 et4.Error() // ok, not an error method. var et5 errorTest5 et5.error() // ok, not an error method. // Can't print a function. Printf("%d", someFunction) // ERROR "arg someFunction in printf call is a function value, not a function call" Printf("%v", someFunction) // ERROR "arg someFunction in printf call is a function value, not a function call" Println(someFunction) // ERROR "arg someFunction in Println call is a function value, not a function call" Printf("%p", someFunction) // ok: maybe someone wants to see the pointer Printf("%T", someFunction) // ok: maybe someone wants to see the type // Bug: used to recur forever. Printf("%p %x", recursiveStructV, recursiveStructV.next) Printf("%p %x", recursiveStruct1V, recursiveStruct1V.next) Printf("%p %x", recursiveSliceV, recursiveSliceV) Printf("%p %x", recursiveMapV, recursiveMapV) // Special handling for Log. math.Log(3) // OK Log(3) // OK Log("%d", 3) // ERROR "possible formatting directive in Log call" Logf("%d", 3) Logf("%d", "hi") // ERROR "arg .hi. for printf verb %d of wrong type: untyped string" } // A function we use as a function value; it has no other purpose. func someFunction() { } func Println(args ...interface{}) { panic("don't call - testing only") } // Printf is used by the test so we must declare it. func Printf(format string, args ...interface{}) { panic("don't call - testing only") } // printf is used by the test so we must declare it. func printf(format string, args ...interface{}) { panic("don't call - testing only") } // multi is used by the test. func multi() []interface{} { panic("don't call - testing only") } type stringer float64 var stringerv stringer func (*stringer) String() string { return "string" } func (*stringer) Warn(int, ...interface{}) string { return "warn" } func (*stringer) Warnf(int, string, ...interface{}) string { return "warnf" } type notstringer struct { f float64 } var notstringerv notstringer type stringerarray [4]float64 func (stringerarray) String() string { return "string" } var stringerarrayv stringerarray type notstringerarray [4]float64 var notstringerarrayv notstringerarray var nonemptyinterface = interface { f() }(nil) // A data type we can print with "%d". type percentDStruct struct { a int b []byte c *float64 } var percentDV percentDStruct // A data type we cannot print correctly with "%d". type notPercentDStruct struct { a int b []byte c bool } var notPercentDV notPercentDStruct // A data type we can print with "%s". type percentSStruct struct { a string b []byte c stringerarray } var percentSV percentSStruct type recursiveStringer int func (s recursiveStringer) String() string { _ = fmt.Sprintf("%d", s) _ = fmt.Sprintf("%#v", s) _ = fmt.Sprintf("%v", s) // ERROR "arg s for printf causes recursive call to String method" _ = fmt.Sprintf("%v", &s) // ERROR "arg &s for printf causes recursive call to String method" _ = fmt.Sprintf("%T", s) // ok; does not recursively call String return fmt.Sprintln(s) // ERROR "arg s in Sprintln call causes recursive call to String method" } type recursivePtrStringer int func (p *recursivePtrStringer) String() string { _ = fmt.Sprintf("%v", *p) return fmt.Sprintln(p) // ERROR "arg p in Sprintln call causes recursive call to String method" } type Formatter bool func (*Formatter) Format(fmt.State, rune) { } type RecursiveSlice []RecursiveSlice var recursiveSliceV = &RecursiveSlice{} type RecursiveMap map[int]RecursiveMap var recursiveMapV = make(RecursiveMap) type RecursiveStruct struct { next *RecursiveStruct } var recursiveStructV = &RecursiveStruct{} type RecursiveStruct1 struct { next *Recursive2Struct } type RecursiveStruct2 struct { next *Recursive1Struct } var recursiveStruct1V = &RecursiveStruct1{} // Fix for issue 7149: Missing return type on String method caused fault. func (int) String() { return "" } ================================================ FILE: testData/highlighting/pointers.go ================================================ package main type T int func (T) M() {} var w *T var x *T var y **T var z ***T func main() { w.M() x.M() y.M() z.M() } type Name struct { aaa int } type B *Name func _(b *B) { b.aaa } func _() { b := new(B) b.aaa } ================================================ FILE: testData/highlighting/rangeIterationOnIllegalType.go ================================================ package main import "fmt" type TestStruct struct { SomeId int } type DataSlice []*TestStruct func _() { data := &DataSlice{} for _, element := range data { // here we should have an error: cannot range over data (type *DataSlice) if element.SomeId > 20 { println("some text") } } } func _() { data := DataSlice{} for _, element := range &data { // here we should have an error: cannot range over cannot range over &data (type *DataSlice) if element.SomeId > 20 { println("some text") } } } func main() { nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } for i, c := range "go" { fmt.Println(i, c) } } ================================================ FILE: testData/highlighting/ranges.go ================================================ package main import "fmt" func append1([]Type, ...Type) []Type type Type int type int int type string string func println1(o... interface {}) { fmt.Println(o) } type Person struct { Name string Likes []string } type ( Packet struct { path string } Plugin struct { Path string Packets Packets } Packets []*Packet ) func main() { var people []*Person likes := make(map[string][]*Person) for _, p := range people { for _, l := range p.Likes { likes[l] = append1(likes[l], p) } } for k, v := range likes { println1(k) println1(v[1].Likes) } var people []*Person // todo: should be redeclared for a, p := range people { println(p.Likes) } for _, p2 := range create() { println(p2.Likes) } var p Plugin = nil for _, p := range p.Packets { println(p.path) } for _, d := range d.Packets { } } func create() []*Person {return make([]*Person, 0)} type myStruct struct { MyVal bool } type myChanType chan myStruct func chanFn(c myChanType) { for v := range c { fmt.Printf("Got %v\n", v.MyVal) // v.MyVal is unresolved } } func _() { ch := make(myChanType) go chanFn(ch) ch <- myStruct{true} } type sampleType struct { a int } type a_ b_ type b_ sampleChan type sampleChan chan sampleType func sample() a_ { return make(chan sampleType, 3) } func _() { c := sample() c <- sampleType{1} c <- sampleType{2} c <- sampleType{3} close(c) for t := range (((c))) { println(t.a) } } ================================================ FILE: testData/highlighting/receiverType.go ================================================ package main import ( "fmt" ) type Vertex struct { X, Y float64 } func main() { v := Vertex{3, 4} fmt.Print(v.Abs()) } func (v *Vertex) Abs() float64 { return (*v).X*v.X + v.Y*v.Y } func (Abs) methodOnFunction() { } ================================================ FILE: testData/highlighting/recv.go ================================================ package main func main() { var ch = make(chan int) select { case test := <-ch: { test := 1 print(test) } } } ================================================ FILE: testData/highlighting/redeclaredImportAsFunction.go ================================================ package demo import "fmt" func _() { fmt.Println("Hello") } func fmt() {} ================================================ FILE: testData/highlighting/relativeImportIgnoringDirectories.go ================================================ package test import `./.name` import `./_name` import `./testdata` ================================================ FILE: testData/highlighting/request.go ================================================ package foo import "net/http" type Request interface { GetHttpRequest() *http.Request } func _(r *http.Request) { print(r.URL.Path) } ================================================ FILE: testData/highlighting/reservedWordUsedAsName.go ================================================ package main type byte struct{} type string interface{} func uint() {} func (u byte) uint() {} func main() { const int = 1 string := "" _ = string } ================================================ FILE: testData/highlighting/returns.go ================================================ package main func main() { Ok1() + Ok2(42) + Ok3() + Ok4() + Ok5() + Ok6() + Ok7() + Ok8() + NoReturn1() + NoReturn2() + NoReturn3(1) + NoReturn4(1) + NoReturn5(1) + NoReturn6(1) + NoReturn65(1) + NoReturn7(1) + NoReturn8(1) + NoReturn9(1) Ok9() SwitchType(nil) rsaPKCS1v15SignatureAlgorithmForHashID(42) rsaPKCS1v15SignatureAlgorithmForHashID2(42) func() int { } } func Ok1() int { return 3 /* */ // } func Ok2(a int) int { if a > 0 { return 3 } panic("NO!") } func Ok3() int { Label: return 3 } func Ok4() bool { for { println("to infinity and beyond!") } } func Ok5() bool { a := 0 if a > 0 { return true }else if a < 0 { return true }else { return false } } func Ok6() bool { a := make(chan bool) select { case <-a: return false default: return true } } func Ok7() bool { a := 3 switch a { case 1: return false case 2: return true default: return true } } func Ok8() bool { for a := 0;; a++ { } } func Ok9() (){ for a := 0;; a++ { } } func NoReturn1() int { } func NoReturn2() (int, int) { } func NoReturn3(a int) (int, int) { if a == 5 { return a, a } } func NoReturn4(int) (int, int) { a := 3 for a > 0 { } } func NoReturn5(int) (int, int) { a := 3 if a > 0 { return 0, 0 } } func NoReturn6(int) (int, int) { a := 3 if a > 0 { return 0, 0 }else if a < 2 { return 0, 0 } } func NoReturn65(int) (int, int) { a := 3 if a > 0 { return 0, 0 }else { } } func NoReturn7(int) (int, int) { a := 3 switch a { case 1: return 0, 0 } } func NoReturn8(int) (int, int) { a := 3 switch a { case 1: return 0, 0 default: } } func NoReturn9(int) (int, int) { a := make(chan bool) select { case <-a: return 0, 0 default: } } func SwitchType(err error) int { switch err.(type) { case nil: return 1 } } func rsaPKCS1v15SignatureAlgorithmForHashID(hashID int) string { switch { case hashID == 512: return "asd2" case hashID == 512: return "asd1" case hashID == 512: fallthrough default: return "asdas" } } func rsaPKCS1v15SignatureAlgorithmForHashID2(hashID int) string { switch { case hashID == 512: return "asd2" case hashID == 512: return "asd1" case hashID == 512: default: return "asdas" } } ================================================ FILE: testData/highlighting/selector.go ================================================ package main import "db" type search struct { generals []string } type context struct { Db db.Database } func initDb(c context) { _ := c.Db.search } ================================================ FILE: testData/highlighting/shortVars.go ================================================ package main import "fmt" func main() { fmt.Println(test()) y := 1 y, _ := 10, 1 fmt.Println(y) } func f1() int {return 1} func f2() (int, int) {return 1, 2} func test() int { x := f1() y, z := f2() x := f1() y, z := f2() fmt.Println(test21313()) fmt.Println(Test2()) x, a := f2() // Ok: `x` is reused and `a` is new b, x := f2() // Ok: `b` is new and `x` is reused return x + y + z + a + b // Just to avoid unused variable error } func test21313() (err int) { { err := 1 return err } return 1 } func bar() error { return nil } func Test2() (err error) { err := bar() if err := bar(); err != nil { return err } else { err := bar() return err } switch err := bar(); { // missing switch expression means "true" case err != nil: return -err default: return err } var c chan int // todo: fix inspection //noinspection GoVarDeclaration select { case err, ok := (<-c): println(err) println(ok) } return err } func _(i int) { for i := 1; i < 3; i++ { _ = i } if i := 1; i > 0 { _ = i } switch i := 1; { case true: _ = i } } func _() string { select { case s := <- ch: case a := <- s: } return s } ================================================ FILE: testData/highlighting/simple.go ================================================ package main import "" import fmt "" import "net/http" import "io" func x(string) {} func main() { println([]string) ((string)) x((string)("foo")) x(string + string) var b Boom Boom.Run(b, aaa{}) string test := test Println(test) test. } type aaa aaa type Boom struct { err aaa } func (b *Boom) Run(a aaa) (r1 aaa, r2 aaa) { b.err + a + r1 + r2 } func _() int { Label: goto Label } func _() int { for i := 1; ; i++ { break } } func _() int { Label: for i := 1; ; i++ { break Label } } func _() int { Label: for i := 1; ; i++ { if (true ) { break Label } } } func _() int { Label: for i := 1; ; i++ { goto Label } } func _() int { for true { return 1 } } func _() int { for i := 1; ; i++ { } } func _() int { for i := 1; i < 10; i++ { return 1 } } func foo() { i := 1 for (i) {return 0} if (i) {return j} headers := []int{1} for _, h := range headers { h++ } } var nil int type int int type byte byte type bool bool type float32 float32 type string string type T struct { a int } func (tv T) Mv(int) int { return 0 } // value receiver func (tp *T) Mp(float32) float32 { return 1 } // pointer receiver var t T func _() { t.Mv(7) T.Mv(t, 7) (T).Mv(t, 7) f1 := T.Mv; f1(t, 7) f2 := (T).Mv; f2(t, 7) fmt f1(fmt) } func foo() { a := &A{} b := &B{b:"bbb"} e := &Empty{} y := make(A, 10) z := new(A) y.hola() z.hola() a.hola() b.hola() e.hola() b.b = "jj" } type B struct { *A b string } type A struct { *Empty a int } type Empty struct { } func (this *Empty) hola() { } type AA struct { N int } func _(b *AA) { b.N } func _(interface{}, ...interface{}) { } func _(o interface{}) { func(i interface{}) { Println(o) Println(i) } } func _(integers []int) []int { ch := make(chan int) responses := []int{} for _, i := range integers { go func(j int) { ch <- j * j }(j) } for _, i := range integers { go func(j int) { ch <- j * j }(i) } err := 1 _, err = 1, 1 return integers } func Println(...interface{}) { } func _() { type connError struct { cn int } ch := make(chan connError) Println(ch.cn) } type ConnStatus interface { Status() int32 Error() error } func Bind() <-chan ConnStatus { ch := make(chan ConnStatus, 1) return ch } func _() { a := Bind() for c := range a { Println("Connection status:", c.Status()) } } type Iface interface { Boo() int } const name1 int = 10 func _(st interface {Foo()}, st1 Iface) { name1, name1 = 1, 2 for name1 = range st { } for name1 = range st { } Println(st.Foo() + st1.Boo()) } // No new variables on left side func _() { c := make(chan int) select { case _ := <-c: println("Ololo") default: } for _ := range "asd" { } if _ := 1 { return } buzz := 0 println(buzz) buzz := <-c buzz = <-c } func _() { goto Label1; Label1: 1; goto Label2} type compositeA struct { int } type compositeB struct { byte } func _ () { a0, b0 := composite1() Println(a0.int, b0.byte) a1, b1 := new(compositeA), new(compositeB) Println(a1.int, b1.byte) a2, b2 := composite2() Println(a2.int, b2.byte) } func composite1() (*compositeA, *compositeB) { return new(compositeA), new(compositeB) } func composite2() (*compositeA, *compositeB) { return new(compositeA), new(compositeB) } func _(o interface {test1() int}) { Println(o.test1()) } func _() (int) { type connError struct { err int } ch := make(chan connError) select { case ce := <-ch: return ce.err } } type Item struct { Key string Value []byte } func _() { m := GetMulti() v := m["AA"].Value Println(v) Println(GetMulti()["AA"].Key) } func GetMulti() (map[string]*Item) { m := make(map[string]*Item) m["AA"] = &Item{} return m } type WebService struct { rootPath string } func (w *WebService) Path(string) *WebService { return w } func (w *WebService) GET(string) *RouteBuilder { return new(RouteBuilder) } type RouteBuilder struct { bool } func (w *WebService) Route(*RouteBuilder) *WebService { return w } func _() { ws1 := new(WebService).Path("/") ws1.GET("").bool ws1.Route(ws1.GET("/{type}/{id}")) } type ServiceError struct { Code int Message string } type ForSwitch struct { Value interface{} } func _(x ForSwitch) { switch x := x.Value.(type) { } } func _() { err := nil switch err.(type) { case ServiceError: ser := err.(ServiceError) Println(ser.Code) Println([]byte(ser.Message)) } } func _(err interface{}) { switch err.(type) { case ServiceError: ser := err.(ServiceError) Println(ser.Code) Println([]byte(ser.Message)) } } type Request struct { Request *http.Request } func _(r *Request) { r.Request.URL } type ReadCloser interface { io.Reader io.Closer } func _(b ReadCloser) { b.Closer() b.Close() } func _() { var tempregexs = []struct { template, regex string literalCount, varCount int }{ {"", "^(/.*)?$", 0, 0}, {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, } for i, fixture := range tempregexs { fixture.regex } } type Route struct { } func (r Route) matchesContentType() { } func _() { rs := []Route{} for _, each := range rs { if each.matchesContentType() { } } var rs2, i = makeTuple() for _, each := range rs2 { if each.matchesContentType() { } } } func makeTuple() ([]Route, int) { return []Route{}, 1 } type Greeting struct { Author string Content string } func _() { greetings := make([]Greeting, 0, 10) for i, value := range greetings { if (value.Content == "") { greetings[i].Content = "" } } } type R struct { Body int } func _() { response := make(chan *R, 1) r := <- response Println(r.Body) Println(response.Body) } func _(a int, a int, c, d, c int) (a, d, x int) { return 1,1,1 } func _(int, ... int, string) (_,_,_ int) { return 1,1,1 } func _(_ int, _, _... int) (_,_,_ ...int) { return 1,1,1 } type RGBA struct { R, G, B, A uint8 } type ( Color RGBA ) func _(col Color) string { Println(col.B) var testdata *struct { a *[7]int } Println(testdata.a) } func _(col Color) () { Println(col.B) var testdata *struct { a *[7]int } Println(testdata.a) } type Name struct { } type B Name func (self *Name) Foo(int) { } func _(b B, c Color) { b.Foo(1) c.A } var Name11 string = "" var nmame11 string = "" func _() int { y, z := 1,3 if y == z {} // Just to avoid unused variable error { y, z := 1, 2 // Should not be an error for vars y and z shadow y and z from the outer scope if y == z {} // Just to avoid unused variable error } return 1 } func init() { } func _() int { { return 1 } } func _(bar func(baz int)) { baz } type Ormer interface { Insert(interface{}) } func _(o Ormer) { (*o).Insert(1) } type Conn interface { Do(commandName string, args ...interface{}) (reply interface{}, err error) } func String(interface{}, error) { } func _(c Conn) { String(c.Do("GET", "somekey")) } type MyType string func (t MyType) Get(string) string { return "hello" } func _() { st := MyType("tag") st.Get("key") // <- unresolved Get } type TestStruct struct { SomeId int } type DataSlice []*TestStruct func NewDataSlice() *DataSlice { return &DataSlice{} } func _() { data := NewDataSlice() for _, element := range data { if element.SomeId > 20 { println("some text") } } } type Params struct { } type Image interface { } type ServerFunc func(params Params) (*Image, error) func (f ServerFunc) Get(params Params) (*Image, error) { return f(params) } type Server interface { Get(Params) (*Image, error) } func _() { server := ServerFunc(func(Params) (*Image, error) { return nil, nil }) server.Get(Params{}) } func _() { type ( client struct { message chan string } clientList struct { m (((map[string]*client))) } ) cl := clientList{m: make(map[string]*client)} message := "" for _, c := range cl.m { c.message <- message } } func _() { addr := "test" x := struct { addr string }{addr: addr} Println(x) } func _() { tests:=[]struct{ want int}{} println(tests) want := "" Println(want) } type SensorFactory struct { Sensors map[string]string } func _() *SensorFactory { factory := new (SensorFactory) factory.Sensors = make(map[string]string) return factory } type Conn1 interface { Close() error } func _() { clientList := make(map[int]struct{ message chan string conn *Conn1 }) message := "" for _, c := range clientList { select { case c.message <- message: default: (*c.conn).Close() } } } type inner_t struct{} func (aa inner_t) foo() { } func _() { c := 10 var fun = func(c inner_t) { c.foo(); } fun(inner_t{}) print(c) } type B1 struct {a string} type B2 B1 func (b B2) method() B2 { return B2{} } func _() { b := B2{a:""} b.method() } func z(int) {} func _() { var f float64 f = 12.345 var i int i = int(f) z(i) i = int() z(i) i = int(3, 4) } type myIFace string func (myIFace) Boo() int { return 444 } type someInterface interface { Foo() string } type someStringType string type anotherStringType someStringType func (someStringType) Foo() string { return "what" } func (anotherStringType) Foo() string { return "what" } func _() { var x someInterface x = someStringType("something") if z, ok := x.(someStringType); ok { if len(string(z)) > 0 {} } x = anotherStringType if z, ok := x.(someStringType); ok { if len(string(z)) > 0 {} } } type interf1 interface{} type interf2 interf1 type interf3 interf2 func _() { var x string if _, ok := x.(string); ok { } var y interf3 if _, ok := y.(string); ok { } } func _() { var x map[string]string x = map[string]string{"a", "b"} if len(x) > 2 {} } type someInterface interface{} func _() { var x Boom var y someInterface y = x if _, ok := y.(Boom); ok { } switch z := y.(type) { case Boom: z.Run(aaa{}) case *Boom: z.Run(aaa{}) } } type baseType interface { Method() string } type middleType struct { baseType } func (c *middleType) /*def*/Method() string { return "Hi!" } type leafType struct { middleType } func _() { var leaf = leafType{} println(leaf./*ref*/Method()) var middle = middleType{} println(middle./*ref*/Method()) } // The only acceptable declarations of init at the top level: as a function with no params // or as a method. var init = 4 type ( someNotInitType string init int ) const ( someConst = 1 init = 4 ) type someInitType struct{} func (someInitType) init() {} func init(int) {} func init() int { return 4 } type GroupSlice []Group type Group int func (gs *GroupSlice) Merge(groups ...*Group) error { for _, g := range groups { if err := (*gs).merge(g); err != nil { return err } } return nil } func (gs *GroupSlice) merge(*Group) error { return nil } type TestType struct{} func (t TestType) func1() { } func test90() ( TestType, error, ) { return TestType{}, nil } func _() { t, _ := test90() t.func1() } func _(key1, key2 int) (string, error) { type MyStruct struct { Name string Label string } var cache map[int]((map[int]MyStruct)) = make((map[int]((map[int]MyStruct)))) tmp1, _ := cache[key1] tmp2, _ := tmp1[key2] return tmp2.Name, nil } // do not resolve inside type func _() { var _ func(variableInFunctionType float64) println(variableInFunctionType) } func _() { _ = 'a';'aaa'' _ = ''' _ = ' ;_ = ' a _ = 'a' _ = 'a ' } func _() { _ = "a" "aaa _ = "" _ = " _ = " a } type foo23213 struct { bar string } var ( _ = [](*foo23213){ { bar: "whatever", }, { }, } ) func (c bufio.Reader) aa(d bufio.MaxScanTokenSize){} ================================================ FILE: testData/highlighting/sliceWithThirdIndex.go ================================================ package main var ( a = [10]int{} _ = a[1: 2: 3] ) func main(){ } ================================================ FILE: testData/highlighting/slices.go ================================================ package main import "fmt" type Foo struct { F int } func bar() int { slice0 := make([]Foo, 10) slice1 := slice0[1:1:1] slice1[0].F = 1 return slice1[0].F } func main() { fmt.Println(bar()) main2() } type Foo2 struct { Test int } func main2() { var a *[]Foo2 (*a)[0].Test // todo: should be an error var b *[]Foo2 b[0].Test // todo: should be an error test(a) } func test(a *[]Foo2) { fmt.Println((*a)[0].Test) for _, c := range *a { fmt.Println(c.Test) } } type Param struct { Id string } type Params []Param func hola(params Params) { params[0].Id } type Params []Param func hola2(params []Param) { params[0].Id // the inspector find the Id field } type File struct { Contents string } func sourceReader(files <-chan *File) { for file := range files { file.Contents } } type FooSl struct { a int } type Baz [5]FooSl type ZOO Baz func _(){ b := &ZOO{} b[0].a = 1 } type typ1 struct { } type typ2 struct { t1 typ1 } func (t typ1) F() { print("t1.F()") } func _() { t2 := typ2{t1:typ1{}} t1 := &t2.t1 t1.F() } ================================================ FILE: testData/highlighting/specTypes.go ================================================ package main type MyType struct { Err string } type t MyType type d t func (a t) foo(){} func (a d) too(){} func main() { e := MyType{ Err: "hello", } out := d(e) println(out.Err) } type a int func (a) foo() int { return 1 } type b int func (b) bar() int { return 2 } type c struct { a b } func _() { c := new(c) println(c.foo()) println(c.bar()) } ================================================ FILE: testData/highlighting/stop.go ================================================ package main type T interface { Method1() T Method2() } type T2 int func (t T2) F1() { } func (t T2) F2() T2 { return nil } func main() { var x T x.Method1().Method2().Method2() var x1 T2 x1.F2().F1().F1() } ================================================ FILE: testData/highlighting/stringInStructSliceWithThirdIndex.go ================================================ package main type t struct { s string } var ( p = t {"asd"} _ = p.s[1:2:3] ) func main(){ } ================================================ FILE: testData/highlighting/stringIndexIsByte.go ================================================ package main import "fmt" func main() { x := "text" if x[0] == "t" && x[1] == 't' { fmt.Println(x[0]) } valid := x[1] == 't' valid = x[0:2] == "te" valid = x[:2] == "te" valid = x[2:] == "xt" valid = x[:] == "xt" fmt.Println(valid) invalid := x[2] == "xt" invalid = "t" == x[0] invalid = x[3] == "x" invalid = x[3] != "x" invalid = x[3] >= "x" invalid = x[3] <= "x" invalid = x[3] > "x" invalid = x[3] < "x" fmt.Println(invalid) } ================================================ FILE: testData/highlighting/stringSliceWithThirdIndex.go ================================================ package main var _ = "asdasd"[1:2:3] func main(){ } ================================================ FILE: testData/highlighting/struct.go ================================================ package main import . "fmt" import "net/url" type alias Formatter type int int type Car struct { wheelCount int } func (car Car) numberOfWheels() int { return car.wheelCount } type Ferrari struct { Car } func Println(...interface{}) { // should be redeclared! // fmt.Println(o...) } func (f Ferrari) sayHiToSchumacher() { Println("Hi Schumacher!") } type AstonMartin struct { Car } func (a AstonMartin) sayHiToBond() { Println("Hi Bond, James Bond!") } type E struct { *E } func (e E) foo() { } type Type int func new(Type) *Type type T int func (t T) name() { } func foo() *T { return new(T) } func doubleFoo() (*T, *T) { return foo(), foo() } func (t T) createT() *T { return new(T) } func main() { e := E{} e.foo() f := Ferrari{Car{4}} Println("A Ferrari has this many wheels:", f.numberOfWheels()) f.sayHiToSchumacher() c := Car{4} Println("A Car has this many wheels:", c.wheelCount) Println("A Car has this many wheels:", c.numberOfWheels()) a := AstonMartin{Car{4}} Println("An Aston Martin has this many wheels:", a.numberOfWheels()) a.sayHiToBond() t := foo() t.name() t2 := t.createT() Println(t2) t3 := doubleFoo() Println(t3) } type inte struct { aa int aa, bbb int byte1 struct { aaa aaa } } type aaa interface { String() int } type inte2 struct { byte1 struct { int int } byte1 struct { int int } } type aaa interface { Str() Str() interface { A() b() A() } } type A struct { b int c int } func NewA(b int) *A { return &A{ b: b, // Reported error: "unknown field b", but that is not correct c: 1, } } func _() { tr := &url.Userinfo{ username:"Name", } _ = tr } type Mtx struct { state int32 sema uint32 } func (m *Mtx) Lock() { } func (m *Mtx) Unlock() { } type Locker interface { Lock() Unlock() } type TMtx struct { M struct { Mtx } } func _() { t := TMtx{} t.M.Lock() t.M.Unlock() } ================================================ FILE: testData/highlighting/structTags.go ================================================ package demo type demoBrokenTags struct { CorrectMultipleTags string `json:"demo,something,something" dark:"side"` CorrectSingleTag string `json:"demo,something,something"` WrongTag1 string `json: "demo"` WrongTag2 string `json:"demo` WrongTag3 string `json:demo` WrongTag4 string ` json:demo` WrongTag5 string "json:demo" WrongTag6 string "json:'demo'" WrongTag7 string `json:"demo"; bson:"demo"` WrongTag8 string ` } ================================================ FILE: testData/highlighting/stubParams.go ================================================ package main import ( "os" ) func writeValues(outfile string) string { file, _ := os.Create(outfile) return file.Name() } ================================================ FILE: testData/highlighting/templates.go ================================================ package main import "text/template" func main() { template.Must(template.ParseGlob("templates/*")) } ================================================ FILE: testData/highlighting/typeConversion.go ================================================ package main type ( int64Val int64 boolVal bool Value interface { Demo() } ) func (int64Val) Demo() {} func (boolVal) Demo() {} func _(x, y Value) { switch x := x.(type) { case boolVal: y := y.(boolVal) _, _ = x, y case int64Val: b := int64(y.(int64Val)) _ = b } } func main() {} ================================================ FILE: testData/highlighting/typeLiterals.go ================================================ package main; import "fmt" type WaitGroup struct { counter int32; waiters int32; sema *uint32 } func main() { fmt.Println(WaitGroup{sema:nil}) } func main3() { fmt.Println(WaitGroup{s1ema:nil}) } func main2() { fmt.Println(WaitGrou1p{sema:nil}) } func _() { type policyTableEntry struct { Prefix string Precedence uint8 Label uint8 } type policyTable []policyTableEntry var _ = policyTable{ { Prefix: "test", Precedence: 50, Label: 0, }, { Prefix: "test2", Precedence: 40, Label: 1, }, } } type Response struct { ResponseWriter } type ResponseWriter interface { Header() Header } type Header int func (h Header) Add(_, _ string) { } func (r Response) AddHeader(header string, value string) Response { rr := r.Header() rr.Add("", "") r.Header().Add(header, value) return r } type Foo struct { A int } type Zoo Foo type Bar Zoo func _() { fmt.Println(Test()) } func Test() Bar { fmt.Println(Foo{A:1}) fmt.Println(Zoo{A:1}) return Bar{A: 1} } type setAuthRequest auth type auth struct { Type int32 Scheme string Auth []byte } func _(scheme string, auth []byte) *setAuthRequest { return &setAuthRequest{Type: 0, Scheme: scheme, Auth: auth} } ================================================ FILE: testData/highlighting/unaryMinus.go ================================================ package main type bar int type foo struct { a bar } func (b bar) printValue() { println(b) } func main() { t := foo { a:4, } t.a.printValue() (-t.a).printValue() } ================================================ FILE: testData/highlighting/unaryPointer.go ================================================ package main type Rat struct { a, b int } type Ad struct { Price Rat } func (x *Rat) Cmp(*Rat) int { return 1 } func main() { rat := &Rat{1, 1} i1 := Ad{}.Price i := &i1 i.Cmp(rat) } ================================================ FILE: testData/highlighting/underscoreUsedAsValue.go ================================================ package main var demov = _ var ( demov1, demov2 = _, _ ) const democ = _ const ( democ1, democ2 = _, _ ) func main() { println(_, "hello1") a, b:= 1, _ _, _, _, _ = a, b, demov, democ _, _, _, _ = demov1, demov2, democ1, democ2 c := 1 + _ + (_) println(_ + (_)) println(c) select { case _ <- 0: break; case _ <- 1: break; case _ = <- 1: break; } for _, _ = range _ { } } ================================================ FILE: testData/highlighting/unusedParameter.go ================================================ package main type ( de interface { Demo(x, y int) } demoo func(p int) (size int) dem string ) func (d dem) demo(hello string) (err int) { println("hello") return nil } func demo(hello string) { func(hello string) { println(hello) }(hello) } func demo2(hello string) { func(hello string) { println(hello) }("hello") } func demo3(hello string) { func() { println(hello) }() } func _(bar func(baz int) (foo int)) { _ = bar } func _(fn func() (i int, e error)) { i, e := fn() print(i) print(e.Error()) } func main() { demo("hello") demo2("hello") demo3("hello") a := dem("hello") a.demo("hello") *(*func(width int) struct{})(nil) } ================================================ FILE: testData/highlighting/unusedParameter_test.go ================================================ package main import "testing" func TestName(t *testing.T) { } func _(t *testing.T) { } ================================================ FILE: testData/highlighting/varBlocks.go ================================================ package main import "fmt" func main() { fmt.Println(test()) fmt.Println(test2()) test3() test4() test5() } func foo() int { return 1 } func test() func() int { fff := foo return func() int { r := fff() return r } } func test2() func () int { f := foo return func() int { r := 1 r = f() return r } } func test3() { if x := 10; x < 9 { fmt.Println(x) } else { fmt.Println("not x") } fmt.Println(x) } func test4() { x := 5 if x := 10; x < 9 { fmt.Println(x, "exists here") } else { fmt.Println("and here!", x) } fmt.Println(x) } func test5() { xy := 5 if xy := 10; xy < 9 { fmt.Println(xy, "exists here") } else { fmt.Println("and here!", xy) } } func _() { fs := *(*func(width int) struct{})(nil) width := 1 _, _ = fs, width } func _() { *(*func(width int) struct{})(nil) width := 1 _ = width } ================================================ FILE: testData/highlighting/varToImport.go ================================================ package main import "fmt" import "time" var ( fmt, _ = fmt.Print(1) // fmt redeclared in this block // previous declaration at *.go:3 ) func main() { } func _() { time := time.Now() fmt.Println(time.Hour()) } ================================================ FILE: testData/highlighting/variadic.go ================================================ package main import "fmt" import "go/ast" type Ref struct { Expr *ast.Expr } type Closer interface { Close() } type CloseImpl struct {} func (impl *CloseImpl) Close() { fmt.Println("closed") } type File struct { name string Closer } func getFile() *File { return &File{"hello", &CloseImpl{}} } func main() { f1 := &File{"hello", &CloseImpl{}} f1.Close() f2 := getFile() f2.Close() // Unresolved reference Close } type User interface { Name() string } func _(users ...User) { users[0].Name() } func _(users ...*User) { users[0].Name() } func _(users User) { users[0].Name() } func _(users ...User) { users.Name() } func _(users *User) { (*users).Name() } func _(users User) { users.Name() } func (r *Ref) Pos() { l1 := *r.Expr l1.Pos() l2 := (*r.Expr) l2.Pos() *r.Expr.Pos () (*r.Expr).Pos() } ================================================ FILE: testData/highlighting/vars.go ================================================ package main import "fmt" import "net/http" import "time" func main() { b := 1 b, a := 11, 1 fmt.Println(b, a) c := simple(10) fmt.Println(c) Foo() Foo2() fmt.Println(http.ErrMissingFile) } func simple(a int) int { a, b := 1, 2 return a + b } func Foo() { err := 1 err = 2 } func Foo2() { err := 1 err,x := 2,1 fmt.Println(x) } func _(p interface{}) error { switch p := p.(type) { case error: return nil } return nil } type Image interface { At(x, y int) } type Image2 interface { } func _() { var p Image switch q := p.(type) { case Image: fmt.Println("draw.Image") switch p.(type) { case Image2: q.At(0,0) } case Image2: q.At(0,0) default: fmt.Println("default") q.At(0, 0) } } var ( interval1 = time.Second interval2 = time.Second * 5 ) func TestIdeaTimeApi() { interval1.Nanoseconds() fmt.Printf("%T %T", interval1, interval2) fmt.Printf("%d %d", interval1.Nanoseconds(), interval2.Nanoseconds()) } func _() { fmt.Println(interval2) fmt.Println(time.Second * 5) f(time.Second) TestIdeaTimeApi() } func f(d time.Duration) { fmt.Println((d * time.Second).Nanoseconds()) fmt.Println(d * time.Second * time.Second) } func _() { time := time.Now(); fmt.Println(time) } ================================================ FILE: testData/highlighting/vendoringImportPaths.go ================================================ package a import "vendoringPackage" import "subVendoringPackage" func _() { vendoringPackage.Hello(); subVendoringPackage.Hello(); } ================================================ FILE: testData/highlighting/voidFunctionUsedAsValue.go ================================================ package main; func withParameter(int) { } func withEmptyResult() () { } func withReturnValue() int { return 1 } func main() { go withParameter(2) defer withParameter(2) println(withParameter(3)) withParameter(1) = 2 withParameter(2) println(withEmptyResult()) withEmptyResult() = 2 withEmptyResult() println(func() {}()) func() {}() = 2 func() {}() println(withReturnValue()) withReturnValue() = 2 withReturnValue println(func() int { return 1 }()) func() int { return 1 }() = 2 func() int { return 1 }() } ================================================ FILE: testData/imports/optimize/doNotOptimizeSideEffectImports.go ================================================ package main import _ "fmt" func main() { } ================================================ FILE: testData/imports/optimize/doNotOptimizeSideEffectImports_after.go ================================================ package main import _ "fmt" func main() { } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithDifferentString.go ================================================ package main import "asdf" import fmt "fmt" import fmt "math" import "fmt" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithDifferentString_after.go ================================================ package main import "fmt" import fmt "math" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithSameString.go ================================================ package main import "asdf" import fmt "fmt" import fmt "fmt" import "fmt" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithSameStringAndDifferentQuotes.go ================================================ package foo import `fmt` import "fmt" func main() { fmt.Println("Hi") } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithSameStringAndDifferentQuotes_after.go ================================================ package foo import `fmt` func main() { fmt.Println("Hi") } ================================================ FILE: testData/imports/optimize/duplicatedImportsWithSameString_after.go ================================================ package main import "fmt" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/importDirectoryWithoutPackages.go ================================================ package main import ( "emptyDirectory" "fmt" ) func main() { fmt.Println("Halo"); } ================================================ FILE: testData/imports/optimize/importDirectoryWithoutPackages_after.go ================================================ package main import ( "fmt" ) func main() { fmt.Println("Halo"); } ================================================ FILE: testData/imports/optimize/importPackageWithMainFiles.go ================================================ package main import "withmain" func Bar(r *withmain.SomeType) { } ================================================ FILE: testData/imports/optimize/importPackageWithMainFiles_after.go ================================================ package main import "withmain" func Bar(r *withmain.SomeType) { } ================================================ FILE: testData/imports/optimize/importWithMultiplePackages.go ================================================ import pack func main() { pack.Test() } ================================================ FILE: testData/imports/optimize/importWithMultiplePackages_after.go ================================================ import pack func main() { pack.Test() } ================================================ FILE: testData/imports/optimize/importWithSameIdentifier.go ================================================ package main import fmt "fmt" import fmt "math" import bar "foo/bar" func main() { fmt.Printf("a2",a2) fmt.Println(bar.Hello) } ================================================ FILE: testData/imports/optimize/importWithSameIdentifier_after.go ================================================ package main import "fmt" import fmt "math" import "foo/bar" func main() { fmt.Printf("a2",a2) fmt.Println(bar.Hello) } ================================================ FILE: testData/imports/optimize/redundantImportQualifier.go ================================================ package main import fmt "fmt" func _() { fmt.Println("Hello") } ================================================ FILE: testData/imports/optimize/redundantImportQualifier_after.go ================================================ package main import "fmt" func _() { fmt.Println("Hello") } ================================================ FILE: testData/imports/optimize/unusedDuplicatedImports.go ================================================ package main import "asdf" import "asdf" import asdf "asdf" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedDuplicatedImports_after.go ================================================ package main func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedImplicitImports.go ================================================ package main import . "fmt" import . "math" func main() { Printf("asd") } ================================================ FILE: testData/imports/optimize/unusedImplicitImports_after.go ================================================ package main import . "fmt" func main() { Printf("asd") } ================================================ FILE: testData/imports/optimize/unusedImports.go ================================================ package main import "asdf" import "encoding/json" import ( "math" "math" ) import "fmt" func main() { fmt.Printf("a2",a2) } type testStruct struct { v string } func test(json testStruct) { return json.v } ================================================ FILE: testData/imports/optimize/unusedImportsQuickFix.go ================================================ package main import "asdf" import "encoding/json" import ( "math" "math" ) import "fmt" func main() { fmt.Printf("a2",a2) } type testStruct struct { v string } func test(json testStruct) { return json.v } ================================================ FILE: testData/imports/optimize/unusedImportsQuickFix_after.go ================================================ package main import "fmt" func main() { fmt.Printf("a2",a2) } type testStruct struct { v string } func test(json testStruct) { return json.v } ================================================ FILE: testData/imports/optimize/unusedImportsWithBacktick.go ================================================ package main import `asdf` import ( `math` `math` ) import `fmt` func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedImportsWithBacktick_after.go ================================================ package main import `fmt` func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedImportsWithSemicolon.go ================================================ package main import "asdf"; import ( "math" "math" ); import "fmt"; func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedImportsWithSemicolon_after.go ================================================ package main import "fmt"; func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/unusedImports_after.go ================================================ package main import "fmt" func main() { fmt.Printf("a2",a2) } type testStruct struct { v string } func test(json testStruct) { return json.v } ================================================ FILE: testData/imports/optimize/usedDuplicatedImports.go ================================================ package main import "asdf" import "fmt" import fmt "fmt" import "fmt" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/usedDuplicatedImports_after.go ================================================ package main import "fmt" func main() { fmt.Printf("a2",a2) } ================================================ FILE: testData/imports/optimize/usedImplicitImports.go ================================================ package main import . "fmt" import . "math" func main() { Printf("a2", Abs(1)) } ================================================ FILE: testData/imports/optimize/usedImplicitImports_after.go ================================================ package main import . "fmt" import . "math" func main() { Printf("a2", Abs(1)) } ================================================ FILE: testData/inspections/anon-field/simple-after.go ================================================ package main; type TypeName ***int var a struct { TypeName } ================================================ FILE: testData/inspections/anon-field/simple.go ================================================ package main; var a struct { ***int } ================================================ FILE: testData/inspections/go-defer-function-call/conversions.go ================================================ package main type int struct {} func _() { defer int(0) defer (func() int)(x) } ================================================ FILE: testData/inspections/go-defer-function-call/deferRecover-after.go ================================================ package main func main() { defer func() { if r := recover(); r != nil { } }() } ================================================ FILE: testData/inspections/go-defer-function-call/deferRecover.go ================================================ package main func main() { defer recover() } ================================================ FILE: testData/inspections/go-defer-function-call/funcLiteral-after.go ================================================ package main func _() { go func() {}() } ================================================ FILE: testData/inspections/go-defer-function-call/funcLiteral.go ================================================ package main func _() { go func(){} } ================================================ FILE: testData/inspections/go-defer-function-call/literal.go ================================================ package main func _() { defer 1 } ================================================ FILE: testData/inspections/go-defer-function-call/parens-after.go ================================================ package main func _() { defer func() {}() } ================================================ FILE: testData/inspections/go-defer-function-call/parens.go ================================================ package main func _() { defer (func(){}()) } ================================================ FILE: testData/inspections/go-defer-function-call/parensFunctionType-after.go ================================================ package main func _() { defer (func() {})() } ================================================ FILE: testData/inspections/go-defer-function-call/parensFunctionType.go ================================================ package main func _() { defer (func(){}) } ================================================ FILE: testData/inspections/go-defer-function-call/twiceParens-after.go ================================================ package main func _() { defer 1 } ================================================ FILE: testData/inspections/go-defer-function-call/twiceParens.go ================================================ package main func _() { defer ((1)) } ================================================ FILE: testData/inspections/go-defer-function-call/valid.go ================================================ package main func _() { defer func(){}() go func(){}() } ================================================ FILE: testData/inspections/go-empty-declaration/constVoidDeclaration-after.go ================================================ package main func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/constVoidDeclaration.go ================================================ package main const( ) func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/importVoidDeclarationWithUpperComment.go ================================================ package main // comment to import import ( ) func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/notVoidImportDeclaration.go ================================================ package main import ( "fmt" ) func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/twoVoidImportsWithOneComment-after.go ================================================ package main //comment import () func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/twoVoidImportsWithOneComment.go ================================================ package main //comment import () import () func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/typeVoidDeclaration-after.go ================================================ package main func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/typeVoidDeclaration.go ================================================ package main type( ) func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/varVoidDeclarationInFunction.go ================================================ package main func _() { var() } ================================================ FILE: testData/inspections/go-empty-declaration/varVoidDeclarationNotInFunction-after.go ================================================ package main func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/varVoidDeclarationNotInFunction.go ================================================ package main var() func _() { } ================================================ FILE: testData/inspections/go-empty-declaration/varVoidDeclarationWithInnerComment.go ================================================ package main var( // comment ) func _() { } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithArrays-after.go ================================================ package main type T struct { x, y int } var _ = [42]T{ 10: {1,2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithArrays.go ================================================ package main type T struct { x, y int } var _ = [42]T{ 10: T{1,2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithArraysInBrackets.go ================================================ package main type T struct { x, y int } var _ = [][]int{ ([]int{}), ([]int{1, 2}), } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithInsertedArrays-after.go ================================================ package main type T struct { x, y int } var _ = [][][]int{ { {0, 1, 2, 3}, }, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithInsertedArrays.go ================================================ package main type T struct { x, y int } var _ = [][][]int{ [][]int{ []int{0, 1, 2, 3}, }, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithInterface.go ================================================ package main type T struct { x, y int } var _ = []interface{}{ T{}, 10: T{1, 2}, 20: T{3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithKeysAndSimpleRedundantTypeDecl-after.go ================================================ package main type T struct { x, y int } var _ = [42]T{ 10: {1,2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithKeysAndSimpleRedundantTypeDecl.go ================================================ package main type T struct { x, y int } var _ = [42]T{ 10: T{1,2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMap-after.go ================================================ package main type T struct { x, y int } var _ = map[string]T{ "foo": {}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMap.go ================================================ package main type T struct { x, y int } var _ = map[string]T{ "foo": T{}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMapOfStruct-after.go ================================================ package main type T struct { x, y int } var _ = map[string]struct { + test x, y int }{ "bal": {3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMapOfStruct.go ================================================ package main type T struct { x, y int } var _ = map[string]struct { x, y int }{ "bal": struct{x, y int }{3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMapWithPointerAndStruct-after.go ================================================ package main var _ = map[string]*struct { x, y int }{ "bal": {3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithMapWithPointerAndStruct.go ================================================ package main var _ = map[string]*struct { x, y int }{ "bal": &struct{ x, y int }{3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithOneSimpleRedundantTypeDecl-after.go ================================================ package main type T struct { x, y int } var _ = [42]T{ {}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithOneSimpleRedundantTypeDecl.go ================================================ package main type T struct { x, y int } var _ = [42]T{ T{}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithPointerAndStructAndInsertedElement-after.go ================================================ package main var _ = []*[]*[]int{ { {0, 1, 2, 3}, }, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithPointerAndStructAndInsertedElement.go ================================================ package main var _ = []*[]*[]int{ &[]*[]int{ &[]int{0, 1, 2, 3}, }, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithPointers-after.go ================================================ package main type T struct { x, y int } var _ = []*T{ {1, 2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithPointers.go ================================================ package main type T struct { x, y int } var _ = []*T{ &T{1, 2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithPointersNoFix.go ================================================ package main type T struct { x, y int } var _ = []*T{ T{1, 2}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithStruct-after.go ================================================ package main type T struct { x, y int } var _ = map[string]struct { x, y int }{ {3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithStruct.go ================================================ package main type T struct { x, y int } var _ = []struct { x, y int }{ struct{ x, y int }{3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithTwoDimensionalArray-after.go ================================================ package main type T struct { x, y int } var _ = [][]int{ {3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/compositeLitWithTwoDimensionalArray.go ================================================ package main type T struct { x, y int } var _ = [][]int{ []int{3, 4}, } func main (){ } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneArg.go ================================================ package main func _() { var x []int for a = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneBlankAndOneNotBlankArgs.go ================================================ package p func _() { var x []int for _, a = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneBlankArg-after.go ================================================ package main func _() { var x []int for range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneBlankArg.go ================================================ package main func _() { var x []int for _ = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneNotBlankAndOneBlankArgs-after.go ================================================ package main func _() { var x []int for a = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithOneNotBlankAndOneBlankArgs.go ================================================ package main func _() { var x []int for a, _ = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithTwoArgs.go ================================================ package p func _() { var x []int for a, b = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithTwoBlankArgs-after.go ================================================ package p func _() { var x []int for range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithTwoBlankArgs.go ================================================ package p func _() { var x []int for _, _ = range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithVarAssign-after.go ================================================ package main func _() { var x []int for a := range x { } } ================================================ FILE: testData/inspections/go-simplify/rangeSimplifyWithVarAssign.go ================================================ package main func _() { var x []int for a, _ := range x { } } ================================================ FILE: testData/inspections/go-simplify/slice-after.go ================================================ package main var ( a [10]byte b [20]int t struct { s byte } _ = a[0: ] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/slice.go ================================================ package main var ( a [10]byte b [20]int t struct { s byte } _ = a[0: len(a)] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/sliceWithLenAnotherArray.go ================================================ package main var ( a [10]byte b [20]int t struct { s byte } _ = b[0: len(a)] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/sliceWithOnlySecondIndex-after.go ================================================ package main var ( a [10]byte _ = a[: ] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/sliceWithOnlySecondIndex.go ================================================ package main var ( a [10]byte _ = a[: len(a)] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/sliceWithRedeclaredLen.go ================================================ package main var a [10]byte func len(o [10]byte) int { return 1; } func main (){ _ = a[0: len(a)] } ================================================ FILE: testData/inspections/go-simplify/sliceWithStructIndex.go ================================================ package main var ( a [10]byte b [20]int t struct { s []byte } _ = t.s[0: len(t.s)] ) func main (){ } ================================================ FILE: testData/inspections/go-simplify/sliceWithThreeIndexes.go ================================================ package main var ( a [10]byte b [20]int t struct { s []byte } _ = a[0: len(a): len(a)] ) func main (){ } ================================================ FILE: testData/inspections/go-struct-initialization/quickFix-after.go ================================================ package foo import "io" func _() { _ = io.LimitedReader{ R: nil, } } ================================================ FILE: testData/inspections/go-struct-initialization/quickFix.go ================================================ package foo import "io" func _() { _ = io.LimitedReader{ nil, } } ================================================ FILE: testData/inspections/go-struct-initialization/uninitializedStructImportedOnly.go ================================================ package demo2094 import "io" import "os" type demo struct { a string b int32 c string } type bemo struct { demo x string } type MyStruct struct { a string b []MyElem c [3]MyElem d map[string]MyElem } type MyElem struct { foo string } func _() struct { x string } { // good defs _ = []MyStruct{ { a: "bar", b: []MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, c: [3]MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, d: map[string]MyElem{ "foo": {foo: "foo"}, "bar": {foo: "foo"}, "baz": {foo: "foo"}, }, }, } _ = map[string]MyStruct{ "foo": { a: "bar", b: []MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, c: [3]MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, d: map[string]MyElem{ "foo": {foo: "foo"}, "bar": {foo: "foo"}, "baz": {foo: "foo"}, }, }, } _ = struct{ x string }{x: "demo"} _ = demo{a: "demo"} _ = demo{a: "demo", b: 1} // bad defs _ = demo{"demo"} b, _ := demo{"demo"}, 1 _ = demo{ "demo", 1, "demo", } _ = demo{ a: "demo", 1, } _ = bemo{x: "demo"} _ = b return struct{ x string }{"demo"} } type Item struct { Name string } type Menu []Item func _() { // good defs _ = Menu{ {Name: "home"}, } _ = os.LinkError{ Op: "string", Old: "string", New: "string", Err: nil, } // bad defs _ = io.LimitedReader{ nil, } _ = os.LinkError{ "string", "string", "string", nil, } } type assertion struct { query string } func _() { tests := []struct { assertions []assertion }{ { assertions: []assertion{ { query: "foo", }, }, }, } _ = tests } ================================================ FILE: testData/inspections/go-struct-initialization/uninitializedStructWithLocal.go ================================================ package demo2094 import "io" import "os" type demo struct { a string b int32 c string } type bemo struct { demo x string } type MyStruct struct { a string b []MyElem c [3]MyElem d map[string]MyElem } type MyElem struct { foo string } func _() struct { x string } { // good defs _ = []MyStruct{ { a: "bar", b: []MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, c: [3]MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, d: map[string]MyElem{ "foo": {foo: "foo"}, "bar": {foo: "foo"}, "baz": {foo: "foo"}, }, }, } _ = map[string]MyStruct{ "foo": { a: "bar", b: []MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, c: [3]MyElem{ {foo: "foo"}, {foo: "foo"}, {foo: "foo"}, }, d: map[string]MyElem{ "foo": {foo: "foo"}, "bar": {foo: "foo"}, "baz": {foo: "foo"}, }, }, } _ = struct{ x string }{x: "demo"} _ = demo{a: "demo"} _ = demo{a: "demo", b: 1} // bad defs _ = demo{"demo"} b, _ := demo{"demo"}, 1 _ = demo{ "demo", 1, "demo", } _ = demo{ a: "demo", 1, } _ = bemo{x: "demo"} _ = b return struct{ x string }{"demo"} } type Item struct { Name string } type Menu []Item func _() { // good defs _ = Menu{ {Name: "home"}, } _ = os.LinkError{ Op: "string", Old: "string", New: "string", Err: nil, } // bad defs _ = io.LimitedReader{ nil, } _ = os.LinkError{ "string", "string", "string", nil, } } type assertion struct { query string } func _() { tests := []struct { assertions []assertion }{ { assertions: []assertion{ { query: "foo", }, }, }, } _ = tests } ================================================ FILE: testData/inspections/suppression/fix/commClauseStatementSuppressionFix-after-highlighting.go ================================================ package main func _() { //noinspection ALL select { case foo <- bar: } } ================================================ FILE: testData/inspections/suppression/fix/commClauseStatementSuppressionFix-after.go ================================================ package main func _() { //noinspection ALL select { case foo <- bar: } } ================================================ FILE: testData/inspections/suppression/fix/commClauseStatementSuppressionFix.go ================================================ package main func _() { select { case foo <- bar: } } ================================================ FILE: testData/inspections/suppression/fix/firstImportStatement-after-highlighting.go ================================================ package main //noinspection GoUnresolvedReference import "package1" import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/firstImportStatement-after.go ================================================ package main //noinspection GoUnresolvedReference import "package1" import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/firstImportStatement.go ================================================ package main import "package1" import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFix-after-highlighting.go ================================================ package newmath //noinspection ALL func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFix-after.go ================================================ package newmath //noinspection ALL func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFix.go ================================================ package newmath func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath //noinspection ALL func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFixWithExistingComment-after.go ================================================ package newmath //noinspection ALL func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionAllSuppressionFixWithExistingComment.go ================================================ package newmath //noinspection SomeInspection func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFix-after-highlighting.go ================================================ package newmath //noinspection GoUnresolvedReference func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFix-after.go ================================================ package newmath //noinspection GoUnresolvedReference func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFix.go ================================================ package newmath func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath //noinspection SomeInspection,GoUnresolvedReference func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFixWithExistingComment-after.go ================================================ package newmath //noinspection SomeInspection,GoUnresolvedReference func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/functionSuppressionFixWithExistingComment.go ================================================ package newmath //noinspection SomeInspection func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/importStatement-after-highlighting.go ================================================ package main import "package1" //noinspection GoUnresolvedReference import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/importStatement-after.go ================================================ package main import "package1" //noinspection GoUnresolvedReference import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/importStatement.go ================================================ package main import "package1" import "package2" func test() { } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix.go ================================================ package newmath func TestFunction() { var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix2-after-highlighting.go ================================================ package newmath func TestFunction() { //noinspection GoUnusedVariable var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix2-after.go ================================================ package newmath func TestFunction() { //noinspection GoUnusedVariable var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix2.go ================================================ package newmath func TestFunction() { var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix3-after-highlighting.go ================================================ package newmath //noinspection GoUnusedVariable func TestFunction() { var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix3-after.go ================================================ package newmath //noinspection GoUnusedVariable func TestFunction() { var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/innerVariableDeclarationSuppressionFix3.go ================================================ package newmath func TestFunction() { var var1 = 1; } ================================================ FILE: testData/inspections/suppression/fix/packageClause-after-highlighting.go ================================================ //noinspection GoMultiplePackages package otherPackage ================================================ FILE: testData/inspections/suppression/fix/packageClause-after.go ================================================ //noinspection GoMultiplePackages package otherPackage ================================================ FILE: testData/inspections/suppression/fix/packageClause.go ================================================ package otherPackage ================================================ FILE: testData/inspections/suppression/fix/packageClauseSuppressAll-after-highlighting.go ================================================ //noinspection ALL package otherPackage ================================================ FILE: testData/inspections/suppression/fix/packageClauseSuppressAll-after.go ================================================ //noinspection ALL package otherPackage ================================================ FILE: testData/inspections/suppression/fix/packageClauseSuppressAll.go ================================================ package otherPackage ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFix-after-highlighting.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFix-after.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFix.go ================================================ package main func _() { select { case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFixWithExistingComment-after-highlighting.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFixWithExistingComment-after.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseAllSuppressionFixWithExistingComment.go ================================================ package main func _() { select { //noinspection BlaBlaBla case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFix-after-highlighting.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFix-after.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFix.go ================================================ package main func _() { select { case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFixWithExistingComment-after-highlighting.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFixWithExistingComment-after.go ================================================ package main func _() { select { //noinspection ALL case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/selectCaseSuppressionFixWithExistingComment.go ================================================ package main func _() { select { //noinspection BlaBlaBla case foo <- bar: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFix-after-highlighting.go ================================================ package newmath func TestFunction() { //noinspection ALL Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFix-after.go ================================================ package newmath func TestFunction() { //noinspection ALL Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFix.go ================================================ package newmath func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath func TestFunction() { //noinspection ALL Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFixWithExistingComment-after.go ================================================ package newmath func TestFunction() { //noinspection ALL Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementAllSuppressionFixWithExistingComment.go ================================================ package newmath func TestFunction() { //noinspection SomeInspection Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFix-after-highlighting.go ================================================ package newmath func TestFunction() { //noinspection GoUnresolvedReference Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFix-after.go ================================================ package newmath func TestFunction() { //noinspection GoUnresolvedReference Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFix.go ================================================ package newmath func TestFunction() { Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath func TestFunction() { //noinspection SomeInspection,GoUnresolvedReference Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFixWithExistingComment-after.go ================================================ package newmath func TestFunction() { //noinspection SomeInspection,GoUnresolvedReference Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/statementSuppressionFixWithExistingComment.go ================================================ package newmath func TestFunction() { //noinspection SomeInspection Test("Sqrt(%v) = %v, want %v") } ================================================ FILE: testData/inspections/suppression/fix/suppressedNestedSelect.go ================================================ package main func _() { select { //noinspection GoUnresolvedReference case foo <- bar: select { case foo <- bar: break } } select { //noinspection GoUnresolvedReference case foo <- bar: select { case foo <- bar: break } } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFix-after-highlighting.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFix-after.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFix.go ================================================ package main func _() { switch 1 { case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFixWithExistingComment-after-highlighting.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFixWithExistingComment-after.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseAllSuppressionFixWithExistingComment.go ================================================ package main func _() { switch 1 { //noinspection BlaBlaBla case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFix-after-highlighting.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFix-after.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFix.go ================================================ package main func _() { switch 1 { case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFixWithExistingComment-after-highlighting.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFixWithExistingComment-after.go ================================================ package main func _() { switch 1 { //noinspection ALL case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/switchCaseSuppressionFixWithExistingComment.go ================================================ package main func _() { switch 1 { //noinspection BlaBlaBla case foo: println(foo) } } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFix-after-highlighting.go ================================================ package newmath //noinspection ALL var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFix-after.go ================================================ package newmath //noinspection ALL var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFix.go ================================================ package newmath var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath //noinspection ALL var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFixWithExistingComment-after.go ================================================ package newmath //noinspection ALL var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationAllSuppressionFixWithExistingComment.go ================================================ package newmath //noinspection SomeInspection var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFix-after-highlighting.go ================================================ package newmath //noinspection GoUnusedGlobalVariable var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFix-after.go ================================================ package newmath //noinspection GoUnusedGlobalVariable var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFix.go ================================================ package newmath var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFixWithExistingComment-after-highlighting.go ================================================ package newmath //noinspection SomeInspection,GoUnusedGlobalVariable var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFixWithExistingComment-after.go ================================================ package newmath //noinspection SomeInspection,GoUnusedGlobalVariable var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/suppression/fix/variableDeclarationSuppressionFixWithExistingComment.go ================================================ package newmath //noinspection SomeInspection var var1 = 1; func TestFunction() { } ================================================ FILE: testData/inspections/test-signatures/benchmark_test-after.go ================================================ package a import "testing" func Benchmark(b *testing.B) { } ================================================ FILE: testData/inspections/test-signatures/benchmark_test.go ================================================ package a import "testing" func Benchmark (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/exampleNonEmptySignature_test-after.go ================================================ package a import "testing" func ExampleFunction() { } ================================================ FILE: testData/inspections/test-signatures/exampleNonEmptySignature_test.go ================================================ package a import "testing" func ExampleFunction (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/exampleWithReturnValue_test-after.go ================================================ package a import . "testing" func ExampleA() { } ================================================ FILE: testData/inspections/test-signatures/exampleWithReturnValue_test.go ================================================ package a import . "testing" func ExampleA () int { } ================================================ FILE: testData/inspections/test-signatures/testLocalTestingImport_test-after.go ================================================ package a import . "testing" func TestLocalImport(t *T) { } ================================================ FILE: testData/inspections/test-signatures/testLocalTestingImport_test.go ================================================ package a import . "testing" func TestLocalImport (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/testMain_test-after.go ================================================ package a import "testing" func TestMain(m *testing.M) { } ================================================ FILE: testData/inspections/test-signatures/testMain_test.go ================================================ package a import "testing" func TestMain (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/testNoTestingImport_test-after.go ================================================ package a import "testing" func TestNoImportEmptySignature(t *testing.T) { } func TestNoImport (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/testNoTestingImport_test.go ================================================ package a func TestNoImportEmptySignature () { } func TestNoImport (t *testing.T) { } ================================================ FILE: testData/inspections/test-signatures/testWithReturnValue_test-after.go ================================================ package a import . "testing" func TestA(t *T) { } ================================================ FILE: testData/inspections/test-signatures/testWithReturnValue_test.go ================================================ package a import . "testing" func TestA (t *T) int { } ================================================ FILE: testData/inspections/test-signatures/testWrongTestingAlias_test-after.go ================================================ package a import t "testing" func TestSignature(t *t.T) { } ================================================ FILE: testData/inspections/test-signatures/testWrongTestingAlias_test.go ================================================ package a import t "testing" func TestSignature (t *testing.T) { } ================================================ FILE: testData/inspections/unused-label/deleteLabelFix-after.go ================================================ package main func _() { println("unused") } ================================================ FILE: testData/inspections/unused-label/deleteLabelFix.go ================================================ package main func _() { UnusedLabel: println("unused") } ================================================ FILE: testData/inspections/unused-label/renameToBlankFix-after.go ================================================ package main func _() { _: println("unused") } ================================================ FILE: testData/inspections/unused-label/renameToBlankFix.go ================================================ package main func _() { UnusedLabel: println("unused") } ================================================ FILE: testData/inspections/unused-label/simple.go ================================================ package main func _() { UnusedLabel: println("unused") UsedLabel: println("used") goto UsedLabel _: println("blank") } ================================================ FILE: testData/intentions/add-missing-body/simple-after.go ================================================ package main func _() int { } ================================================ FILE: testData/intentions/add-missing-body/simple.go ================================================ package main func _() int ================================================ FILE: testData/intentions/move-to-struct-initialization/anonymousField-after.go ================================================ package main type S struct { string } func main() { s := S{string: "bar"} _ = "foo" print(s.string) } ================================================ FILE: testData/intentions/move-to-struct-initialization/anonymousField.go ================================================ package main type S struct { string } func main() { s := S{} _, s.string = "foo", "bar" print(s.string) } ================================================ FILE: testData/intentions/move-to-struct-initialization/caretAtValue-after.go ================================================ package main type S struct { foo string } func main() { var b string s := S{foo: "bar"} b = "b" print(s.foo) print(b) } ================================================ FILE: testData/intentions/move-to-struct-initialization/caretAtValue.go ================================================ package main type S struct { foo string } func main() { var b string s := S{} s.foo, b = "bar", "b" print(s.foo) print(b) } ================================================ FILE: testData/intentions/move-to-struct-initialization/duplicateFields-after.go ================================================ package main type S struct { foo string bar string } func main() { s := S{bar: "bar"} s.foo, s.foo = "foo", "bar1" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/duplicateFields.go ================================================ package main type S struct { foo string bar string } func main() { s := S{} s.foo, s.foo, s.bar= "foo", "bar1", "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/existingDeclaration.go ================================================ package main type S struct { foo string } func main() { s := S{foo: "foo"} s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/existingField-after.go ================================================ package main type S struct { foo string b string } func main() { s := S{b: "a", foo: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/existingField.go ================================================ package main type S struct { foo string b string } func main() { s := S{b: "a"} s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/fieldExchange-after.go ================================================ package main type S struct { foo string } func main() { var b, s S s, b.foo = S{foo: "bar"}, "foo" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/fieldExchange.go ================================================ package main type S struct { foo string } func main() { var b, s S s, b.foo = S{}, "foo" s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/fieldExtractedFromParens-after.go ================================================ package main type S struct { foo string } func main() { s := S{foo: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/fieldExtractedFromParens.go ================================================ package main type S struct { foo string } func main() { s := S{} (s.foo) = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/invalidAssignment-after.go ================================================ package main type S struct { foo string bar string } func str2() (string, string) { return "foo", "bar" } func main() { var a string s := S{foo: str2(), bar: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/invalidAssignment.go ================================================ package main type S struct { foo string bar string } func str2() (string, string) { return "foo", "bar" } func main() { var a string s := S{} s.foo, s.bar = str2(), "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedFieldParens.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, (str) = S{}, "bar" s.foo, (s.bar) = "foo", ((str)) print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedVar-after.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, str = S{foo: "foo"}, "bar" s.bar = str print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedVar.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, str = S{}, "bar" s.foo, s.bar = "foo", str print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedVarBothParens.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, (str) = S{}, "bar" s.foo, s.bar = "foo", ((str)) print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedVarWrongCaret.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, str = S{}, "bar" s.foo, s.bar = "foo", str print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justAssignedVarWrongCaretWithParens.go ================================================ package main type S struct { foo string bar string } func main() { var s S var str string s, str = S{}, "bar" s.foo, s.bar = "foo", ((str)) print(s.foo) print(str) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justInitializedVar-after.go ================================================ package main type S struct { foo string bar string } func main() { s, str := S{foo: "foo"}, "bar" s.bar = str print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justInitializedVar.go ================================================ package main type S struct { foo string bar string } func main() { s, str := S{}, "bar" s.foo, s.bar = "foo", str print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/justInitializedVarWrongCaret.go ================================================ package main type S struct { foo string bar string } func main() { s, str := S{}, "bar" s.foo, s.bar = "foo", str print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multiReturnFunction.go ================================================ package main type S struct { foo int bar int } func int2() (int, int) { return 1, 2 } func main() { s := S{} s.foo, s.bar= int2() print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsLeftmost-after.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{foo: "bar"} b, a = "b", "a" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsLeftmost.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{} s.foo, b, a = "bar", "b", "a" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsMiddle-after.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{foo: "bar"} a, b = "a", "c" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsMiddle.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{} a, s.foo, b = "a", "bar", "c" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsRightmost-after.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{foo: "bar"} a, b = "a", "b" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleAssignmentsRightmost.go ================================================ package main type S struct { foo string } func main() { var b, a string s := S{} a, b, s.foo = "a", "b", "bar" print(s.foo) print(b) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFields-after.go ================================================ package main type S struct { foo string bar string } type B struct { x int } func main() { s, b := S{foo: "foo", bar: "bar"}, B{} b.x = 3 print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFields.go ================================================ package main type S struct { foo string bar string } type B struct { x int } func main() { s, b := S{}, B{} s.foo, b.x, s.bar= "foo", 3, "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFieldsPartlyAssigned-after.go ================================================ package main type S struct { foo string bar string } func main() { s := S{foo: "oof", bar: "bar"} s.foo = "foo" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFieldsPartlyAssigned.go ================================================ package main type S struct { foo string bar string } func main() { s := S{foo: "oof"} s.foo, s.bar = "foo", "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFieldsSameStructureCaretAtValue-after.go ================================================ package main type S struct { foo string bar string } func main() { var a int s := S{foo: "foo", bar: "bar"} a = 3 print(s.foo) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/multipleFieldsSameStructureCaretAtValue.go ================================================ package main type S struct { foo string bar string } func main() { var a int s := S{} s.foo, a, s.bar = "foo", 3, "bar" print(s.foo) print(a) } ================================================ FILE: testData/intentions/move-to-struct-initialization/notExistingField.go ================================================ package main type S struct { foo string } func main() { s := S{} s.x = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/oneLineFieldDeclaration-after.go ================================================ package main type S struct { bar, foo string } func main() { s := S{foo: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/oneLineFieldDeclaration.go ================================================ package main type S struct { bar, foo string } func main() { s := S{} s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/simple-after.go ================================================ package main type S struct { foo string } func main() { s := S{foo: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/simple.go ================================================ package main type S struct { foo string } func main() { s := S{} s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/structAssignment-after.go ================================================ package main type S struct { foo string } func main() { var s S s = S{foo: "bar"} print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/structAssignment.go ================================================ package main type S struct { foo string } func main() { var s S s = S{} s.foo = "bar" print(s.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/structAssignmentMultipleAssignee-after.go ================================================ package main type S struct { foo string } func main() { var s S var a, b string a, s, b = "a", S{foo: "bar"}, "b" print(s.foo) print(a) print(b) } ================================================ FILE: testData/intentions/move-to-struct-initialization/structAssignmentMultipleAssignee.go ================================================ package main type S struct { foo string } func main() { var s S var a, b string a, s, b = "a", S{}, "b" s.foo = "bar" print(s.foo) print(a) print(b) } ================================================ FILE: testData/intentions/move-to-struct-initialization/twoSameStructures-after.go ================================================ package main type S struct { foo string } func main() { s, b := S{}, S{foo: "foo"} s.foo = "bar" print(s.foo) print(b.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/twoSameStructures.go ================================================ package main type S struct { foo string } func main() { s, b := S{}, S{} s.foo, b.foo = "bar", "foo" print(s.foo) print(b.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/twoSameStructuresAssignment-after.go ================================================ package main type S struct { foo string } func main() { var s, b S s, b = S{}, S{foo: "foo"} s.foo = "bar" print(s.foo) print(b.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/twoSameStructuresAssignment.go ================================================ package main type S struct { foo string } func main() { var s, b S s, b = S{}, S{} s.foo, b.foo = "bar", "foo" print(s.foo) print(b.foo) } ================================================ FILE: testData/intentions/move-to-struct-initialization/withParens-after.go ================================================ package main type S struct { string } func main() { s := S{string: "bar"} (_) = "foo" print(s.string) } ================================================ FILE: testData/intentions/move-to-struct-initialization/withParens.go ================================================ package main type S struct { string } func main() { s := S{} (_), ((s.string)) = "foo", "bar" print(s.string) } ================================================ FILE: testData/intentions/move-to-struct-initialization/wrongStruct.go ================================================ package main type S struct { foo string } type B struct { bar string } func main() { var s S b := B{} s.foo = "bar" print(b.foo) } ================================================ FILE: testData/lexer/basicTypes.go ================================================ var ( ToBe bool = false MaxInt uint64 = 1<<64 - 1 z complex128 = cmplx.Sqrt(-5 + 12i) ) ================================================ FILE: testData/lexer/basicTypes.txt ================================================ var ('var') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('ToBe') GO_WHITESPACE (' ') identifier ('bool') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('false') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('MaxInt') GO_WHITESPACE (' ') identifier ('uint64') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') int ('1') << ('<<') int ('64') GO_WHITESPACE (' ') - ('-') GO_WHITESPACE (' ') int ('1') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('z') GO_WHITESPACE (' ') identifier ('complex128') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('cmplx') . ('.') identifier ('Sqrt') ( ('(') - ('-') int ('5') GO_WHITESPACE (' ') + ('+') GO_WHITESPACE (' ') decimali ('12i') ) (')') ('') GO_WS_NEW_LINES ('\n') ) (')') ================================================ FILE: testData/lexer/constants.go ================================================ const Pi = 3.14 const ( Big = 1 << 100 Small = Big >> 99 ) ================================================ FILE: testData/lexer/constants.txt ================================================ const ('const') GO_WHITESPACE (' ') identifier ('Pi') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') float ('3.14') ('') GO_WS_NEW_LINES ('\n\n') const ('const') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('Big') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') int ('1') GO_WHITESPACE (' ') << ('<<') GO_WHITESPACE (' ') int ('100') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('Small') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('Big') GO_WHITESPACE (' ') >> ('>>') GO_WHITESPACE (' ') int ('99') ('') GO_WS_NEW_LINES ('\n') ) (')') ================================================ FILE: testData/lexer/couldNotMatch.go ================================================ // errorcheck // Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package p const ( _ = iota _ // ERROR "illegal character|invalid character" _ // ERROR "illegal character|invalid character" _ // ERROR "illegal character|invalid character" _ // ERROR "illegal character|invalid character" ) ================================================ FILE: testData/lexer/couldNotMatch.txt ================================================ GO_LINE_COMMENT ('// errorcheck') GO_WS_NEW_LINES ('\n\n') GO_LINE_COMMENT ('// Copyright 2012 The Go Authors. All rights reserved.') GO_WS_NEW_LINES ('\n') GO_LINE_COMMENT ('// Use of this source code is governed by a BSD-style') GO_WS_NEW_LINES ('\n') GO_LINE_COMMENT ('// license that can be found in the LICENSE file.') GO_WS_NEW_LINES ('\n\n') package ('package') GO_WHITESPACE (' ') identifier ('p') ('') GO_WS_NEW_LINES ('\n\n') const ('const') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('_') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('iota') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('_') BAD_CHARACTER ('') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// ERROR "illegal character|invalid character"') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('_') BAD_CHARACTER ('') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// ERROR "illegal character|invalid character"') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('_') ('') GO_WS_NEW_LINES (' ') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// ERROR "illegal character|invalid character"') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('_') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// ERROR "illegal character|invalid character"') ('') GO_WS_NEW_LINES ('\n') ) (')') ================================================ FILE: testData/lexer/escapedQuote.go ================================================ package newmath import "testing" const c = '\a' const c = '\\' const c = '\' const c = '\ const c = ' const c = '\n const c = 'n const c = "\n const c = "\ const c = "\n const c = "n const c = " 'a' 'ä' '本' '\t' '\000' '\007' '\377' '\x07' '\xff' '\u12e4' '\U00101234' '\'' // rune literal containing single quote character 'aa' // illegal: too many characters '\xa' // illegal: too few hexadecimal digits '\0' // illegal: too few octal digits '\uDFFF' // illegal: surrogate half '\U00110000' // illegal: invalid Unicode code point ================================================ FILE: testData/lexer/escapedQuote.txt ================================================ package ('package') GO_WHITESPACE (' ') identifier ('newmath') ('') GO_WS_NEW_LINES ('\n\n') import ('import') GO_WHITESPACE (' ') string ('"testing"') ('') GO_WS_NEW_LINES ('\n\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') char (''\a'') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') char (''\\'') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') BAD_CHARACTER (''\'') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') BAD_CHARACTER (''') BAD_CHARACTER ('\') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') char (''\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') char (''\n') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') char (''n') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') string ('"\n') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') string ('"') BAD_CHARACTER ('\') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') string ('"\n') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') string ('"n') ('') GO_WS_NEW_LINES ('\n') const ('const') GO_WHITESPACE (' ') identifier ('c') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') string ('"') ('') GO_WS_NEW_LINES ('\n\n') char (''a'') ('') GO_WS_NEW_LINES ('\n') char (''ä'') ('') GO_WS_NEW_LINES ('\n') char (''本'') ('') GO_WS_NEW_LINES ('\n') char (''\t'') ('') GO_WS_NEW_LINES ('\n') char (''\000'') ('') GO_WS_NEW_LINES ('\n') char (''\007'') ('') GO_WS_NEW_LINES ('\n') char (''\377'') ('') GO_WS_NEW_LINES ('\n') char (''\x07'') ('') GO_WS_NEW_LINES ('\n') char (''\xff'') ('') GO_WS_NEW_LINES ('\n') char (''\u12e4'') ('') GO_WS_NEW_LINES ('\n') char (''\U00101234'') ('') GO_WS_NEW_LINES ('\n\n') char (''\''') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// rune literal containing single quote character') ('') GO_WS_NEW_LINES ('\n') char (''a') identifier ('a') char ('' ') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// illegal: too many characters') ('') GO_WS_NEW_LINES ('\n') BAD_CHARACTER (''') BAD_CHARACTER ('\') identifier ('xa') char ('' ') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// illegal: too few hexadecimal digits') ('') GO_WS_NEW_LINES ('\n') BAD_CHARACTER (''') BAD_CHARACTER ('\') int ('0') char ('' ') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// illegal: too few octal digits') ('') GO_WS_NEW_LINES ('\n') char (''\uDFFF'') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// illegal: surrogate half') ('') GO_WS_NEW_LINES ('\n') char (''\U00110000'') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// illegal: invalid Unicode code point') ================================================ FILE: testData/lexer/for.go ================================================ func main() { sum := 0 for i := 0; i < 10; i++ { sum += i } for ; sum < 1000; { sum += sum } for sum < 1000 { sum += sum } for { fmt.Println(sum) break } } ================================================ FILE: testData/lexer/for.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') int ('0') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('i') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') int ('0') ; (';') GO_WHITESPACE (' ') identifier ('i') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') int ('10') ; (';') GO_WHITESPACE (' ') identifier ('i') ++ ('++') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') += ('+=') GO_WHITESPACE (' ') identifier ('i') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') ; (';') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') int ('1000') ; (';') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') += ('+=') GO_WHITESPACE (' ') identifier ('sum') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') int ('1000') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') += ('+=') GO_WHITESPACE (' ') identifier ('sum') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('sum') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') break ('break') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/functionArguments.go ================================================ func add(x int, y int) int { return x + y } func add(x, y int) int { return x + y } ================================================ FILE: testData/lexer/functionArguments.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('add') ( ('(') identifier ('x') GO_WHITESPACE (' ') identifier ('int') , (',') GO_WHITESPACE (' ') identifier ('y') GO_WHITESPACE (' ') identifier ('int') ) (')') GO_WHITESPACE (' ') identifier ('int') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('x') GO_WHITESPACE (' ') + ('+') GO_WHITESPACE (' ') identifier ('y') ('') GO_WS_NEW_LINES ('\n') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('add') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('y') GO_WHITESPACE (' ') identifier ('int') ) (')') GO_WHITESPACE (' ') identifier ('int') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('x') GO_WHITESPACE (' ') + ('+') GO_WHITESPACE (' ') identifier ('y') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/helloWorld.go ================================================ package main import ( "fmt" "net" "os" "time" ) func main() { fmt.Println("Welcome to the playground!") fmt.Println("The time is", time.Now()) fmt.Println("And if you try to open a file:") fmt.Println(os.Open("filename")) fmt.Println("Or access the network:") fmt.Println(net.Dial("tcp", "google.com")) } ================================================ FILE: testData/lexer/helloWorld.txt ================================================ package ('package') GO_WHITESPACE (' ') identifier ('main') ('') GO_WS_NEW_LINES ('\n\n') import ('import') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"fmt"') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"net"') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"os"') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"time"') ('') GO_WS_NEW_LINES ('\n') ) (')') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"Welcome to the playground!"') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"The time is"') , (',') GO_WHITESPACE (' ') identifier ('time') . ('.') identifier ('Now') ( ('(') ) (')') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"And if you try to open a file:"') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('os') . ('.') identifier ('Open') ( ('(') string ('"filename"') ) (')') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"Or access the network:"') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('net') . ('.') identifier ('Dial') ( ('(') string ('"tcp"') , (',') GO_WHITESPACE (' ') string ('"google.com"') ) (')') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/if.go ================================================ func sqrt(x float64) string { if x < 0 { return sqrt(-x) + "i" } return fmt.Sprint(math.Sqrt(x)) } func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } return lim } func powElse(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %g\n", v, lim) } // can't use v here, though return lim } ================================================ FILE: testData/lexer/if.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('sqrt') ( ('(') identifier ('x') GO_WHITESPACE (' ') identifier ('float64') ) (')') GO_WHITESPACE (' ') identifier ('string') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') if ('if') GO_WHITESPACE (' ') identifier ('x') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') int ('0') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('sqrt') ( ('(') - ('-') identifier ('x') ) (')') GO_WHITESPACE (' ') + ('+') GO_WHITESPACE (' ') string ('"i"') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Sprint') ( ('(') identifier ('math') . ('.') identifier ('Sqrt') ( ('(') identifier ('x') ) (')') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('pow') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('n') , (',') GO_WHITESPACE (' ') identifier ('lim') GO_WHITESPACE (' ') identifier ('float64') ) (')') GO_WHITESPACE (' ') identifier ('float64') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') if ('if') GO_WHITESPACE (' ') identifier ('v') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('math') . ('.') identifier ('Pow') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('n') ) (')') ; (';') GO_WHITESPACE (' ') identifier ('v') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') identifier ('lim') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('v') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('lim') ('') GO_WS_NEW_LINES ('\n') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('powElse') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('n') , (',') GO_WHITESPACE (' ') identifier ('lim') GO_WHITESPACE (' ') identifier ('float64') ) (')') GO_WHITESPACE (' ') identifier ('float64') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') if ('if') GO_WHITESPACE (' ') identifier ('v') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('math') . ('.') identifier ('Pow') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('n') ) (')') ; (';') GO_WHITESPACE (' ') identifier ('v') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') identifier ('lim') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('v') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') GO_WHITESPACE (' ') else ('else') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Printf') ( ('(') string ('"%g >= %g\n"') , (',') GO_WHITESPACE (' ') identifier ('v') , (',') GO_WHITESPACE (' ') identifier ('lim') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// can't use v here, though') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('lim') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/imports.go ================================================ import ( "fmt" "math" ) import "fmt" import "math" ================================================ FILE: testData/lexer/imports.txt ================================================ import ('import') GO_WHITESPACE (' ') ( ('(') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"fmt"') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') string ('"math"') ('') GO_WS_NEW_LINES ('\n') ) (')') ('') GO_WS_NEW_LINES ('\n\n') import ('import') GO_WHITESPACE (' ') string ('"fmt"') GO_WHITESPACE (' ') ('') GO_WS_NEW_LINES ('\n') import ('import') GO_WHITESPACE (' ') string ('"math"') ================================================ FILE: testData/lexer/multipleResult.go ================================================ func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("hello", "world") fmt.Println(a, b) } ================================================ FILE: testData/lexer/multipleResult.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('swap') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('y') GO_WHITESPACE (' ') identifier ('string') ) (')') GO_WHITESPACE (' ') ( ('(') identifier ('string') , (',') GO_WHITESPACE (' ') identifier ('string') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') GO_WHITESPACE (' ') identifier ('y') , (',') GO_WHITESPACE (' ') identifier ('x') ('') GO_WS_NEW_LINES ('\n') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('a') , (',') GO_WHITESPACE (' ') identifier ('b') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('swap') ( ('(') string ('"hello"') , (',') GO_WHITESPACE (' ') string ('"world"') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('a') , (',') GO_WHITESPACE (' ') identifier ('b') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/namedResult.go ================================================ func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } ================================================ FILE: testData/lexer/namedResult.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('split') ( ('(') identifier ('sum') GO_WHITESPACE (' ') identifier ('int') ) (')') GO_WHITESPACE (' ') ( ('(') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('y') GO_WHITESPACE (' ') identifier ('int') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('x') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') * ('*') GO_WHITESPACE (' ') int ('4') GO_WHITESPACE (' ') / ('/') GO_WHITESPACE (' ') int ('9') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('y') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('sum') GO_WHITESPACE (' ') - ('-') GO_WHITESPACE (' ') identifier ('x') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') return ('return') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/pointers.go ================================================ func main() { p := Vertex{1, 2} q := &p q.X = 1e9 fmt.Println(p) } ================================================ FILE: testData/lexer/pointers.txt ================================================ func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('p') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('Vertex') { ('{') int ('1') , (',') GO_WHITESPACE (' ') int ('2') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('q') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') & ('&') identifier ('p') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('q') . ('.') identifier ('X') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') float ('1e9') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('p') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/rangeFor.go ================================================ package main import "fmt" var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} func main() { for i, v := range pow { fmt.Printf("2**%d = %d\n", i, v) } for i := range pow { pow[i] = 1 << uint(i) } for _, value := range pow { fmt.Printf("%d\n", value) } } ================================================ FILE: testData/lexer/rangeFor.txt ================================================ package ('package') GO_WHITESPACE (' ') identifier ('main') ('') GO_WS_NEW_LINES ('\n\n') import ('import') GO_WHITESPACE (' ') string ('"fmt"') ('') GO_WS_NEW_LINES ('\n\n') var ('var') GO_WHITESPACE (' ') identifier ('pow') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') [ ('[') ] (']') identifier ('int') { ('{') int ('1') , (',') GO_WHITESPACE (' ') int ('2') , (',') GO_WHITESPACE (' ') int ('4') , (',') GO_WHITESPACE (' ') int ('8') , (',') GO_WHITESPACE (' ') int ('16') , (',') GO_WHITESPACE (' ') int ('32') , (',') GO_WHITESPACE (' ') int ('64') , (',') GO_WHITESPACE (' ') int ('128') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('i') , (',') GO_WHITESPACE (' ') identifier ('v') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') range ('range') GO_WHITESPACE (' ') identifier ('pow') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Printf') ( ('(') string ('"2**%d = %d\n"') , (',') GO_WHITESPACE (' ') identifier ('i') , (',') GO_WHITESPACE (' ') identifier ('v') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('i') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') range ('range') GO_WHITESPACE (' ') identifier ('pow') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('pow') [ ('[') identifier ('i') ] (']') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') int ('1') GO_WHITESPACE (' ') << ('<<') GO_WHITESPACE (' ') identifier ('uint') ( ('(') identifier ('i') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('_') , (',') GO_WHITESPACE (' ') identifier ('value') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') range ('range') GO_WHITESPACE (' ') identifier ('pow') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Printf') ( ('(') string ('"%d\n"') , (',') GO_WHITESPACE (' ') identifier ('value') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/slices.go ================================================ package main import "fmt" func main() { p := []int{2, 3, 5, 7, 11, 13} fmt.Println("p ==", p) for i := 0; i < len(p); i++ { fmt.Printf("p[%d] == %d\n", i, p[i]) } fmt.Println("p[1:4] ==", p[1:4]) // missing low index implies 0 fmt.Println("p[:3] ==", p[:3]) // missing high index implies len(s) fmt.Println("p[4:] ==", p[4:]) } ================================================ FILE: testData/lexer/slices.txt ================================================ package ('package') GO_WHITESPACE (' ') identifier ('main') ('') GO_WS_NEW_LINES ('\n\n') import ('import') GO_WHITESPACE (' ') string ('"fmt"') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('p') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') [ ('[') ] (']') identifier ('int') { ('{') int ('2') , (',') GO_WHITESPACE (' ') int ('3') , (',') GO_WHITESPACE (' ') int ('5') , (',') GO_WHITESPACE (' ') int ('7') , (',') GO_WHITESPACE (' ') int ('11') , (',') GO_WHITESPACE (' ') int ('13') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"p =="') , (',') GO_WHITESPACE (' ') identifier ('p') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') for ('for') GO_WHITESPACE (' ') identifier ('i') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') int ('0') ; (';') GO_WHITESPACE (' ') identifier ('i') GO_WHITESPACE (' ') < ('<') GO_WHITESPACE (' ') identifier ('len') ( ('(') identifier ('p') ) (')') ; (';') GO_WHITESPACE (' ') identifier ('i') ++ ('++') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Printf') ( ('(') string ('"p[%d] == %d\n"') , (',') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('i') , (',') GO_WHITESPACE (' ') identifier ('p') [ ('[') identifier ('i') ] (']') ) (')') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"p[1:4] =="') , (',') GO_WHITESPACE (' ') identifier ('p') [ ('[') int ('1') : (':') int ('4') ] (']') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// missing low index implies 0') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"p[:3] =="') , (',') GO_WHITESPACE (' ') identifier ('p') [ ('[') : (':') int ('3') ] (']') ) (')') ('') GO_WS_NEW_LINES ('\n\n') GO_WHITESPACE (' ') GO_LINE_COMMENT ('// missing high index implies len(s)') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') string ('"p[4:] =="') , (',') GO_WHITESPACE (' ') identifier ('p') [ ('[') int ('4') : (':') ] (']') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/structs.go ================================================ type Vertex struct { X int Y int } func main() { p := Vertex{1, 2} q := &p q.X = 1e9 fmt.Println(p) } ================================================ FILE: testData/lexer/structs.txt ================================================ type ('type') GO_WHITESPACE (' ') identifier ('Vertex') GO_WHITESPACE (' ') struct ('struct') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('X') GO_WHITESPACE (' ') identifier ('int') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('Y') GO_WHITESPACE (' ') identifier ('int') ('') GO_WS_NEW_LINES ('\n') } ('}') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('p') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('Vertex') { ('{') int ('1') , (',') GO_WHITESPACE (' ') int ('2') } ('}') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('q') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') & ('&') identifier ('p') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('q') . ('.') identifier ('X') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') float ('1e9') ('') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('fmt') . ('.') identifier ('Println') ( ('(') identifier ('p') ) (')') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/lexer/utf16.go ================================================ 𝓐 ================================================ FILE: testData/lexer/utf16.txt ================================================ identifier ('𝓐') ================================================ FILE: testData/lexer/variables.go ================================================ var x, y, z int var c, python, java bool var x, y, z int = 1, 2, 3 var c, python, java = true, false, "no!" func main() { c, python, java := true, false, "no!" } ================================================ FILE: testData/lexer/variables.txt ================================================ var ('var') GO_WHITESPACE (' ') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('y') , (',') GO_WHITESPACE (' ') identifier ('z') GO_WHITESPACE (' ') identifier ('int') ('') GO_WS_NEW_LINES ('\n') var ('var') GO_WHITESPACE (' ') identifier ('c') , (',') GO_WHITESPACE (' ') identifier ('python') , (',') GO_WHITESPACE (' ') identifier ('java') GO_WHITESPACE (' ') identifier ('bool') ('') GO_WS_NEW_LINES ('\n\n') var ('var') GO_WHITESPACE (' ') identifier ('x') , (',') GO_WHITESPACE (' ') identifier ('y') , (',') GO_WHITESPACE (' ') identifier ('z') GO_WHITESPACE (' ') identifier ('int') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') int ('1') , (',') GO_WHITESPACE (' ') int ('2') , (',') GO_WHITESPACE (' ') int ('3') ('') GO_WS_NEW_LINES ('\n') var ('var') GO_WHITESPACE (' ') identifier ('c') , (',') GO_WHITESPACE (' ') identifier ('python') , (',') GO_WHITESPACE (' ') identifier ('java') GO_WHITESPACE (' ') = ('=') GO_WHITESPACE (' ') identifier ('true') , (',') GO_WHITESPACE (' ') identifier ('false') , (',') GO_WHITESPACE (' ') string ('"no!"') ('') GO_WS_NEW_LINES ('\n\n') func ('func') GO_WHITESPACE (' ') identifier ('main') ( ('(') ) (')') GO_WHITESPACE (' ') { ('{') GO_WS_NEW_LINES ('\n') GO_WHITESPACE (' ') identifier ('c') , (',') GO_WHITESPACE (' ') identifier ('python') , (',') GO_WHITESPACE (' ') identifier ('java') GO_WHITESPACE (' ') := (':=') GO_WHITESPACE (' ') identifier ('true') , (',') GO_WHITESPACE (' ') identifier ('false') , (',') GO_WHITESPACE (' ') string ('"no!"') ('') GO_WS_NEW_LINES ('\n') } ('}') ================================================ FILE: testData/marker/Go.go ================================================ package main func recv(value int, ch chan bool) { if value < 0 { ch <- true return } go recv(value - 1, ch) } ================================================ FILE: testData/marker/Recursive.go ================================================ package main func Recursive(number int) int { if number == 1 { return number } return number + Recursive(number-1) } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/bufio/scan.go ================================================ // Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bufio import ( "bytes" "errors" "io" "unicode/utf8" ) // Scanner provides a convenient interface for reading data such as // a file of newline-delimited lines of text. Successive calls to // the Scan method will step through the 'tokens' of a file, skipping // the bytes between the tokens. The specification of a token is // defined by a split function of type SplitFunc; the default split // function breaks the input into lines with line termination stripped. Split // functions are defined in this package for scanning a file into // lines, bytes, UTF-8-encoded runes, and space-delimited words. The // client may instead provide a custom split function. // // Scanning stops unrecoverably at EOF, the first I/O error, or a token too // large to fit in the buffer. When a scan stops, the reader may have // advanced arbitrarily far past the last token. Programs that need more // control over error handling or large tokens, or must run sequential scans // on a reader, should use bufio.Reader instead. // type Scanner struct { r io.Reader // The reader provided by the client. split SplitFunc // The function to split the tokens. maxTokenSize int // Maximum size of a token; modified by tests. token []byte // Last token returned by split. buf []byte // Buffer used as argument to split. start int // First non-processed byte in buf. end int // End of data in buf. err error // Sticky error. empties int // Count of successive empty tokens. } // SplitFunc is the signature of the split function used to tokenize the // input. The arguments are an initial substring of the remaining unprocessed // data and a flag, atEOF, that reports whether the Reader has no more data // to give. The return values are the number of bytes to advance the input // and the next token to return to the user, plus an error, if any. If the // data does not yet hold a complete token, for instance if it has no newline // while scanning lines, SplitFunc can return (0, nil, nil) to signal the // Scanner to read more data into the slice and try again with a longer slice // starting at the same point in the input. // // If the returned error is non-nil, scanning stops and the error // is returned to the client. // // The function is never called with an empty data slice unless atEOF // is true. If atEOF is true, however, data may be non-empty and, // as always, holds unprocessed text. type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error) // Errors returned by Scanner. var ( ErrTooLong = errors.New("bufio.Scanner: token too long") ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count") ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input") ) const ( // MaxScanTokenSize is the maximum size used to buffer a token. // The actual maximum token size may be smaller as the buffer // may need to include, for instance, a newline. MaxScanTokenSize = 64 * 1024 ) // NewScanner returns a new Scanner to read from r. // The split function defaults to ScanLines. func NewScanner(r io.Reader) *Scanner { return &Scanner{ r: r, split: ScanLines, maxTokenSize: MaxScanTokenSize, buf: make([]byte, 4096), // Plausible starting size; needn't be large. } } // Err returns the first non-EOF error that was encountered by the Scanner. func (s *Scanner) Err() error { if s.err == io.EOF { return nil } return s.err } // Bytes returns the most recent token generated by a call to Scan. // The underlying array may point to data that will be overwritten // by a subsequent call to Scan. It does no allocation. func (s *Scanner) Bytes() []byte { return s.token } // Text returns the most recent token generated by a call to Scan // as a newly allocated string holding its bytes. func (s *Scanner) Text() string { return string(s.token) } // Scan advances the Scanner to the next token, which will then be // available through the Bytes or Text method. It returns false when the // scan stops, either by reaching the end of the input or an error. // After Scan returns false, the Err method will return any error that // occurred during scanning, except that if it was io.EOF, Err // will return nil. // Scan panics if the split function returns 100 empty tokens without // advancing the input. This is a common error mode for scanners. func (s *Scanner) Scan() bool { // Loop until we have a token. for { // See if we can get a token with what we already have. // If we've run out of data but have an error, give the split function // a chance to recover any remaining, possibly empty token. if s.end > s.start || s.err != nil { advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil) if err != nil { s.setErr(err) return false } if !s.advance(advance) { return false } s.token = token if token != nil { if s.err == nil || advance > 0 { s.empties = 0 } else { // Returning tokens not advancing input at EOF. s.empties++ if s.empties > 100 { panic("bufio.Scan: 100 empty tokens without progressing") } } return true } } // We cannot generate a token with what we are holding. // If we've already hit EOF or an I/O error, we are done. if s.err != nil { // Shut it down. s.start = 0 s.end = 0 return false } // Must read more data. // First, shift data to beginning of buffer if there's lots of empty space // or space is needed. if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) { copy(s.buf, s.buf[s.start:s.end]) s.end -= s.start s.start = 0 } // Is the buffer full? If so, resize. if s.end == len(s.buf) { if len(s.buf) >= s.maxTokenSize { s.setErr(ErrTooLong) return false } newSize := len(s.buf) * 2 if newSize > s.maxTokenSize { newSize = s.maxTokenSize } newBuf := make([]byte, newSize) copy(newBuf, s.buf[s.start:s.end]) s.buf = newBuf s.end -= s.start s.start = 0 continue } // Finally we can read some input. Make sure we don't get stuck with // a misbehaving Reader. Officially we don't need to do this, but let's // be extra careful: Scanner is for safe, simple jobs. for loop := 0; ; { n, err := s.r.Read(s.buf[s.end:len(s.buf)]) s.end += n if err != nil { s.setErr(err) break } if n > 0 { s.empties = 0 break } loop++ if loop > maxConsecutiveEmptyReads { s.setErr(io.ErrNoProgress) break } } } } // advance consumes n bytes of the buffer. It reports whether the advance was legal. func (s *Scanner) advance(n int) bool { if n < 0 { s.setErr(ErrNegativeAdvance) return false } if n > s.end-s.start { s.setErr(ErrAdvanceTooFar) return false } s.start += n return true } // setErr records the first error encountered. func (s *Scanner) setErr(err error) { if s.err == nil || s.err == io.EOF { s.err = err } } // Split sets the split function for the Scanner. If called, it must be // called before Scan. The default split function is ScanLines. func (s *Scanner) Split(split SplitFunc) { s.split = split } // Split functions // ScanBytes is a split function for a Scanner that returns each byte as a token. func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } return 1, data[0:1], nil } var errorRune = []byte(string(utf8.RuneError)) // ScanRunes is a split function for a Scanner that returns each // UTF-8-encoded rune as a token. The sequence of runes returned is // equivalent to that from a range loop over the input as a string, which // means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". // Because of the Scan interface, this makes it impossible for the client to // distinguish correctly encoded replacement runes from encoding errors. func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } // Fast path 1: ASCII. if data[0] < utf8.RuneSelf { return 1, data[0:1], nil } // Fast path 2: Correct UTF-8 decode without error. _, width := utf8.DecodeRune(data) if width > 1 { // It's a valid encoding. Width cannot be one for a correctly encoded // non-ASCII rune. return width, data[0:width], nil } // We know it's an error: we have width==1 and implicitly r==utf8.RuneError. // Is the error because there wasn't a full rune to be decoded? // FullRune distinguishes correctly between erroneous and incomplete encodings. if !atEOF && !utf8.FullRune(data) { // Incomplete; get more bytes. return 0, nil, nil } // We have a real UTF-8 encoding error. Return a properly encoded error rune // but advance only one byte. This matches the behavior of a range loop over // an incorrectly encoded string. return 1, errorRune, nil } // dropCR drops a terminal \r from the data. func dropCR(data []byte) []byte { if len(data) > 0 && data[len(data)-1] == '\r' { return data[0 : len(data)-1] } return data } // ScanLines is a split function for a Scanner that returns each line of // text, stripped of any trailing end-of-line marker. The returned line may // be empty. The end-of-line marker is one optional carriage return followed // by one mandatory newline. In regular expression notation, it is `\r?\n`. // The last non-empty line of input will be returned even if it has no // newline. func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } if i := bytes.IndexByte(data, '\n'); i >= 0 { // We have a full newline-terminated line. return i + 1, dropCR(data[0:i]), nil } // If we're at EOF, we have a final, non-terminated line. Return it. if atEOF { return len(data), dropCR(data), nil } // Request more data. return 0, nil, nil } // isSpace reports whether the character is a Unicode white space character. // We avoid dependency on the unicode package, but check validity of the implementation // in the tests. func isSpace(r rune) bool { if r <= '\u00FF' { // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs. switch r { case ' ', '\t', '\n', '\v', '\f', '\r': return true case '\u0085', '\u00A0': return true } return false } // High-valued ones. if '\u2000' <= r && r <= '\u200a' { return true } switch r { case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000': return true } return false } // ScanWords is a split function for a Scanner that returns each // space-separated word of text, with surrounding spaces deleted. It will // never return an empty string. The definition of space is set by // unicode.IsSpace. func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) { // Skip leading spaces. start := 0 for width := 0; start < len(data); start += width { var r rune r, width = utf8.DecodeRune(data[start:]) if !isSpace(r) { break } } // Scan until space, marking end of word. for width, i := 0, start; i < len(data); i += width { var r rune r, width = utf8.DecodeRune(data[i:]) if isSpace(r) { return i + width, data[start:i], nil } } // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. if atEOF && len(data) > start { return len(data), data[start:], nil } // Request more data. return start, nil, nil } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/builtin/builtin.go ================================================ // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers. */ package builtin // bool is the set of boolean values, true and false. type bool bool // true and false are the two untyped boolean values. const ( true = 0 == 0 // Untyped bool. false = 0 != 0 // Untyped bool. ) // uint8 is the set of all unsigned 8-bit integers. // Range: 0 through 255. type uint8 uint8 // uint16 is the set of all unsigned 16-bit integers. // Range: 0 through 65535. type uint16 uint16 // uint32 is the set of all unsigned 32-bit integers. // Range: 0 through 4294967295. type uint32 uint32 // uint64 is the set of all unsigned 64-bit integers. // Range: 0 through 18446744073709551615. type uint64 uint64 // int8 is the set of all signed 8-bit integers. // Range: -128 through 127. type int8 int8 // int16 is the set of all signed 16-bit integers. // Range: -32768 through 32767. type int16 int16 // int32 is the set of all signed 32-bit integers. // Range: -2147483648 through 2147483647. type int32 int32 // int64 is the set of all signed 64-bit integers. // Range: -9223372036854775808 through 9223372036854775807. type int64 int64 // float32 is the set of all IEEE-754 32-bit floating-point numbers. type float32 float32 // float64 is the set of all IEEE-754 64-bit floating-point numbers. type float64 float64 // complex64 is the set of all complex numbers with float32 real and // imaginary parts. type complex64 complex64 // complex128 is the set of all complex numbers with float64 real and // imaginary parts. type complex128 complex128 // string is the set of all strings of 8-bit bytes, conventionally but not // necessarily representing UTF-8-encoded text. A string may be empty, but // not nil. Values of string type are immutable. type string string // int is a signed integer type that is at least 32 bits in size. It is a // distinct type, however, and not an alias for, say, int32. type int int // uint is an unsigned integer type that is at least 32 bits in size. It is a // distinct type, however, and not an alias for, say, uint32. type uint uint // uintptr is an integer type that is large enough to hold the bit pattern of // any pointer. type uintptr uintptr // byte is an alias for uint8 and is equivalent to uint8 in all ways. It is // used, by convention, to distinguish byte values from 8-bit unsigned // integer values. type byte byte // rune is an alias for int32 and is equivalent to int32 in all ways. It is // used, by convention, to distinguish character values from integer values. type rune rune // iota is a predeclared identifier representing the untyped integer ordinal // number of the current const specification in a (usually parenthesized) // const declaration. It is zero-indexed. const iota = 0 // Untyped int. // nil is a predeclared identifier representing the zero value for a // pointer, channel, func, interface, map, or slice type. var nil Type // Type must be a pointer, channel, func, interface, map, or slice type // Type is here for the purposes of documentation only. It is a stand-in // for any Go type, but represents the same type for any given function // invocation. type Type int // Type1 is here for the purposes of documentation only. It is a stand-in // for any Go type, but represents the same type for any given function // invocation. type Type1 int // IntegerType is here for the purposes of documentation only. It is a stand-in // for any integer type: int, uint, int8 etc. type IntegerType int // FloatType is here for the purposes of documentation only. It is a stand-in // for either float type: float32 or float64. type FloatType float32 // ComplexType is here for the purposes of documentation only. It is a // stand-in for either complex type: complex64 or complex128. type ComplexType complex64 // The append built-in function appends elements to the end of a slice. If // it has sufficient capacity, the destination is resliced to accommodate the // new elements. If it does not, a new underlying array will be allocated. // Append returns the updated slice. It is therefore necessary to store the // result of append, often in the variable holding the slice itself: // slice = append(slice, elem1, elem2) // slice = append(slice, anotherSlice...) // As a special case, it is legal to append a string to a byte slice, like this: // slice = append([]byte("hello "), "world"...) func append(slice []Type, elems ...Type) []Type // The copy built-in function copies elements from a source slice into a // destination slice. (As a special case, it also will copy bytes from a // string to a slice of bytes.) The source and destination may overlap. Copy // returns the number of elements copied, which will be the minimum of // len(src) and len(dst). func copy(dst, src []Type) int // The delete built-in function deletes the element with the specified key // (m[key]) from the map. If m is nil or there is no such element, delete // is a no-op. func delete(m map[Type]Type1, key Type) // The len built-in function returns the length of v, according to its type: // Array: the number of elements in v. // Pointer to array: the number of elements in *v (even if v is nil). // Slice, or map: the number of elements in v; if v is nil, len(v) is zero. // String: the number of bytes in v. // Channel: the number of elements queued (unread) in the channel buffer; // if v is nil, len(v) is zero. func len(v Type) int // The cap built-in function returns the capacity of v, according to its type: // Array: the number of elements in v (same as len(v)). // Pointer to array: the number of elements in *v (same as len(v)). // Slice: the maximum length the slice can reach when resliced; // if v is nil, cap(v) is zero. // Channel: the channel buffer capacity, in units of elements; // if v is nil, cap(v) is zero. func cap(v Type) int // The make built-in function allocates and initializes an object of type // slice, map, or chan (only). Like new, the first argument is a type, not a // value. Unlike new, make's return type is the same as the type of its // argument, not a pointer to it. The specification of the result depends on // the type: // Slice: The size specifies the length. The capacity of the slice is // equal to its length. A second integer argument may be provided to // specify a different capacity; it must be no smaller than the // length, so make([]int, 0, 10) allocates a slice of length 0 and // capacity 10. // Map: An initial allocation is made according to the size but the // resulting map has length 0. The size may be omitted, in which case // a small starting size is allocated. // Channel: The channel's buffer is initialized with the specified // buffer capacity. If zero, or the size is omitted, the channel is // unbuffered. func make(Type, size IntegerType) Type // The new built-in function allocates memory. The first argument is a type, // not a value, and the value returned is a pointer to a newly // allocated zero value of that type. func new(Type) *Type // The complex built-in function constructs a complex value from two // floating-point values. The real and imaginary parts must be of the same // size, either float32 or float64 (or assignable to them), and the return // value will be the corresponding complex type (complex64 for float32, // complex128 for float64). func complex(r, i FloatType) ComplexType // The real built-in function returns the real part of the complex number c. // The return value will be floating point type corresponding to the type of c. func real(c ComplexType) FloatType // The imag built-in function returns the imaginary part of the complex // number c. The return value will be floating point type corresponding to // the type of c. func imag(c ComplexType) FloatType // The close built-in function closes a channel, which must be either // bidirectional or send-only. It should be executed only by the sender, // never the receiver, and has the effect of shutting down the channel after // the last sent value is received. After the last value has been received // from a closed channel c, any receive from c will succeed without // blocking, returning the zero value for the channel element. The form // x, ok := <-c // will also set ok to false for a closed channel. func close(c chan<- Type) // The panic built-in function stops normal execution of the current // goroutine. When a function F calls panic, normal execution of F stops // immediately. Any functions whose execution was deferred by F are run in // the usual way, and then F returns to its caller. To the caller G, the // invocation of F then behaves like a call to panic, terminating G's // execution and running any deferred functions. This continues until all // functions in the executing goroutine have stopped, in reverse order. At // that point, the program is terminated and the error condition is reported, // including the value of the argument to panic. This termination sequence // is called panicking and can be controlled by the built-in function // recover. func panic(v interface{}) // The recover built-in function allows a program to manage behavior of a // panicking goroutine. Executing a call to recover inside a deferred // function (but not any function called by it) stops the panicking sequence // by restoring normal execution and retrieves the error value passed to the // call of panic. If recover is called outside the deferred function it will // not stop a panicking sequence. In this case, or when the goroutine is not // panicking, or if the argument supplied to panic was nil, recover returns // nil. Thus the return value from recover reports whether the goroutine is // panicking. func recover() interface{} // The print built-in function formats its arguments in an implementation- // specific way and writes the result to standard error. // Print is useful for bootstrapping and debugging; it is not guaranteed // to stay in the language. func print(args ...Type) // The println built-in function formats its arguments in an implementation- // specific way and writes the result to standard error. // Spaces are always added between arguments and a newline is appended. // Println is useful for bootstrapping and debugging; it is not guaranteed // to stay in the language. func println(args ...Type) // The error built-in interface type is the conventional interface for // representing an error condition, with the nil value representing no error. type error interface { Error() string } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/dirName/doesNotMatchDirectory.go ================================================ package otherPackage func PackageNameTesting() string { return "otherPackage" } func FunctionInPackageThatDoesNotMatchDirectoryName() string { return "otherPackage" } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/dirName/packageMatchesDirectory.go ================================================ package dirName func PackageNameTesting() string { return "hi" } func FunctionInPackageThatMatchesDirectoryName() string { return "otherPackage" } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/doc/dirs.go ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "go/build" "log" "os" "path" "path/filepath" "strings" ) // Dirs is a structure for scanning the directory tree. // Its Next method returns the next Go source directory it finds. // Although it can be used to scan the tree multiple times, it // only walks the tree once, caching the data it finds. type Dirs struct { scan chan string // directories generated by walk. paths []string // Cache of known paths. offset int // Counter for Next. } var dirs Dirs func init() { dirs.paths = make([]string, 0, 1000) dirs.scan = make(chan string) go dirs.walk() } // Reset puts the scan back at the beginning. func (d *Dirs) Reset() { d.offset = 0 } // Next returns the next directory in the scan. The boolean // is false when the scan is done. func (d *Dirs) Next() (string, bool) { if d.offset < len(d.paths) { path := d.paths[d.offset] d.offset++ return path, true } path, ok := <-d.scan if !ok { return "", false } d.paths = append(d.paths, path) d.offset++ return path, ok } // walk walks the trees in GOROOT and GOPATH. func (d *Dirs) walk() { d.bfsWalkRoot(build.Default.GOROOT) for _, root := range splitGopath() { d.bfsWalkRoot(root) } close(d.scan) } // bfsWalkRoot walks a single directory hierarchy in breadth-first lexical order. // Each Go source directory it finds is delivered on d.scan. func (d *Dirs) bfsWalkRoot(root string) { root = path.Join(root, "src") // this is the queue of directories to examine in this pass. this := []string{} // next is the queue of directories to examine in the next pass. next := []string{root} for len(next) > 0 { this, next = next, this[0:0] for _, dir := range this { fd, err := os.Open(dir) if err != nil { log.Printf("error opening %s: %v", dir, err) return // TODO? There may be entry before the error. } entries, err := fd.Readdir(0) fd.Close() if err != nil { log.Printf("error reading %s: %v", dir, err) return // TODO? There may be entry before the error. } hasGoFiles := false for _, entry := range entries { name := entry.Name() // For plain files, remember if this directory contains any .go // source files, but ignore them otherwise. if !entry.IsDir() { if !hasGoFiles && strings.HasSuffix(name, ".go") { hasGoFiles = true } continue } // Entry is a directory. // No .git or other dot nonsense please. if strings.HasPrefix(name, ".") { continue } // Remember this (fully qualified) directory for the next pass. next = append(next, filepath.Join(dir, name)) } if hasGoFiles { // It's a candidate. d.scan <- dir } } } } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/doc/doc_test.go ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "flag" "regexp" "runtime" "strings" "testing" ) func maybeSkip(t *testing.T) { if strings.HasPrefix(runtime.GOOS, "nacl") { t.Skip("nacl does not have a full file tree") } if runtime.GOOS == "darwin" && strings.HasPrefix(runtime.GOARCH, "arm") { t.Skip("darwin/arm does not have a full file tree") } } const ( dataDir = "testdata" binary = "testdoc" ) type test struct { name string args []string // Arguments to "[go] doc". yes []string // Regular expressions that should match. no []string // Regular expressions that should not match. } const p = "cmd/doc/testdata" var tests = []test{ // Sanity check. { "sanity check", []string{p}, []string{`type ExportedType struct`}, nil, }, // Package dump includes import, package statement. { "package clause", []string{p}, []string{`package pkg.*cmd/doc/testdata`}, nil, }, // Constants. // Package dump { "full package", []string{p}, []string{ `Package comment`, `const ExportedConstant = 1`, // Simple constant. `const ConstOne = 1`, // First entry in constant block. `const ConstFive ...`, // From block starting with unexported constant. `var ExportedVariable = 1`, // Simple variable. `var VarOne = 1`, // First entry in variable block. `func ExportedFunc\(a int\) bool`, // Function. `type ExportedType struct { ... }`, // Exported type. `const ExportedTypedConstant ExportedType = iota`, // Typed constant. `const ExportedTypedConstant_unexported unexportedType`, // Typed constant, exported for unexported type. }, []string{ `const internalConstant = 2`, // No internal constants. `var internalVariable = 2`, // No internal variables. `func internalFunc(a int) bool`, // No internal functions. `Comment about exported constant`, // No comment for single constant. `Comment about exported variable`, // No comment for single variable. `Comment about block of constants.`, // No comment for constant block. `Comment about block of variables.`, // No comment for variable block. `Comment before ConstOne`, // No comment for first entry in constant block. `Comment before VarOne`, // No comment for first entry in variable block. `ConstTwo = 2`, // No second entry in constant block. `VarTwo = 2`, // No second entry in variable block. `VarFive = 5`, // From block starting with unexported variable. `type unexportedType`, // No unexported type. `unexportedTypedConstant`, // No unexported typed constant. `Field`, // No fields. `Method`, // No methods. }, }, // Package dump -u { "full package with u", []string{`-u`, p}, []string{ `const ExportedConstant = 1`, // Simple constant. `const internalConstant = 2`, // Internal constants. `func internalFunc\(a int\) bool`, // Internal functions. }, []string{ `Comment about exported constant`, // No comment for simple constant. `Comment about block of constants`, // No comment for constant block. `Comment about internal function`, // No comment for internal function. }, }, // Single constant. { "single constant", []string{p, `ExportedConstant`}, []string{ `Comment about exported constant`, // Include comment. `const ExportedConstant = 1`, }, nil, }, // Single constant -u. { "single constant with -u", []string{`-u`, p, `internalConstant`}, []string{ `Comment about internal constant`, // Include comment. `const internalConstant = 2`, }, nil, }, // Block of constants. { "block of constants", []string{p, `ConstTwo`}, []string{ `Comment before ConstOne.\n.*ConstOne = 1`, // First... `ConstTwo = 2.*Comment on line with ConstTwo`, // And second show up. `Comment about block of constants`, // Comment does too. }, []string{ `constThree`, // No unexported constant. }, }, // Block of constants -u. { "block of constants with -u", []string{"-u", p, `constThree`}, []string{ `constThree = 3.*Comment on line with constThree`, }, nil, }, // Single variable. { "single variable", []string{p, `ExportedVariable`}, []string{ `ExportedVariable`, // Include comment. `var ExportedVariable = 1`, }, nil, }, // Single variable -u. { "single variable with -u", []string{`-u`, p, `internalVariable`}, []string{ `Comment about internal variable`, // Include comment. `var internalVariable = 2`, }, nil, }, // Block of variables. { "block of variables", []string{p, `VarTwo`}, []string{ `Comment before VarOne.\n.*VarOne = 1`, // First... `VarTwo = 2.*Comment on line with VarTwo`, // And second show up. `Comment about block of variables`, // Comment does too. }, []string{ `varThree= 3`, // No unexported variable. }, }, // Block of variables -u. { "block of variables with -u", []string{"-u", p, `varThree`}, []string{ `varThree = 3.*Comment on line with varThree`, }, nil, }, // Function. { "function", []string{p, `ExportedFunc`}, []string{ `Comment about exported function`, // Include comment. `func ExportedFunc\(a int\) bool`, }, nil, }, // Function -u. { "function with -u", []string{"-u", p, `internalFunc`}, []string{ `Comment about internal function`, // Include comment. `func internalFunc\(a int\) bool`, }, nil, }, // Type. { "type", []string{p, `ExportedType`}, []string{ `Comment about exported type`, // Include comment. `type ExportedType struct`, // Type definition. `Comment before exported field.*\n.*ExportedField +int` + `.*Comment on line with exported field.`, `Has unexported fields`, `func \(ExportedType\) ExportedMethod\(a int\) bool`, `const ExportedTypedConstant ExportedType = iota`, // Must include associated constant. `func ExportedTypeConstructor\(\) \*ExportedType`, // Must include constructor. }, []string{ `unexportedField`, // No unexported field. `Comment about exported method.`, // No comment about exported method. `unexportedMethod`, // No unexported method. `unexportedTypedConstant`, // No unexported constant. }, }, // Type -u with unexported fields. { "type with unexported fields and -u", []string{"-u", p, `ExportedType`}, []string{ `Comment about exported type`, // Include comment. `type ExportedType struct`, // Type definition. `Comment before exported field.*\n.*ExportedField +int`, `unexportedField int.*Comment on line with unexported field.`, `func \(ExportedType\) unexportedMethod\(a int\) bool`, `unexportedTypedConstant`, }, []string{ `Has unexported fields`, }, }, // Unexported type with -u. { "unexported type with -u", []string{"-u", p, `unexportedType`}, []string{ `Comment about unexported type`, // Include comment. `type unexportedType int`, // Type definition. `func \(unexportedType\) ExportedMethod\(\) bool`, `func \(unexportedType\) unexportedMethod\(\) bool`, `ExportedTypedConstant_unexported unexportedType = iota`, `const unexportedTypedConstant unexportedType = 1`, }, nil, }, // Interface. { "type", []string{p, `ExportedInterface`}, []string{ `Comment about exported interface`, // Include comment. `type ExportedInterface interface`, // Interface definition. `Comment before exported method.*\n.*ExportedMethod\(\)` + `.*Comment on line with exported method`, `Has unexported methods`, }, []string{ `unexportedField`, // No unexported field. `Comment about exported method`, // No comment about exported method. `unexportedMethod`, // No unexported method. `unexportedTypedConstant`, // No unexported constant. }, }, // Interface -u with unexported methods. { "type with unexported methods and -u", []string{"-u", p, `ExportedInterface`}, []string{ `Comment about exported interface`, // Include comment. `type ExportedInterface interface`, // Interface definition. `Comment before exported method.*\n.*ExportedMethod\(\)` + `.*Comment on line with exported method`, `unexportedMethod\(\).*Comment on line with unexported method.`, }, []string{ `Has unexported methods`, }, }, // Method. { "method", []string{p, `ExportedType.ExportedMethod`}, []string{ `func \(ExportedType\) ExportedMethod\(a int\) bool`, `Comment about exported method.`, }, nil, }, // Method with -u. { "method with -u", []string{"-u", p, `ExportedType.unexportedMethod`}, []string{ `func \(ExportedType\) unexportedMethod\(a int\) bool`, `Comment about unexported method.`, }, nil, }, // Case matching off. { "case matching off", []string{p, `casematch`}, []string{ `CaseMatch`, `Casematch`, }, nil, }, // Case matching on. { "case matching on", []string{"-c", p, `Casematch`}, []string{ `Casematch`, }, []string{ `CaseMatch`, }, }, } func TestDoc(t *testing.T) { maybeSkip(t) for _, test := range tests { var b bytes.Buffer var flagSet flag.FlagSet err := do(&b, &flagSet, test.args) if err != nil { t.Fatalf("%s: %s\n", test.name, err) } output := b.Bytes() failed := false for j, yes := range test.yes { re, err := regexp.Compile(yes) if err != nil { t.Fatalf("%s.%d: compiling %#q: %s", test.name, j, yes, err) } if !re.Match(output) { t.Errorf("%s.%d: no match for %s %#q", test.name, j, test.args, yes) failed = true } } for j, no := range test.no { re, err := regexp.Compile(no) if err != nil { t.Fatalf("%s.%d: compiling %#q: %s", test.name, j, no, err) } if re.Match(output) { t.Errorf("%s.%d: incorrect match for %s %#q", test.name, j, test.args, no) failed = true } } if failed { t.Logf("\n%s", output) } } } // Test the code to try multiple packages. Our test case is // go doc rand.Float64 // This needs to find math/rand.Float64; however crypto/rand, which doesn't // have the symbol, usually appears first in the directory listing. func TestMultiplePackages(t *testing.T) { if testing.Short() { t.Skip("scanning file system takes too long") } maybeSkip(t) var b bytes.Buffer // We don't care about the output. // Make sure crypto/rand does not have the symbol. { var flagSet flag.FlagSet err := do(&b, &flagSet, []string{"crypto/rand.float64"}) if err == nil { t.Errorf("expected error from crypto/rand.float64") } else if !strings.Contains(err.Error(), "no symbol float64") { t.Errorf("unexpected error %q from crypto/rand.float64", err) } } // Make sure math/rand does have the symbol. { var flagSet flag.FlagSet err := do(&b, &flagSet, []string{"math/rand.float64"}) if err != nil { t.Errorf("unexpected error %q from math/rand.float64", err) } } // Try the shorthand. { var flagSet flag.FlagSet err := do(&b, &flagSet, []string{"rand.float64"}) if err != nil { t.Errorf("unexpected error %q from rand.float64", err) } } // Now try a missing symbol. We should see both packages in the error. { var flagSet flag.FlagSet err := do(&b, &flagSet, []string{"rand.doesnotexit"}) if err == nil { t.Errorf("expected error from rand.doesnotexit") } else { errStr := err.Error() if !strings.Contains(errStr, "no symbol") { t.Errorf("error %q should contain 'no symbol", errStr) } if !strings.Contains(errStr, "crypto/rand") { t.Errorf("error %q should contain crypto/rand", errStr) } if !strings.Contains(errStr, "math/rand") { t.Errorf("error %q should contain math/rand", errStr) } } } } type trimTest struct { path string prefix string result string ok bool } var trimTests = []trimTest{ {"", "", "", true}, {"/usr/gopher", "/usr/gopher", "/usr/gopher", true}, {"/usr/gopher/bar", "/usr/gopher", "bar", true}, {"/usr/gopher", "/usr/gopher", "/usr/gopher", true}, {"/usr/gopherflakes", "/usr/gopher", "/usr/gopherflakes", false}, {"/usr/gopher/bar", "/usr/zot", "/usr/gopher/bar", false}, } func TestTrim(t *testing.T) { for _, test := range trimTests { result, ok := trim(test.path, test.prefix) if ok != test.ok { t.Errorf("%s %s expected %t got %t", test.path, test.prefix, test.ok, ok) continue } if result != test.result { t.Errorf("%s %s expected %q got %q", test.path, test.prefix, test.result, result) continue } } } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/doc/main.go ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Doc (usually run as go doc) accepts zero, one or two arguments. // // Zero arguments: // go doc // Show the documentation for the package in the current directory. // // One argument: // go doc // go doc [.] // go doc [.][.] // go doc [.][.] // The first item in this list that succeeds is the one whose documentation // is printed. If there is a symbol but no package, the package in the current // directory is chosen. However, if the argument begins with a capital // letter it is always assumed to be a symbol in the current directory. // // Two arguments: // go doc [.] // // Show the documentation for the package, symbol, and method. The // first argument must be a full package path. This is similar to the // command-line usage for the godoc command. // // For commands, unless the -cmd flag is present "go doc command" // shows only the package-level docs for the package. // // For complete documentation, run "go help doc". package main import ( "bytes" "flag" "fmt" "go/build" "io" "log" "os" "path/filepath" "strings" "unicode" "unicode/utf8" ) var ( unexported bool // -u flag matchCase bool // -c flag showCmd bool // -cmd flag ) // usage is a replacement usage function for the flags package. func usage() { fmt.Fprintf(os.Stderr, "Usage of [go] doc:\n") fmt.Fprintf(os.Stderr, "\tgo doc\n") fmt.Fprintf(os.Stderr, "\tgo doc \n") fmt.Fprintf(os.Stderr, "\tgo doc [.]\n") fmt.Fprintf(os.Stderr, "\tgo doc [].[.]\n") fmt.Fprintf(os.Stderr, "\tgo doc [.]\n") fmt.Fprintf(os.Stderr, "For more information run\n") fmt.Fprintf(os.Stderr, "\tgo help doc\n\n") fmt.Fprintf(os.Stderr, "Flags:\n") flag.PrintDefaults() os.Exit(2) } func main() { log.SetFlags(0) log.SetPrefix("doc: ") err := do(os.Stdout, flag.CommandLine, os.Args[1:]) if err != nil { log.Fatal(err) } } // do is the workhorse, broken out of main to make testing easier. func do(writer io.Writer, flagSet *flag.FlagSet, args []string) (err error) { flagSet.Usage = usage unexported = false matchCase = false flagSet.BoolVar(&unexported, "u", false, "show unexported symbols as well as exported") flagSet.BoolVar(&matchCase, "c", false, "symbol matching honors case (paths not affected)") flagSet.BoolVar(&showCmd, "cmd", false, "show symbols with package docs even if package is a command") flagSet.Parse(args) var paths []string var symbol, method string // Loop until something is printed. dirs.Reset() for i := 0; ; i++ { buildPackage, userPath, sym, more := parseArgs(flagSet.Args()) if i > 0 && !more { // Ignore the "more" bit on the first iteration. return failMessage(paths, symbol, method) } symbol, method = parseSymbol(sym) pkg := parsePackage(writer, buildPackage, userPath) paths = append(paths, pkg.prettyPath()) defer func() { pkg.flush() e := recover() if e == nil { return } pkgError, ok := e.(PackageError) if ok { err = pkgError return } panic(e) }() // The builtin package needs special treatment: its symbols are lower // case but we want to see them, always. if pkg.build.ImportPath == "builtin" { unexported = true } switch { case symbol == "": pkg.packageDoc() // The package exists, so we got some output. return case method == "": if pkg.symbolDoc(symbol) { return } default: if pkg.methodDoc(symbol, method) { return } } } } // failMessage creates a nicely formatted error message when there is no result to show. func failMessage(paths []string, symbol, method string) error { var b bytes.Buffer if len(paths) > 1 { b.WriteString("s") } b.WriteString(" ") for i, path := range paths { if i > 0 { b.WriteString(", ") } b.WriteString(path) } if method == "" { return fmt.Errorf("no symbol %s in package%s", symbol, &b) } return fmt.Errorf("no method %s.%s in package%s", symbol, method, &b) } // parseArgs analyzes the arguments (if any) and returns the package // it represents, the part of the argument the user used to identify // the path (or "" if it's the current package) and the symbol // (possibly with a .method) within that package. // parseSymbol is used to analyze the symbol itself. // The boolean final argument reports whether it is possible that // there may be more directories worth looking at. It will only // be true if the package path is a partial match for some directory // and there may be more matches. For example, if the argument // is rand.Float64, we must scan both crypto/rand and math/rand // to find the symbol, and the first call will return crypto/rand, true. func parseArgs(args []string) (pkg *build.Package, path, symbol string, more bool) { switch len(args) { default: usage() case 0: // Easy: current directory. return importDir(pwd()), "", "", false case 1: // Done below. case 2: // Package must be importable. pkg, err := build.Import(args[0], "", build.ImportComment) if err != nil { log.Fatalf("%s", err) } return pkg, args[0], args[1], false } // Usual case: one argument. arg := args[0] // If it contains slashes, it begins with a package path. // First, is it a complete package path as it is? If so, we are done. // This avoids confusion over package paths that have other // package paths as their prefix. pkg, err := build.Import(arg, "", build.ImportComment) if err == nil { return pkg, arg, "", false } // Another disambiguator: If the symbol starts with an upper // case letter, it can only be a symbol in the current directory. // Kills the problem caused by case-insensitive file systems // matching an upper case name as a package name. if isUpper(arg) { pkg, err := build.ImportDir(".", build.ImportComment) if err == nil { return pkg, "", arg, false } } // If it has a slash, it must be a package path but there is a symbol. // It's the last package path we care about. slash := strings.LastIndex(arg, "/") // There may be periods in the package path before or after the slash // and between a symbol and method. // Split the string at various periods to see what we find. // In general there may be ambiguities but this should almost always // work. var period int // slash+1: if there's no slash, the value is -1 and start is 0; otherwise // start is the byte after the slash. for start := slash + 1; start < len(arg); start = period + 1 { period = strings.Index(arg[start:], ".") symbol := "" if period < 0 { period = len(arg) } else { period += start symbol = arg[period+1:] } // Have we identified a package already? pkg, err := build.Import(arg[0:period], "", build.ImportComment) if err == nil { return pkg, arg[0:period], symbol, false } // See if we have the basename or tail of a package, as in json for encoding/json // or ivy/value for robpike.io/ivy/value. // Launch findPackage as a goroutine so it can return multiple paths if required. path, ok := findPackage(arg[0:period]) if ok { return importDir(path), arg[0:period], symbol, true } dirs.Reset() // Next iteration of for loop must scan all the directories again. } // If it has a slash, we've failed. if slash >= 0 { log.Fatalf("no such package %s", arg[0:period]) } // Guess it's a symbol in the current directory. return importDir(pwd()), "", arg, false } // importDir is just an error-catching wrapper for build.ImportDir. func importDir(dir string) *build.Package { pkg, err := build.ImportDir(dir, build.ImportComment) if err != nil { log.Fatal(err) } return pkg } // parseSymbol breaks str apart into a symbol and method. // Both may be missing or the method may be missing. // If present, each must be a valid Go identifier. func parseSymbol(str string) (symbol, method string) { if str == "" { return } elem := strings.Split(str, ".") switch len(elem) { case 1: case 2: method = elem[1] isIdentifier(method) default: log.Printf("too many periods in symbol specification") usage() } symbol = elem[0] isIdentifier(symbol) return } // isIdentifier checks that the name is valid Go identifier, and // logs and exits if it is not. func isIdentifier(name string) { if len(name) == 0 { log.Fatal("empty symbol") } for i, ch := range name { if unicode.IsLetter(ch) || ch == '_' || i > 0 && unicode.IsDigit(ch) { continue } log.Fatalf("invalid identifier %q", name) } } // isExported reports whether the name is an exported identifier. // If the unexported flag (-u) is true, isExported returns true because // it means that we treat the name as if it is exported. func isExported(name string) bool { return unexported || isUpper(name) } // isUpper reports whether the name starts with an upper case letter. func isUpper(name string) bool { ch, _ := utf8.DecodeRuneInString(name) return unicode.IsUpper(ch) } // findPackage returns the full file name path that first matches the // (perhaps partial) package path pkg. The boolean reports if any match was found. func findPackage(pkg string) (string, bool) { if pkg == "" || isUpper(pkg) { // Upper case symbol cannot be a package name. return "", false } pkgString := filepath.Clean(string(filepath.Separator) + pkg) for { path, ok := dirs.Next() if !ok { return "", false } if strings.HasSuffix(path, pkgString) { return path, true } } } // splitGopath splits $GOPATH into a list of roots. func splitGopath() []string { return filepath.SplitList(build.Default.GOPATH) } // pwd returns the current directory. func pwd() string { wd, err := os.Getwd() if err != nil { log.Fatal(err) } return wd } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/doc/pkg.go ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "fmt" "go/ast" "go/build" "go/doc" "go/format" "go/parser" "go/token" "io" "log" "os" "path/filepath" "strings" "unicode" "unicode/utf8" ) const ( punchedCardWidth = 80 // These things just won't leave us alone. indentedWidth = punchedCardWidth - len(indent) indent = " " ) type Package struct { writer io.Writer // Destination for output. name string // Package name, json for encoding/json. userPath string // String the user used to find this package. unexported bool matchCase bool pkg *ast.Package // Parsed package. file *ast.File // Merged from all files in the package doc *doc.Package build *build.Package fs *token.FileSet // Needed for printing. buf bytes.Buffer } type PackageError string // type returned by pkg.Fatalf. func (p PackageError) Error() string { return string(p) } // prettyPath returns a version of the package path that is suitable for an // error message. It obeys the import comment if present. Also, since // pkg.build.ImportPath is sometimes the unhelpful "" or ".", it looks for a // directory name in GOROOT or GOPATH if that happens. func (pkg *Package) prettyPath() string { path := pkg.build.ImportComment if path == "" { path = pkg.build.ImportPath } if path != "." && path != "" { return path } // Convert the source directory into a more useful path. // Also convert everything to slash-separated paths for uniform handling. path = filepath.Clean(filepath.ToSlash(pkg.build.Dir)) // Can we find a decent prefix? goroot := filepath.Join(build.Default.GOROOT, "src") if p, ok := trim(path, filepath.ToSlash(goroot)); ok { return p } for _, gopath := range splitGopath() { if p, ok := trim(path, filepath.ToSlash(gopath)); ok { return p } } return path } // trim trims the directory prefix from the path, paying attention // to the path separator. If they are the same string or the prefix // is not present the original is returned. The boolean reports whether // the prefix is present. That path and prefix have slashes for separators. func trim(path, prefix string) (string, bool) { if !strings.HasPrefix(path, prefix) { return path, false } if path == prefix { return path, true } if path[len(prefix)] == '/' { return path[len(prefix)+1:], true } return path, false // Textual prefix but not a path prefix. } // pkg.Fatalf is like log.Fatalf, but panics so it can be recovered in the // main do function, so it doesn't cause an exit. Allows testing to work // without running a subprocess. The log prefix will be added when // logged in main; it is not added here. func (pkg *Package) Fatalf(format string, args ...interface{}) { panic(PackageError(fmt.Sprintf(format, args...))) } // parsePackage turns the build package we found into a parsed package // we can then use to generate documentation. func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Package { fs := token.NewFileSet() // include tells parser.ParseDir which files to include. // That means the file must be in the build package's GoFiles or CgoFiles // list only (no tag-ignored files, tests, swig or other non-Go files). include := func(info os.FileInfo) bool { for _, name := range pkg.GoFiles { if name == info.Name() { return true } } for _, name := range pkg.CgoFiles { if name == info.Name() { return true } } return false } pkgs, err := parser.ParseDir(fs, pkg.Dir, include, parser.ParseComments) if err != nil { log.Fatal(err) } // Make sure they are all in one package. if len(pkgs) != 1 { log.Fatalf("multiple packages in directory %s", pkg.Dir) } astPkg := pkgs[pkg.Name] // TODO: go/doc does not include typed constants in the constants // list, which is what we want. For instance, time.Sunday is of type // time.Weekday, so it is defined in the type but not in the // Consts list for the package. This prevents // go doc time.Sunday // from finding the symbol. Work around this for now, but we // should fix it in go/doc. // A similar story applies to factory functions. docPkg := doc.New(astPkg, pkg.ImportPath, doc.AllDecls) for _, typ := range docPkg.Types { docPkg.Consts = append(docPkg.Consts, typ.Consts...) docPkg.Vars = append(docPkg.Vars, typ.Vars...) docPkg.Funcs = append(docPkg.Funcs, typ.Funcs...) } return &Package{ writer: writer, name: pkg.Name, userPath: userPath, pkg: astPkg, file: ast.MergePackageFiles(astPkg, 0), doc: docPkg, build: pkg, fs: fs, } } func (pkg *Package) Printf(format string, args ...interface{}) { fmt.Fprintf(&pkg.buf, format, args...) } func (pkg *Package) flush() { _, err := pkg.writer.Write(pkg.buf.Bytes()) if err != nil { log.Fatal(err) } pkg.buf.Reset() // Not needed, but it's a flush. } var newlineBytes = []byte("\n\n") // We never ask for more than 2. // newlines guarantees there are n newlines at the end of the buffer. func (pkg *Package) newlines(n int) { for !bytes.HasSuffix(pkg.buf.Bytes(), newlineBytes[:n]) { pkg.buf.WriteRune('\n') } } // emit prints the node. func (pkg *Package) emit(comment string, node ast.Node) { if node != nil { err := format.Node(&pkg.buf, pkg.fs, node) if err != nil { log.Fatal(err) } if comment != "" { pkg.newlines(1) doc.ToText(&pkg.buf, comment, " ", indent, indentedWidth) pkg.newlines(2) // Blank line after comment to separate from next item. } else { pkg.newlines(1) } } } var formatBuf bytes.Buffer // Reusable to avoid allocation. // formatNode is a helper function for printing. func (pkg *Package) formatNode(node ast.Node) []byte { formatBuf.Reset() format.Node(&formatBuf, pkg.fs, node) return formatBuf.Bytes() } // oneLineFunc prints a function declaration as a single line. func (pkg *Package) oneLineFunc(decl *ast.FuncDecl) { decl.Doc = nil decl.Body = nil pkg.emit("", decl) } // oneLineValueGenDecl prints a var or const declaration as a single line. func (pkg *Package) oneLineValueGenDecl(decl *ast.GenDecl) { decl.Doc = nil dotDotDot := "" if len(decl.Specs) > 1 { dotDotDot = " ..." } // Find the first relevant spec. for i, spec := range decl.Specs { valueSpec := spec.(*ast.ValueSpec) // Must succeed; we can't mix types in one genDecl. if !isExported(valueSpec.Names[0].Name) { continue } typ := "" if valueSpec.Type != nil { typ = fmt.Sprintf(" %s", pkg.formatNode(valueSpec.Type)) } val := "" if i < len(valueSpec.Values) && valueSpec.Values[i] != nil { val = fmt.Sprintf(" = %s", pkg.formatNode(valueSpec.Values[i])) } pkg.Printf("%s %s%s%s%s\n", decl.Tok, valueSpec.Names[0], typ, val, dotDotDot) break } } // oneLineTypeDecl prints a type declaration as a single line. func (pkg *Package) oneLineTypeDecl(spec *ast.TypeSpec) { spec.Doc = nil spec.Comment = nil switch spec.Type.(type) { case *ast.InterfaceType: pkg.Printf("type %s interface { ... }\n", spec.Name) case *ast.StructType: pkg.Printf("type %s struct { ... }\n", spec.Name) default: pkg.Printf("type %s %s\n", spec.Name, pkg.formatNode(spec.Type)) } } // packageDoc prints the docs for the package (package doc plus one-liners of the rest). func (pkg *Package) packageDoc() { defer pkg.flush() if pkg.showInternals() { pkg.packageClause(false) } doc.ToText(&pkg.buf, pkg.doc.Doc, "", indent, indentedWidth) pkg.newlines(1) if !pkg.showInternals() { // Show only package docs for commands. return } pkg.newlines(2) // Guarantee blank line before the components. pkg.valueSummary(pkg.doc.Consts) pkg.valueSummary(pkg.doc.Vars) pkg.funcSummary(pkg.doc.Funcs) pkg.typeSummary() pkg.bugs() } // showInternals reports whether we should show the internals // of a package as opposed to just the package docs. // Used to decide whether to suppress internals for commands. // Called only by Package.packageDoc. func (pkg *Package) showInternals() bool { return pkg.pkg.Name != "main" || showCmd } // packageClause prints the package clause. // The argument boolean, if true, suppresses the output if the // user's argument is identical to the actual package path or // is empty, meaning it's the current directory. func (pkg *Package) packageClause(checkUserPath bool) { if checkUserPath { if pkg.userPath == "" || pkg.userPath == pkg.build.ImportPath { return } } importPath := pkg.build.ImportComment if importPath == "" { importPath = pkg.build.ImportPath } pkg.Printf("package %s // import %q\n\n", pkg.name, importPath) if importPath != pkg.build.ImportPath { pkg.Printf("WARNING: package source is installed in %q\n", pkg.build.ImportPath) } } // valueSummary prints a one-line summary for each set of values and constants. func (pkg *Package) valueSummary(values []*doc.Value) { for _, value := range values { pkg.oneLineValueGenDecl(value.Decl) } } // funcSummary prints a one-line summary for each function. func (pkg *Package) funcSummary(funcs []*doc.Func) { for _, fun := range funcs { decl := fun.Decl // Exported functions only. The go/doc package does not include methods here. if isExported(fun.Name) { pkg.oneLineFunc(decl) } } } // typeSummary prints a one-line summary for each type. func (pkg *Package) typeSummary() { for _, typ := range pkg.doc.Types { for _, spec := range typ.Decl.Specs { typeSpec := spec.(*ast.TypeSpec) // Must succeed. if isExported(typeSpec.Name.Name) { pkg.oneLineTypeDecl(typeSpec) } } } } // bugs prints the BUGS information for the package. // TODO: Provide access to TODOs and NOTEs as well (very noisy so off by default)? func (pkg *Package) bugs() { if pkg.doc.Notes["BUG"] == nil { return } pkg.Printf("\n") for _, note := range pkg.doc.Notes["BUG"] { pkg.Printf("%s: %v\n", "BUG", note.Body) } } // findValues finds the doc.Values that describe the symbol. func (pkg *Package) findValues(symbol string, docValues []*doc.Value) (values []*doc.Value) { for _, value := range docValues { for _, name := range value.Names { if match(symbol, name) { values = append(values, value) } } } return } // findFuncs finds the doc.Funcs that describes the symbol. func (pkg *Package) findFuncs(symbol string) (funcs []*doc.Func) { for _, fun := range pkg.doc.Funcs { if match(symbol, fun.Name) { funcs = append(funcs, fun) } } return } // findTypes finds the doc.Types that describes the symbol. // If symbol is empty, it finds all exported types. func (pkg *Package) findTypes(symbol string) (types []*doc.Type) { for _, typ := range pkg.doc.Types { if symbol == "" && isExported(typ.Name) || match(symbol, typ.Name) { types = append(types, typ) } } return } // findTypeSpec returns the ast.TypeSpec within the declaration that defines the symbol. // The name must match exactly. func (pkg *Package) findTypeSpec(decl *ast.GenDecl, symbol string) *ast.TypeSpec { for _, spec := range decl.Specs { typeSpec := spec.(*ast.TypeSpec) // Must succeed. if symbol == typeSpec.Name.Name { return typeSpec } } return nil } // symbolDoc prints the docs for symbol. There may be multiple matches. // If symbol matches a type, output includes its methods factories and associated constants. // If there is no top-level symbol, symbolDoc looks for methods that match. func (pkg *Package) symbolDoc(symbol string) bool { defer pkg.flush() found := false // Functions. for _, fun := range pkg.findFuncs(symbol) { if !found { pkg.packageClause(true) } // Symbol is a function. decl := fun.Decl decl.Body = nil pkg.emit(fun.Doc, decl) found = true } // Constants and variables behave the same. values := pkg.findValues(symbol, pkg.doc.Consts) values = append(values, pkg.findValues(symbol, pkg.doc.Vars)...) for _, value := range values { // Print each spec only if there is at least one exported symbol in it. // (See issue 11008.) // TODO: Should we elide unexported symbols from a single spec? // It's an unlikely scenario, probably not worth the trouble. // TODO: Would be nice if go/doc did this for us. specs := make([]ast.Spec, 0, len(value.Decl.Specs)) for _, spec := range value.Decl.Specs { vspec := spec.(*ast.ValueSpec) for _, ident := range vspec.Names { if isExported(ident.Name) { specs = append(specs, vspec) break } } } if len(specs) == 0 { continue } value.Decl.Specs = specs if !found { pkg.packageClause(true) } pkg.emit(value.Doc, value.Decl) found = true } // Types. for _, typ := range pkg.findTypes(symbol) { if !found { pkg.packageClause(true) } decl := typ.Decl spec := pkg.findTypeSpec(decl, typ.Name) trimUnexportedElems(spec) // If there are multiple types defined, reduce to just this one. if len(decl.Specs) > 1 { decl.Specs = []ast.Spec{spec} } pkg.emit(typ.Doc, decl) // Show associated methods, constants, etc. if len(typ.Consts) > 0 || len(typ.Vars) > 0 || len(typ.Funcs) > 0 || len(typ.Methods) > 0 { pkg.Printf("\n") } pkg.valueSummary(typ.Consts) pkg.valueSummary(typ.Vars) pkg.funcSummary(typ.Funcs) pkg.funcSummary(typ.Methods) found = true } if !found { // See if there are methods. if !pkg.printMethodDoc("", symbol) { return false } } return true } // trimUnexportedElems modifies spec in place to elide unexported fields from // structs and methods from interfaces (unless the unexported flag is set). func trimUnexportedElems(spec *ast.TypeSpec) { if unexported { return } switch typ := spec.Type.(type) { case *ast.StructType: typ.Fields = trimUnexportedFields(typ.Fields, "fields") case *ast.InterfaceType: typ.Methods = trimUnexportedFields(typ.Methods, "methods") } } // trimUnexportedFields returns the field list trimmed of unexported fields. func trimUnexportedFields(fields *ast.FieldList, what string) *ast.FieldList { trimmed := false list := make([]*ast.Field, 0, len(fields.List)) for _, field := range fields.List { // Trims if any is unexported. Good enough in practice. ok := true for _, name := range field.Names { if !isExported(name.Name) { trimmed = true ok = false break } } if ok { list = append(list, field) } } if !trimmed { return fields } unexportedField := &ast.Field{ Type: &ast.Ident{ // Hack: printer will treat this as a field with a named type. // Setting Name and NamePos to ("", fields.Closing-1) ensures that // when Pos and End are called on this field, they return the // position right before closing '}' character. Name: "", NamePos: fields.Closing - 1, }, Comment: &ast.CommentGroup{ List: []*ast.Comment{{Text: fmt.Sprintf("// Has unexported %s.\n", what)}}, }, } return &ast.FieldList{ Opening: fields.Opening, List: append(list, unexportedField), Closing: fields.Closing, } } // printMethodDoc prints the docs for matches of symbol.method. // If symbol is empty, it prints all methods that match the name. // It reports whether it found any methods. func (pkg *Package) printMethodDoc(symbol, method string) bool { defer pkg.flush() types := pkg.findTypes(symbol) if types == nil { if symbol == "" { return false } pkg.Fatalf("symbol %s is not a type in package %s installed in %q", symbol, pkg.name, pkg.build.ImportPath) } found := false for _, typ := range types { for _, meth := range typ.Methods { if match(method, meth.Name) { decl := meth.Decl decl.Body = nil pkg.emit(meth.Doc, decl) found = true } } } return found } // methodDoc prints the docs for matches of symbol.method. func (pkg *Package) methodDoc(symbol, method string) bool { defer pkg.flush() return pkg.printMethodDoc(symbol, method) } // match reports whether the user's symbol matches the program's. // A lower-case character in the user's string matches either case in the program's. // The program string must be exported. func match(user, program string) bool { if !isExported(program) { return false } if matchCase { return user == program } for _, u := range user { p, w := utf8.DecodeRuneInString(program) program = program[w:] if u == p { continue } if unicode.IsLower(u) && simpleFold(u) == simpleFold(p) { continue } return false } return program == "" } // simpleFold returns the minimum rune equivalent to r // under Unicode-defined simple case folding. func simpleFold(r rune) rune { for { r1 := unicode.SimpleFold(r) if r1 <= r { return r1 // wrapped around, found min } r = r1 } } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/doc/testdata/pkg.go ================================================ // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package comment. package pkg // Constants // Comment about exported constant. const ExportedConstant = 1 // Comment about internal constant. const internalConstant = 2 // Comment about block of constants. const ( // Comment before ConstOne. ConstOne = 1 ConstTwo = 2 // Comment on line with ConstTwo. constThree = 3 // Comment on line with constThree. ) // Const block where first entry is unexported. const ( constFour = iota ConstFive ConstSix ) // Variables // Comment about exported variable. var ExportedVariable = 1 // Comment about internal variable. var internalVariable = 2 // Comment about block of variables. var ( // Comment before VarOne. VarOne = 1 VarTwo = 2 // Comment on line with VarTwo. varThree = 3 // Comment on line with varThree. ) // Var block where first entry is unexported. var ( varFour = 4 VarFive = 5 varSix = 6 ) // Comment about exported function. func ExportedFunc(a int) bool // Comment about internal function. func internalFunc(a int) bool // Comment about exported type. type ExportedType struct { // Comment before exported field. ExportedField int // Comment on line with exported field. unexportedField int // Comment on line with unexported field. } // Comment about exported method. func (ExportedType) ExportedMethod(a int) bool { return true } // Comment about unexported method. func (ExportedType) unexportedMethod(a int) bool { return true } // Constants tied to ExportedType. (The type is a struct so this isn't valid Go, // but it parses and that's all we need.) const ( ExportedTypedConstant ExportedType = iota ) // Comment about constructor for exported type. func ExportedTypeConstructor() *ExportedType { return nil } const unexportedTypedConstant ExportedType = 1 // In a separate section to test -u. // Comment about exported interface. type ExportedInterface interface { // Comment before exported method. ExportedMethod() // Comment on line with exported method. unexportedMethod() // Comment on line with unexported method. } // Comment about unexported type. type unexportedType int func (unexportedType) ExportedMethod() bool { return true } func (unexportedType) unexportedMethod() bool { return true } // Constants tied to unexportedType. const ( ExportedTypedConstant_unexported unexportedType = iota ) const unexportedTypedConstant unexportedType = 1 // In a separate section to test -u. // For case matching. const CaseMatch = 1 const Casematch = 2 ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/docs/docs.go ================================================ package docs // TypeResult func comment func TypeResult(s string) string { return s } // MultiType is a function like all other functions func MultiType( demo interface{}, err error, ) ( []interface{}, error, ) { return []interface{}{}, err } // Global comment var ( // InnerVariable_1 InnerVariable_1, // InnerVariable_2 InnerVariable_2, // InnerVariable_3 InnerVariable_3 int // InnerVariable_4 InnerVariable_4 int InnerVariable_5 int ) ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/emptyDirectory/.doNotDelete ================================================ ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/fmt/doc.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler. */ package fmt ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/fmt/format.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fmt import ( "strconv" "unicode/utf8" ) const ( nByte = 65 // %b of an int64, plus a sign. ldigits = "0123456789abcdef" udigits = "0123456789ABCDEF" ) const ( signed = true unsigned = false ) var padZeroBytes = make([]byte, nByte) var padSpaceBytes = make([]byte, nByte) var newline = []byte{'\n'} func init() { for i := 0; i < nByte; i++ { padZeroBytes[i] = '0' padSpaceBytes[i] = ' ' } } // A fmt is the raw formatter used by Printf etc. // It prints into a buffer that must be set up separately. type fmt struct { intbuf [nByte]byte buf *buffer // width, precision wid int prec int // flags widPresent bool precPresent bool minus bool plus bool sharp bool space bool unicode bool uniQuote bool // Use 'x'= prefix for %U if printable. zero bool } func (f *fmt) clearflags() { f.wid = 0 f.widPresent = false f.prec = 0 f.precPresent = false f.minus = false f.plus = false f.sharp = false f.space = false f.unicode = false f.uniQuote = false f.zero = false } func (f *fmt) init(buf *buffer) { f.buf = buf f.clearflags() } // computePadding computes left and right padding widths (only one will be non-zero). func (f *fmt) computePadding(width int) (padding []byte, leftWidth, rightWidth int) { left := !f.minus w := f.wid if w < 0 { left = false w = -w } w -= width if w > 0 { if left && f.zero { return padZeroBytes, w, 0 } if left { return padSpaceBytes, w, 0 } else { // can't be zero padding on the right return padSpaceBytes, 0, w } } return } // writePadding generates n bytes of padding. func (f *fmt) writePadding(n int, padding []byte) { for n > 0 { m := n if m > nByte { m = nByte } f.buf.Write(padding[0:m]) n -= m } } // pad appends b to f.buf, padded on left (w > 0) or right (w < 0 or f.minus). func (f *fmt) pad(b []byte) { if !f.widPresent || f.wid == 0 { f.buf.Write(b) return } padding, left, right := f.computePadding(len(b)) if left > 0 { f.writePadding(left, padding) } f.buf.Write(b) if right > 0 { f.writePadding(right, padding) } } // padString appends s to buf, padded on left (w > 0) or right (w < 0 or f.minus). func (f *fmt) padString(s string) { if !f.widPresent || f.wid == 0 { f.buf.WriteString(s) return } padding, left, right := f.computePadding(utf8.RuneCountInString(s)) if left > 0 { f.writePadding(left, padding) } f.buf.WriteString(s) if right > 0 { f.writePadding(right, padding) } } var ( trueBytes = []byte("true") falseBytes = []byte("false") ) // fmt_boolean formats a boolean. func (f *fmt) fmt_boolean(v bool) { if v { f.pad(trueBytes) } else { f.pad(falseBytes) } } // integer; interprets prec but not wid. Once formatted, result is sent to pad() // and then flags are cleared. func (f *fmt) integer(a int64, base uint64, signedness bool, digits string) { // precision of 0 and value of 0 means "print nothing" if f.precPresent && f.prec == 0 && a == 0 { return } var buf []byte = f.intbuf[0:] negative := signedness == signed && a < 0 if negative { a = -a } // two ways to ask for extra leading zero digits: %.3d or %03d. // apparently the first cancels the second. prec := 0 if f.precPresent { prec = f.prec f.zero = false } else if f.zero && f.widPresent && !f.minus && f.wid > 0 { prec = f.wid if negative || f.plus || f.space { prec-- // leave room for sign } } // format a into buf, ending at buf[i]. (printing is easier right-to-left.) // a is made into unsigned ua. we could make things // marginally faster by splitting the 32-bit case out into a separate // block but it's not worth the duplication, so ua has 64 bits. i := len(f.intbuf) ua := uint64(a) for ua >= base { i-- buf[i] = digits[ua%base] ua /= base } i-- buf[i] = digits[ua] for i > 0 && prec > nByte-i { i-- buf[i] = '0' } // Various prefixes: 0x, -, etc. if f.sharp { switch base { case 8: if buf[i] != '0' { i-- buf[i] = '0' } case 16: i-- buf[i] = 'x' + digits[10] - 'a' i-- buf[i] = '0' } } if f.unicode { i-- buf[i] = '+' i-- buf[i] = 'U' } if negative { i-- buf[i] = '-' } else if f.plus { i-- buf[i] = '+' } else if f.space { i-- buf[i] = ' ' } // If we want a quoted char for %#U, move the data up to make room. if f.unicode && f.uniQuote && a >= 0 && a <= utf8.MaxRune && strconv.IsPrint(rune(a)) { runeWidth := utf8.RuneLen(rune(a)) width := 1 + 1 + runeWidth + 1 // space, quote, rune, quote copy(buf[i-width:], buf[i:]) // guaranteed to have enough room. i -= width // Now put " 'x'" at the end. j := len(buf) - width buf[j] = ' ' j++ buf[j] = '\'' j++ utf8.EncodeRune(buf[j:], rune(a)) j += runeWidth buf[j] = '\'' } f.pad(buf[i:]) } // truncate truncates the string to the specified precision, if present. func (f *fmt) truncate(s string) string { if f.precPresent && f.prec < utf8.RuneCountInString(s) { n := f.prec for i := range s { if n == 0 { s = s[:i] break } n-- } } return s } // fmt_s formats a string. func (f *fmt) fmt_s(s string) { s = f.truncate(s) f.padString(s) } // fmt_sbx formats a string or byte slice as a hexadecimal encoding of its bytes. func (f *fmt) fmt_sbx(s string, b []byte, digits string) { n := len(b) if b == nil { n = len(s) } x := digits[10] - 'a' + 'x' // TODO: Avoid buffer by pre-padding. var buf []byte for i := 0; i < n; i++ { if i > 0 && f.space { buf = append(buf, ' ') } if f.sharp { buf = append(buf, '0', x) } var c byte if b == nil { c = s[i] } else { c = b[i] } buf = append(buf, digits[c>>4], digits[c&0xF]) } f.pad(buf) } // fmt_sx formats a string as a hexadecimal encoding of its bytes. func (f *fmt) fmt_sx(s, digits string) { f.fmt_sbx(s, nil, digits) } // fmt_bx formats a byte slice as a hexadecimal encoding of its bytes. func (f *fmt) fmt_bx(b []byte, digits string) { f.fmt_sbx("", b, digits) } // fmt_q formats a string as a double-quoted, escaped Go string constant. func (f *fmt) fmt_q(s string) { s = f.truncate(s) var quoted string if f.sharp && strconv.CanBackquote(s) { quoted = "`" + s + "`" } else { if f.plus { quoted = strconv.QuoteToASCII(s) } else { quoted = strconv.Quote(s) } } f.padString(quoted) } // fmt_qc formats the integer as a single-quoted, escaped Go character constant. // If the character is not valid Unicode, it will print '\ufffd'. func (f *fmt) fmt_qc(c int64) { var quoted []byte if f.plus { quoted = strconv.AppendQuoteRuneToASCII(f.intbuf[0:0], rune(c)) } else { quoted = strconv.AppendQuoteRune(f.intbuf[0:0], rune(c)) } f.pad(quoted) } // floating-point func doPrec(f *fmt, def int) int { if f.precPresent { return f.prec } return def } // formatFloat formats a float64; it is an efficient equivalent to f.pad(strconv.FormatFloat()...). func (f *fmt) formatFloat(v float64, verb byte, prec, n int) { // We leave one byte at the beginning of f.intbuf for a sign if needed, // and make it a space, which we might be able to use. f.intbuf[0] = ' ' slice := strconv.AppendFloat(f.intbuf[0:1], v, verb, prec, n) // Add a plus sign or space to the floating-point string representation if missing and required. // The formatted number starts at slice[1]. switch slice[1] { case '-', '+': // We're set; drop the leading space. slice = slice[1:] default: // There's no sign, but we might need one. if f.plus { slice[0] = '+' } else if f.space { // space is already there } else { slice = slice[1:] } } f.pad(slice) } // fmt_e64 formats a float64 in the form -1.23e+12. func (f *fmt) fmt_e64(v float64) { f.formatFloat(v, 'e', doPrec(f, 6), 64) } // fmt_E64 formats a float64 in the form -1.23E+12. func (f *fmt) fmt_E64(v float64) { f.formatFloat(v, 'E', doPrec(f, 6), 64) } // fmt_f64 formats a float64 in the form -1.23. func (f *fmt) fmt_f64(v float64) { f.formatFloat(v, 'f', doPrec(f, 6), 64) } // fmt_g64 formats a float64 in the 'f' or 'e' form according to size. func (f *fmt) fmt_g64(v float64) { f.formatFloat(v, 'g', doPrec(f, -1), 64) } // fmt_G64 formats a float64 in the 'f' or 'E' form according to size. func (f *fmt) fmt_G64(v float64) { f.formatFloat(v, 'G', doPrec(f, -1), 64) } // fmt_fb64 formats a float64 in the form -123p3 (exponent is power of 2). func (f *fmt) fmt_fb64(v float64) { f.formatFloat(v, 'b', 0, 64) } // float32 // cannot defer to float64 versions // because it will get rounding wrong in corner cases. // fmt_e32 formats a float32 in the form -1.23e+12. func (f *fmt) fmt_e32(v float32) { f.formatFloat(float64(v), 'e', doPrec(f, 6), 32) } // fmt_E32 formats a float32 in the form -1.23E+12. func (f *fmt) fmt_E32(v float32) { f.formatFloat(float64(v), 'E', doPrec(f, 6), 32) } // fmt_f32 formats a float32 in the form -1.23. func (f *fmt) fmt_f32(v float32) { f.formatFloat(float64(v), 'f', doPrec(f, 6), 32) } // fmt_g32 formats a float32 in the 'f' or 'e' form according to size. func (f *fmt) fmt_g32(v float32) { f.formatFloat(float64(v), 'g', doPrec(f, -1), 32) } // fmt_G32 formats a float32 in the 'f' or 'E' form according to size. func (f *fmt) fmt_G32(v float32) { f.formatFloat(float64(v), 'G', doPrec(f, -1), 32) } // fmt_fb32 formats a float32 in the form -123p3 (exponent is power of 2). func (f *fmt) fmt_fb32(v float32) { f.formatFloat(float64(v), 'b', 0, 32) } // fmt_c64 formats a complex64 according to the verb. func (f *fmt) fmt_c64(v complex64, verb rune) { f.buf.WriteByte('(') r := real(v) oldPlus := f.plus for i := 0; ; i++ { switch verb { case 'e': f.fmt_e32(r) case 'E': f.fmt_E32(r) case 'f': f.fmt_f32(r) case 'g': f.fmt_g32(r) case 'G': f.fmt_G32(r) } if i != 0 { break } f.plus = true r = imag(v) } f.plus = oldPlus f.buf.Write(irparenBytes) } // fmt_c128 formats a complex128 according to the verb. func (f *fmt) fmt_c128(v complex128, verb rune) { f.buf.WriteByte('(') r := real(v) oldPlus := f.plus for i := 0; ; i++ { switch verb { case 'e': f.fmt_e64(r) case 'E': f.fmt_E64(r) case 'f': f.fmt_f64(r) case 'g': f.fmt_g64(r) case 'G': f.fmt_G64(r) } if i != 0 { break } f.plus = true r = imag(v) } f.plus = oldPlus f.buf.Write(irparenBytes) } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/fmt/print.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fmt import ( "errors" "io" "os" "reflect" "sync" "unicode/utf8" ) // Some constants in the form of bytes, to avoid string overhead. // Needlessly fastidious, I suppose. var ( commaSpaceBytes = []byte(", ") nilAngleBytes = []byte("") nilParenBytes = []byte("(nil)") nilBytes = []byte("nil") mapBytes = []byte("map[") missingBytes = []byte("(MISSING)") panicBytes = []byte("(PANIC=") extraBytes = []byte("%!(EXTRA ") irparenBytes = []byte("i)") bytesBytes = []byte("[]byte{") badWidthBytes = []byte("%!(BADWIDTH)") badPrecBytes = []byte("%!(BADPREC)") noVerbBytes = []byte("%!(NOVERB)") ) // State represents the printer state passed to custom formatters. // It provides access to the io.Writer interface plus information about // the flags and options for the operand's format specifier. type State interface { // Write is the function to call to emit formatted output to be printed. Write(b []byte) (ret int, err error) // Width returns the value of the width option and whether it has been set. Width() (wid int, ok bool) // Precision returns the value of the precision option and whether it has been set. Precision() (prec int, ok bool) // Flag returns whether the flag c, a character, has been set. Flag(c int) bool } // Formatter is the interface implemented by values with a custom formatter. // The implementation of Format may call Sprint(f) or Fprint(f) etc. // to generate its output. type Formatter interface { Format(f State, c rune) } // Stringer is implemented by any value that has a String method, // which defines the ``native'' format for that value. // The String method is used to print values passed as an operand // to any format that accepts a string or to an unformatted printer // such as Print. type Stringer interface { String() string } // GoStringer is implemented by any value that has a GoString method, // which defines the Go syntax for that value. // The GoString method is used to print values passed as an operand // to a %#v format. type GoStringer interface { GoString() string } // Use simple []byte instead of bytes.Buffer to avoid large dependency. type buffer []byte func (b *buffer) Write(p []byte) (n int, err error) { *b = append(*b, p...) return len(p), nil } func (b *buffer) WriteString(s string) (n int, err error) { *b = append(*b, s...) return len(s), nil } func (b *buffer) WriteByte(c byte) error { *b = append(*b, c) return nil } func (bp *buffer) WriteRune(r rune) error { if r < utf8.RuneSelf { *bp = append(*bp, byte(r)) return nil } b := *bp n := len(b) for n+utf8.UTFMax > cap(b) { b = append(b, 0) } w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r) *bp = b[:n+w] return nil } type pp struct { n int panicking bool erroring bool // printing an error condition buf buffer // field holds the current item, as an interface{}. field interface{} // value holds the current item, as a reflect.Value, and will be // the zero Value if the item has not been reflected. value reflect.Value runeBuf [utf8.UTFMax]byte fmt fmt } // A cache holds a set of reusable objects. // The slice is a stack (LIFO). // If more are needed, the cache creates them by calling new. type cache struct { mu sync.Mutex saved []interface{} new func() interface{} } func (c *cache) put(x interface{}) { c.mu.Lock() if len(c.saved) < cap(c.saved) { c.saved = append(c.saved, x) } c.mu.Unlock() } func (c *cache) get() interface{} { c.mu.Lock() n := len(c.saved) if n == 0 { c.mu.Unlock() return c.new() } x := c.saved[n-1] c.saved = c.saved[0 : n-1] c.mu.Unlock() return x } func newCache(f func() interface{}) *cache { return &cache{saved: make([]interface{}, 0, 100), new: f} } var ppFree = newCache(func() interface{} { return new(pp) }) // newPrinter allocates a new pp struct or grab a cached one. func newPrinter() *pp { p := ppFree.get().(*pp) p.panicking = false p.erroring = false p.fmt.init(&p.buf) return p } // free saves used pp structs in ppFree; avoids an allocation per invocation. func (p *pp) free() { // Don't hold on to pp structs with large buffers. if cap(p.buf) > 1024 { return } p.buf = p.buf[:0] p.field = nil p.value = reflect.Value{} ppFree.put(p) } func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent } func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent } func (p *pp) Flag(b int) bool { switch b { case '-': return p.fmt.minus case '+': return p.fmt.plus case '#': return p.fmt.sharp case ' ': return p.fmt.space case '0': return p.fmt.zero } return false } func (p *pp) add(c rune) { p.buf.WriteRune(c) } // Implement Write so we can call Fprintf on a pp (through State), for // recursive use in custom verbs. func (p *pp) Write(b []byte) (ret int, err error) { return p.buf.Write(b) } // These routines end in 'f' and take a format string. // Fprintf formats according to a format specifier and writes to w. // It returns the number of bytes written and any write error encountered. func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { p := newPrinter() p.doPrintf(format, a) n64, err := w.Write(p.buf) p.free() return int(n64), err } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func Printf(format string, a ...interface{}) (n int, err error) { return Fprintf(os.Stdout, format, a...) } // Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...interface{}) string { p := newPrinter() p.doPrintf(format, a) s := string(p.buf) p.free() return s } // Errorf formats according to a format specifier and returns the string // as a value that satisfies error. func Errorf(format string, a ...interface{}) error { return errors.New(Sprintf(format, a...)) } // These routines do not take a format string // Fprint formats using the default formats for its operands and writes to w. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func Fprint(w io.Writer, a ...interface{}) (n int, err error) { p := newPrinter() p.doPrint(a, false, false) n64, err := w.Write(p.buf) p.free() return int(n64), err } // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func Print(a ...interface{}) (n int, err error) { return Fprint(os.Stdout, a...) } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func Sprint(a ...interface{}) string { p := newPrinter() p.doPrint(a, false, false) s := string(p.buf) p.free() return s } // These routines end in 'ln', do not take a format string, // always add spaces between operands, and add a newline // after the last operand. // Fprintln formats using the default formats for its operands and writes to w. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { p := newPrinter() p.doPrint(a, true, true) n64, err := w.Write(p.buf) p.free() return int(n64), err } // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func Println(a ...interface{}) (n int, err error) { return Fprintln(os.Stdout, a...) } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func Sprintln(a ...interface{}) string { p := newPrinter() p.doPrint(a, true, true) s := string(p.buf) p.free() return s } // getField gets the i'th arg of the struct value. // If the arg itself is an interface, return a value for // the thing inside the interface, not the interface itself. func getField(v reflect.Value, i int) reflect.Value { val := v.Field(i) if val.Kind() == reflect.Interface && !val.IsNil() { val = val.Elem() } return val } // parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present. func parsenum(s string, start, end int) (num int, isnum bool, newi int) { if start >= end { return 0, false, end } for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ { num = num*10 + int(s[newi]-'0') isnum = true } return } func (p *pp) unknownType(v interface{}) { if v == nil { p.buf.Write(nilAngleBytes) return } p.buf.WriteByte('?') p.buf.WriteString(reflect.TypeOf(v).String()) p.buf.WriteByte('?') } func (p *pp) badVerb(verb rune) { p.erroring = true p.add('%') p.add('!') p.add(verb) p.add('(') switch { case p.field != nil: p.buf.WriteString(reflect.TypeOf(p.field).String()) p.add('=') p.printField(p.field, 'v', false, false, 0) case p.value.IsValid(): p.buf.WriteString(p.value.Type().String()) p.add('=') p.printValue(p.value, 'v', false, false, 0) default: p.buf.Write(nilAngleBytes) } p.add(')') p.erroring = false } func (p *pp) fmtBool(v bool, verb rune) { switch verb { case 't', 'v': p.fmt.fmt_boolean(v) default: p.badVerb(verb) } } // fmtC formats a rune for the 'c' format. func (p *pp) fmtC(c int64) { r := rune(c) // Check for overflow. if int64(r) != c { r = utf8.RuneError } w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r) p.fmt.pad(p.runeBuf[0:w]) } func (p *pp) fmtInt64(v int64, verb rune) { switch verb { case 'b': p.fmt.integer(v, 2, signed, ldigits) case 'c': p.fmtC(v) case 'd', 'v': p.fmt.integer(v, 10, signed, ldigits) case 'o': p.fmt.integer(v, 8, signed, ldigits) case 'q': if 0 <= v && v <= utf8.MaxRune { p.fmt.fmt_qc(v) } else { p.badVerb(verb) } case 'x': p.fmt.integer(v, 16, signed, ldigits) case 'U': p.fmtUnicode(v) case 'X': p.fmt.integer(v, 16, signed, udigits) default: p.badVerb(verb) } } // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or // not, as requested, by temporarily setting the sharp flag. func (p *pp) fmt0x64(v uint64, leading0x bool) { sharp := p.fmt.sharp p.fmt.sharp = leading0x p.fmt.integer(int64(v), 16, unsigned, ldigits) p.fmt.sharp = sharp } // fmtUnicode formats a uint64 in U+1234 form by // temporarily turning on the unicode flag and tweaking the precision. func (p *pp) fmtUnicode(v int64) { precPresent := p.fmt.precPresent sharp := p.fmt.sharp p.fmt.sharp = false prec := p.fmt.prec if !precPresent { // If prec is already set, leave it alone; otherwise 4 is minimum. p.fmt.prec = 4 p.fmt.precPresent = true } p.fmt.unicode = true // turn on U+ p.fmt.uniQuote = sharp p.fmt.integer(int64(v), 16, unsigned, udigits) p.fmt.unicode = false p.fmt.uniQuote = false p.fmt.prec = prec p.fmt.precPresent = precPresent p.fmt.sharp = sharp } func (p *pp) fmtUint64(v uint64, verb rune, goSyntax bool) { switch verb { case 'b': p.fmt.integer(int64(v), 2, unsigned, ldigits) case 'c': p.fmtC(int64(v)) case 'd': p.fmt.integer(int64(v), 10, unsigned, ldigits) case 'v': if goSyntax { p.fmt0x64(v, true) } else { p.fmt.integer(int64(v), 10, unsigned, ldigits) } case 'o': p.fmt.integer(int64(v), 8, unsigned, ldigits) case 'q': if 0 <= v && v <= utf8.MaxRune { p.fmt.fmt_qc(int64(v)) } else { p.badVerb(verb) } case 'x': p.fmt.integer(int64(v), 16, unsigned, ldigits) case 'X': p.fmt.integer(int64(v), 16, unsigned, udigits) case 'U': p.fmtUnicode(int64(v)) default: p.badVerb(verb) } } func (p *pp) fmtFloat32(v float32, verb rune) { switch verb { case 'b': p.fmt.fmt_fb32(v) case 'e': p.fmt.fmt_e32(v) case 'E': p.fmt.fmt_E32(v) case 'f': p.fmt.fmt_f32(v) case 'g', 'v': p.fmt.fmt_g32(v) case 'G': p.fmt.fmt_G32(v) default: p.badVerb(verb) } } func (p *pp) fmtFloat64(v float64, verb rune) { switch verb { case 'b': p.fmt.fmt_fb64(v) case 'e': p.fmt.fmt_e64(v) case 'E': p.fmt.fmt_E64(v) case 'f': p.fmt.fmt_f64(v) case 'g', 'v': p.fmt.fmt_g64(v) case 'G': p.fmt.fmt_G64(v) default: p.badVerb(verb) } } func (p *pp) fmtComplex64(v complex64, verb rune) { switch verb { case 'e', 'E', 'f', 'F', 'g', 'G': p.fmt.fmt_c64(v, verb) case 'v': p.fmt.fmt_c64(v, 'g') default: p.badVerb(verb) } } func (p *pp) fmtComplex128(v complex128, verb rune) { switch verb { case 'e', 'E', 'f', 'F', 'g', 'G': p.fmt.fmt_c128(v, verb) case 'v': p.fmt.fmt_c128(v, 'g') default: p.badVerb(verb) } } func (p *pp) fmtString(v string, verb rune, goSyntax bool) { switch verb { case 'v': if goSyntax { p.fmt.fmt_q(v) } else { p.fmt.fmt_s(v) } case 's': p.fmt.fmt_s(v) case 'x': p.fmt.fmt_sx(v, ldigits) case 'X': p.fmt.fmt_sx(v, udigits) case 'q': p.fmt.fmt_q(v) default: p.badVerb(verb) } } func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, typ reflect.Type, depth int) { if verb == 'v' || verb == 'd' { if goSyntax { if typ == nil { p.buf.Write(bytesBytes) } else { p.buf.WriteString(typ.String()) p.buf.WriteByte('{') } } else { p.buf.WriteByte('[') } for i, c := range v { if i > 0 { if goSyntax { p.buf.Write(commaSpaceBytes) } else { p.buf.WriteByte(' ') } } p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1) } if goSyntax { p.buf.WriteByte('}') } else { p.buf.WriteByte(']') } return } switch verb { case 's': p.fmt.fmt_s(string(v)) case 'x': p.fmt.fmt_bx(v, ldigits) case 'X': p.fmt.fmt_bx(v, udigits) case 'q': p.fmt.fmt_q(string(v)) default: p.badVerb(verb) } } func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) { use0x64 := true switch verb { case 'p', 'v': // ok case 'b', 'd', 'o', 'x', 'X': use0x64 = false // ok default: p.badVerb(verb) return } var u uintptr switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: u = value.Pointer() default: p.badVerb(verb) return } if goSyntax { p.add('(') p.buf.WriteString(value.Type().String()) p.add(')') p.add('(') if u == 0 { p.buf.Write(nilBytes) } else { p.fmt0x64(uint64(u), true) } p.add(')') } else if verb == 'v' && u == 0 { p.buf.Write(nilAngleBytes) } else { if use0x64 { p.fmt0x64(uint64(u), !p.fmt.sharp) } else { p.fmtUint64(uint64(u), verb, false) } } } var ( intBits = reflect.TypeOf(0).Bits() floatBits = reflect.TypeOf(0.0).Bits() complexBits = reflect.TypeOf(1i).Bits() uintptrBits = reflect.TypeOf(uintptr(0)).Bits() ) func (p *pp) catchPanic(field interface{}, verb rune) { if err := recover(); err != nil { // If it's a nil pointer, just say "". The likeliest causes are a // Stringer that fails to guard against nil or a nil pointer for a // value receiver, and in either case, "" is a nice result. if v := reflect.ValueOf(field); v.Kind() == reflect.Ptr && v.IsNil() { p.buf.Write(nilAngleBytes) return } // Otherwise print a concise panic message. Most of the time the panic // value will print itself nicely. if p.panicking { // Nested panics; the recursion in printField cannot succeed. panic(err) } p.buf.WriteByte('%') p.add(verb) p.buf.Write(panicBytes) p.panicking = true p.printField(err, 'v', false, false, 0) p.panicking = false p.buf.WriteByte(')') } } func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString, handled bool) { if p.erroring { return } // Is it a Formatter? if formatter, ok := p.field.(Formatter); ok { handled = true wasString = false defer p.catchPanic(p.field, verb) formatter.Format(p, verb) return } // Must not touch flags before Formatter looks at them. if plus { p.fmt.plus = false } // If we're doing Go syntax and the field knows how to supply it, take care of it now. if goSyntax { p.fmt.sharp = false if stringer, ok := p.field.(GoStringer); ok { wasString = false handled = true defer p.catchPanic(p.field, verb) // Print the result of GoString unadorned. p.fmtString(stringer.GoString(), 's', false) return } } else { // If a string is acceptable according to the format, see if // the value satisfies one of the string-valued interfaces. // Println etc. set verb to %v, which is "stringable". switch verb { case 'v', 's', 'x', 'X', 'q': // Is it an error or Stringer? // The duplication in the bodies is necessary: // setting wasString and handled, and deferring catchPanic, // must happen before calling the method. switch v := p.field.(type) { case error: wasString = false handled = true defer p.catchPanic(p.field, verb) p.printField(v.Error(), verb, plus, false, depth) return case Stringer: wasString = false handled = true defer p.catchPanic(p.field, verb) p.printField(v.String(), verb, plus, false, depth) return } } } handled = false return } func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) { p.field = field p.value = reflect.Value{} if field == nil { if verb == 'T' || verb == 'v' { p.fmt.pad(nilAngleBytes) } else { p.badVerb(verb) } return false } // Special processing considerations. // %T (the value's type) and %p (its address) are special; we always do them first. switch verb { case 'T': p.printField(reflect.TypeOf(field).String(), 's', false, false, 0) return false case 'p': p.fmtPointer(reflect.ValueOf(field), verb, goSyntax) return false } // Clear flags for base formatters. // handleMethods needs them, so we must restore them later. // We could call handleMethods here and avoid this work, but // handleMethods is expensive enough to be worth delaying. oldPlus := p.fmt.plus oldSharp := p.fmt.sharp if plus { p.fmt.plus = false } if goSyntax { p.fmt.sharp = false } // Some types can be done without reflection. switch f := field.(type) { case bool: p.fmtBool(f, verb) case float32: p.fmtFloat32(f, verb) case float64: p.fmtFloat64(f, verb) case complex64: p.fmtComplex64(complex64(f), verb) case complex128: p.fmtComplex128(f, verb) case int: p.fmtInt64(int64(f), verb) case int8: p.fmtInt64(int64(f), verb) case int16: p.fmtInt64(int64(f), verb) case int32: p.fmtInt64(int64(f), verb) case int64: p.fmtInt64(f, verb) case uint: p.fmtUint64(uint64(f), verb, goSyntax) case uint8: p.fmtUint64(uint64(f), verb, goSyntax) case uint16: p.fmtUint64(uint64(f), verb, goSyntax) case uint32: p.fmtUint64(uint64(f), verb, goSyntax) case uint64: p.fmtUint64(f, verb, goSyntax) case uintptr: p.fmtUint64(uint64(f), verb, goSyntax) case string: p.fmtString(f, verb, goSyntax) wasString = verb == 's' || verb == 'v' case []byte: p.fmtBytes(f, verb, goSyntax, nil, depth) wasString = verb == 's' default: // Restore flags in case handleMethods finds a Formatter. p.fmt.plus = oldPlus p.fmt.sharp = oldSharp // If the type is not simple, it might have methods. if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { return wasString } // Need to use reflection return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth) } p.field = nil return } // printValue is like printField but starts with a reflect value, not an interface{} value. func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) { if !value.IsValid() { if verb == 'T' || verb == 'v' { p.buf.Write(nilAngleBytes) } else { p.badVerb(verb) } return false } // Special processing considerations. // %T (the value's type) and %p (its address) are special; we always do them first. switch verb { case 'T': p.printField(value.Type().String(), 's', false, false, 0) return false case 'p': p.fmtPointer(value, verb, goSyntax) return false } // Handle values with special methods. // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us. p.field = nil // Make sure it's cleared, for safety. if value.CanInterface() { p.field = value.Interface() } if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { return wasString } return p.printReflectValue(value, verb, plus, goSyntax, depth) } // printReflectValue is the fallback for both printField and printValue. // It uses reflect to print the value. func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) { oldValue := p.value p.value = value BigSwitch: switch f := value; f.Kind() { case reflect.Bool: p.fmtBool(f.Bool(), verb) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.fmtInt64(f.Int(), verb) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p.fmtUint64(uint64(f.Uint()), verb, goSyntax) case reflect.Float32, reflect.Float64: if f.Type().Size() == 4 { p.fmtFloat32(float32(f.Float()), verb) } else { p.fmtFloat64(float64(f.Float()), verb) } case reflect.Complex64, reflect.Complex128: if f.Type().Size() == 8 { p.fmtComplex64(complex64(f.Complex()), verb) } else { p.fmtComplex128(complex128(f.Complex()), verb) } case reflect.String: p.fmtString(f.String(), verb, goSyntax) case reflect.Map: if goSyntax { p.buf.WriteString(f.Type().String()) if f.IsNil() { p.buf.WriteString("(nil)") break } p.buf.WriteByte('{') } else { p.buf.Write(mapBytes) } keys := f.MapKeys() for i, key := range keys { if i > 0 { if goSyntax { p.buf.Write(commaSpaceBytes) } else { p.buf.WriteByte(' ') } } p.printValue(key, verb, plus, goSyntax, depth+1) p.buf.WriteByte(':') p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1) } if goSyntax { p.buf.WriteByte('}') } else { p.buf.WriteByte(']') } case reflect.Struct: if goSyntax { p.buf.WriteString(value.Type().String()) } p.add('{') v := f t := v.Type() for i := 0; i < v.NumField(); i++ { if i > 0 { if goSyntax { p.buf.Write(commaSpaceBytes) } else { p.buf.WriteByte(' ') } } if plus || goSyntax { if f := t.Field(i); f.Name != "" { p.buf.WriteString(f.Name) p.buf.WriteByte(':') } } p.printValue(getField(v, i), verb, plus, goSyntax, depth+1) } p.buf.WriteByte('}') case reflect.Interface: value := f.Elem() if !value.IsValid() { if goSyntax { p.buf.WriteString(f.Type().String()) p.buf.Write(nilParenBytes) } else { p.buf.Write(nilAngleBytes) } } else { wasString = p.printValue(value, verb, plus, goSyntax, depth+1) } case reflect.Array, reflect.Slice: // Byte slices are special. if typ := f.Type(); typ.Elem().Kind() == reflect.Uint8 { var bytes []byte if f.Kind() == reflect.Slice { bytes = f.Bytes() } else if f.CanAddr() { bytes = f.Slice(0, f.Len()).Bytes() } else { // We have an array, but we cannot Slice() a non-addressable array, // so we build a slice by hand. This is a rare case but it would be nice // if reflection could help a little more. bytes = make([]byte, f.Len()) for i := range bytes { bytes[i] = byte(f.Index(i).Uint()) } } p.fmtBytes(bytes, verb, goSyntax, typ, depth) wasString = verb == 's' break } if goSyntax { p.buf.WriteString(value.Type().String()) if f.Kind() == reflect.Slice && f.IsNil() { p.buf.WriteString("(nil)") break } p.buf.WriteByte('{') } else { p.buf.WriteByte('[') } for i := 0; i < f.Len(); i++ { if i > 0 { if goSyntax { p.buf.Write(commaSpaceBytes) } else { p.buf.WriteByte(' ') } } p.printValue(f.Index(i), verb, plus, goSyntax, depth+1) } if goSyntax { p.buf.WriteByte('}') } else { p.buf.WriteByte(']') } case reflect.Ptr: v := f.Pointer() // pointer to array or slice or struct? ok at top level // but not embedded (avoid loops) if v != 0 && depth == 0 { switch a := f.Elem(); a.Kind() { case reflect.Array, reflect.Slice: p.buf.WriteByte('&') p.printValue(a, verb, plus, goSyntax, depth+1) break BigSwitch case reflect.Struct: p.buf.WriteByte('&') p.printValue(a, verb, plus, goSyntax, depth+1) break BigSwitch } } fallthrough case reflect.Chan, reflect.Func, reflect.UnsafePointer: p.fmtPointer(value, verb, goSyntax) default: p.unknownType(f) } p.value = oldValue return wasString } // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int. func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) { newi, newfieldnum = end, fieldnum if i < end && fieldnum < len(a) { num, isInt = a[fieldnum].(int) newi, newfieldnum = i+1, fieldnum+1 } return } func (p *pp) doPrintf(format string, a []interface{}) { end := len(format) fieldnum := 0 // we process one field per non-trivial format for i := 0; i < end; { lasti := i for i < end && format[i] != '%' { i++ } if i > lasti { p.buf.WriteString(format[lasti:i]) } if i >= end { // done processing format string break } // Process one verb i++ // flags and widths p.fmt.clearflags() F: for ; i < end; i++ { switch format[i] { case '#': p.fmt.sharp = true case '0': p.fmt.zero = true case '+': p.fmt.plus = true case '-': p.fmt.minus = true case ' ': p.fmt.space = true default: break F } } // do we have width? if i < end && format[i] == '*' { p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum) if !p.fmt.widPresent { p.buf.Write(badWidthBytes) } } else { p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end) } // do we have precision? if i+1 < end && format[i] == '.' { if format[i+1] == '*' { p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum) if !p.fmt.precPresent { p.buf.Write(badPrecBytes) } } else { p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end) if !p.fmt.precPresent { p.fmt.prec = 0 p.fmt.precPresent = true } } } if i >= end { p.buf.Write(noVerbBytes) continue } c, w := utf8.DecodeRuneInString(format[i:]) i += w // percent is special - absorbs no operand if c == '%' { p.buf.WriteByte('%') // We ignore width and prec. continue } if fieldnum >= len(a) { // out of operands p.buf.WriteByte('%') p.add(c) p.buf.Write(missingBytes) continue } field := a[fieldnum] fieldnum++ goSyntax := c == 'v' && p.fmt.sharp plus := c == 'v' && p.fmt.plus p.printField(field, c, plus, goSyntax, 0) } if fieldnum < len(a) { p.buf.Write(extraBytes) for ; fieldnum < len(a); fieldnum++ { field := a[fieldnum] if field != nil { p.buf.WriteString(reflect.TypeOf(field).String()) p.buf.WriteByte('=') } p.printField(field, 'v', false, false, 0) if fieldnum+1 < len(a) { p.buf.Write(commaSpaceBytes) } } p.buf.WriteByte(')') } } func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) { prevString := false for fieldnum := 0; fieldnum < len(a); fieldnum++ { p.fmt.clearflags() // always add spaces if we're doing Println field := a[fieldnum] if fieldnum > 0 { isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String if addspace || !isString && !prevString { p.buf.WriteByte(' ') } } prevString = p.printField(field, 'v', false, false, 0) } if addnewline { p.buf.WriteByte('\n') } } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/fmt/scan.go ================================================ // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fmt import ( "errors" "io" "math" "os" "reflect" "strconv" "unicode/utf8" ) // runeUnreader is the interface to something that can unread runes. // If the object provided to Scan does not satisfy this interface, // a local buffer will be used to back up the input, but its contents // will be lost when Scan returns. type runeUnreader interface { UnreadRune() error } // ScanState represents the scanner state passed to custom scanners. // Scanners may do rune-at-a-time scanning or ask the ScanState // to discover the next space-delimited token. type ScanState interface { // ReadRune reads the next rune (Unicode code point) from the input. // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will // return EOF after returning the first '\n' or when reading beyond // the specified width. ReadRune() (r rune, size int, err error) // UnreadRune causes the next call to ReadRune to return the same rune. UnreadRune() error // SkipSpace skips space in the input. Newlines are treated as space // unless the scan operation is Scanln, Fscanln or Sscanln, in which case // a newline is treated as EOF. SkipSpace() // Token skips space in the input if skipSpace is true, then returns the // run of Unicode code points c satisfying f(c). If f is nil, // !unicode.IsSpace(c) is used; that is, the token will hold non-space // characters. Newlines are treated as space unless the scan operation // is Scanln, Fscanln or Sscanln, in which case a newline is treated as // EOF. The returned slice points to shared data that may be overwritten // by the next call to Token, a call to a Scan function using the ScanState // as input, or when the calling Scan method returns. Token(skipSpace bool, f func(rune) bool) (token []byte, err error) // Width returns the value of the width option and whether it has been set. // The unit is Unicode code points. Width() (wid int, ok bool) // Because ReadRune is implemented by the interface, Read should never be // called by the scanning routines and a valid implementation of // ScanState may choose always to return an error from Read. Read(buf []byte) (n int, err error) } // Scanner is implemented by any value that has a Scan method, which scans // the input for the representation of a value and stores the result in the // receiver, which must be a pointer to be useful. The Scan method is called // for any argument to Scan, Scanf, or Scanln that implements it. type Scanner interface { Scan(state ScanState, verb rune) error } // Scan scans text read from standard input, storing successive // space-separated values into successive arguments. Newlines count // as space. It returns the number of items successfully scanned. // If that is less than the number of arguments, err will report why. func Scan(a ...interface{}) (n int, err error) { return Fscan(os.Stdin, a...) } // Scanln is similar to Scan, but stops scanning at a newline and // after the final item there must be a newline or EOF. func Scanln(a ...interface{}) (n int, err error) { return Fscanln(os.Stdin, a...) } // Scanf scans text read from standard input, storing successive // space-separated values into successive arguments as determined by // the format. It returns the number of items successfully scanned. func Scanf(format string, a ...interface{}) (n int, err error) { return Fscanf(os.Stdin, format, a...) } type stringReader string func (r *stringReader) Read(b []byte) (n int, err error) { n = copy(b, *r) *r = (*r)[n:] if n == 0 { err = io.EOF } return } // Sscan scans the argument string, storing successive space-separated // values into successive arguments. Newlines count as space. It // returns the number of items successfully scanned. If that is less // than the number of arguments, err will report why. func Sscan(str string, a ...interface{}) (n int, err error) { return Fscan((*stringReader)(&str), a...) } // Sscanln is similar to Sscan, but stops scanning at a newline and // after the final item there must be a newline or EOF. func Sscanln(str string, a ...interface{}) (n int, err error) { return Fscanln((*stringReader)(&str), a...) } // Sscanf scans the argument string, storing successive space-separated // values into successive arguments as determined by the format. It // returns the number of items successfully parsed. func Sscanf(str string, format string, a ...interface{}) (n int, err error) { return Fscanf((*stringReader)(&str), format, a...) } // Fscan scans text read from r, storing successive space-separated // values into successive arguments. Newlines count as space. It // returns the number of items successfully scanned. If that is less // than the number of arguments, err will report why. func Fscan(r io.Reader, a ...interface{}) (n int, err error) { s, old := newScanState(r, true, false) n, err = s.doScan(a) s.free(old) return } // Fscanln is similar to Fscan, but stops scanning at a newline and // after the final item there must be a newline or EOF. func Fscanln(r io.Reader, a ...interface{}) (n int, err error) { s, old := newScanState(r, false, true) n, err = s.doScan(a) s.free(old) return } // Fscanf scans text read from r, storing successive space-separated // values into successive arguments as determined by the format. It // returns the number of items successfully parsed. func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) { s, old := newScanState(r, false, false) n, err = s.doScanf(format, a) s.free(old) return } // scanError represents an error generated by the scanning software. // It's used as a unique signature to identify such errors when recovering. type scanError struct { err error } const eof = -1 // ss is the internal implementation of ScanState. type ss struct { rr io.RuneReader // where to read input buf buffer // token accumulator peekRune rune // one-rune lookahead prevRune rune // last rune returned by ReadRune count int // runes consumed so far. atEOF bool // already read EOF ssave } // ssave holds the parts of ss that need to be // saved and restored on recursive scans. type ssave struct { validSave bool // is or was a part of an actual ss. nlIsEnd bool // whether newline terminates scan nlIsSpace bool // whether newline counts as white space fieldLimit int // max value of ss.count for this field; fieldLimit <= limit limit int // max value of ss.count. maxWid int // width of this field. } // The Read method is only in ScanState so that ScanState // satisfies io.Reader. It will never be called when used as // intended, so there is no need to make it actually work. func (s *ss) Read(buf []byte) (n int, err error) { return 0, errors.New("ScanState's Read should not be called. Use ReadRune") } func (s *ss) ReadRune() (r rune, size int, err error) { if s.peekRune >= 0 { s.count++ r = s.peekRune size = utf8.RuneLen(r) s.prevRune = r s.peekRune = -1 return } if s.atEOF || s.nlIsEnd && s.prevRune == '\n' || s.count >= s.fieldLimit { err = io.EOF return } r, size, err = s.rr.ReadRune() if err == nil { s.count++ s.prevRune = r } else if err == io.EOF { s.atEOF = true } return } func (s *ss) Width() (wid int, ok bool) { if s.maxWid == hugeWid { return 0, false } return s.maxWid, true } // The public method returns an error; this private one panics. // If getRune reaches EOF, the return value is EOF (-1). func (s *ss) getRune() (r rune) { r, _, err := s.ReadRune() if err != nil { if err == io.EOF { return eof } s.error(err) } return } // mustReadRune turns io.EOF into a panic(io.ErrUnexpectedEOF). // It is called in cases such as string scanning where an EOF is a // syntax error. func (s *ss) mustReadRune() (r rune) { r = s.getRune() if r == eof { s.error(io.ErrUnexpectedEOF) } return } func (s *ss) UnreadRune() error { if u, ok := s.rr.(runeUnreader); ok { u.UnreadRune() } else { s.peekRune = s.prevRune } s.prevRune = -1 s.count-- return nil } func (s *ss) error(err error) { panic(scanError{err}) } func (s *ss) errorString(err string) { panic(scanError{errors.New(err)}) } func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) { defer func() { if e := recover(); e != nil { if se, ok := e.(scanError); ok { err = se.err } else { panic(e) } } }() if f == nil { f = notSpace } s.buf = s.buf[:0] tok = s.token(skipSpace, f) return } // space is a copy of the unicode.White_Space ranges, // to avoid depending on package unicode. var space = [][2]uint16{ {0x0009, 0x000d}, {0x0020, 0x0020}, {0x0085, 0x0085}, {0x00a0, 0x00a0}, {0x1680, 0x1680}, {0x180e, 0x180e}, {0x2000, 0x200a}, {0x2028, 0x2029}, {0x202f, 0x202f}, {0x205f, 0x205f}, {0x3000, 0x3000}, } func isSpace(r rune) bool { if r >= 1<<16 { return false } rx := uint16(r) for _, rng := range space { if rx < rng[0] { return false } if rx <= rng[1] { return true } } return false } // notSpace is the default scanning function used in Token. func notSpace(r rune) bool { return !isSpace(r) } // SkipSpace provides Scan methods the ability to skip space and newline // characters in keeping with the current scanning mode set by format strings // and Scan/Scanln. func (s *ss) SkipSpace() { s.skipSpace(false) } // readRune is a structure to enable reading UTF-8 encoded code points // from an io.Reader. It is used if the Reader given to the scanner does // not already implement io.RuneReader. type readRune struct { reader io.Reader buf [utf8.UTFMax]byte // used only inside ReadRune pending int // number of bytes in pendBuf; only >0 for bad UTF-8 pendBuf [utf8.UTFMax]byte // bytes left over } // readByte returns the next byte from the input, which may be // left over from a previous read if the UTF-8 was ill-formed. func (r *readRune) readByte() (b byte, err error) { if r.pending > 0 { b = r.pendBuf[0] copy(r.pendBuf[0:], r.pendBuf[1:]) r.pending-- return } n, err := io.ReadFull(r.reader, r.pendBuf[0:1]) if n != 1 { return 0, err } return r.pendBuf[0], err } // unread saves the bytes for the next read. func (r *readRune) unread(buf []byte) { copy(r.pendBuf[r.pending:], buf) r.pending += len(buf) } // ReadRune returns the next UTF-8 encoded code point from the // io.Reader inside r. func (r *readRune) ReadRune() (rr rune, size int, err error) { r.buf[0], err = r.readByte() if err != nil { return 0, 0, err } if r.buf[0] < utf8.RuneSelf { // fast check for common ASCII case rr = rune(r.buf[0]) return } var n int for n = 1; !utf8.FullRune(r.buf[0:n]); n++ { r.buf[n], err = r.readByte() if err != nil { if err == io.EOF { err = nil break } return } } rr, size = utf8.DecodeRune(r.buf[0:n]) if size < n { // an error r.unread(r.buf[size:n]) } return } var ssFree = newCache(func() interface{} { return new(ss) }) // newScanState allocates a new ss struct or grab a cached one. func newScanState(r io.Reader, nlIsSpace, nlIsEnd bool) (s *ss, old ssave) { // If the reader is a *ss, then we've got a recursive // call to Scan, so re-use the scan state. s, ok := r.(*ss) if ok { old = s.ssave s.limit = s.fieldLimit s.nlIsEnd = nlIsEnd || s.nlIsEnd s.nlIsSpace = nlIsSpace return } s = ssFree.get().(*ss) if rr, ok := r.(io.RuneReader); ok { s.rr = rr } else { s.rr = &readRune{reader: r} } s.nlIsSpace = nlIsSpace s.nlIsEnd = nlIsEnd s.prevRune = -1 s.peekRune = -1 s.atEOF = false s.limit = hugeWid s.fieldLimit = hugeWid s.maxWid = hugeWid s.validSave = true s.count = 0 return } // free saves used ss structs in ssFree; avoid an allocation per invocation. func (s *ss) free(old ssave) { // If it was used recursively, just restore the old state. if old.validSave { s.ssave = old return } // Don't hold on to ss structs with large buffers. if cap(s.buf) > 1024 { return } s.buf = s.buf[:0] s.rr = nil ssFree.put(s) } // skipSpace skips spaces and maybe newlines. func (s *ss) skipSpace(stopAtNewline bool) { for { r := s.getRune() if r == eof { return } if r == '\n' { if stopAtNewline { break } if s.nlIsSpace { continue } s.errorString("unexpected newline") return } if !isSpace(r) { s.UnreadRune() break } } } // token returns the next space-delimited string from the input. It // skips white space. For Scanln, it stops at newlines. For Scan, // newlines are treated as spaces. func (s *ss) token(skipSpace bool, f func(rune) bool) []byte { if skipSpace { s.skipSpace(false) } // read until white space or newline for { r := s.getRune() if r == eof { break } if !f(r) { s.UnreadRune() break } s.buf.WriteRune(r) } return s.buf } // typeError indicates that the type of the operand did not match the format func (s *ss) typeError(field interface{}, expected string) { s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String()) } var complexError = errors.New("syntax error scanning complex number") var boolError = errors.New("syntax error scanning boolean") func indexRune(s string, r rune) int { for i, c := range s { if c == r { return i } } return -1 } // consume reads the next rune in the input and reports whether it is in the ok string. // If accept is true, it puts the character into the input token. func (s *ss) consume(ok string, accept bool) bool { r := s.getRune() if r == eof { return false } if indexRune(ok, r) >= 0 { if accept { s.buf.WriteRune(r) } return true } if r != eof && accept { s.UnreadRune() } return false } // peek reports whether the next character is in the ok string, without consuming it. func (s *ss) peek(ok string) bool { r := s.getRune() if r != eof { s.UnreadRune() } return indexRune(ok, r) >= 0 } func (s *ss) notEOF() { // Guarantee there is data to be read. if r := s.getRune(); r == eof { panic(io.EOF) } s.UnreadRune() } // accept checks the next rune in the input. If it's a byte (sic) in the string, it puts it in the // buffer and returns true. Otherwise it return false. func (s *ss) accept(ok string) bool { return s.consume(ok, true) } // okVerb verifies that the verb is present in the list, setting s.err appropriately if not. func (s *ss) okVerb(verb rune, okVerbs, typ string) bool { for _, v := range okVerbs { if v == verb { return true } } s.errorString("bad verb %" + string(verb) + " for " + typ) return false } // scanBool returns the value of the boolean represented by the next token. func (s *ss) scanBool(verb rune) bool { s.skipSpace(false) s.notEOF() if !s.okVerb(verb, "tv", "boolean") { return false } // Syntax-checking a boolean is annoying. We're not fastidious about case. switch s.getRune() { case '0': return false case '1': return true case 't', 'T': if s.accept("rR") && (!s.accept("uU") || !s.accept("eE")) { s.error(boolError) } return true case 'f', 'F': if s.accept("aA") && (!s.accept("lL") || !s.accept("sS") || !s.accept("eE")) { s.error(boolError) } return false } return false } // Numerical elements const ( binaryDigits = "01" octalDigits = "01234567" decimalDigits = "0123456789" hexadecimalDigits = "0123456789aAbBcCdDeEfF" sign = "+-" period = "." exponent = "eEp" ) // getBase returns the numeric base represented by the verb and its digit string. func (s *ss) getBase(verb rune) (base int, digits string) { s.okVerb(verb, "bdoUxXv", "integer") // sets s.err base = 10 digits = decimalDigits switch verb { case 'b': base = 2 digits = binaryDigits case 'o': base = 8 digits = octalDigits case 'x', 'X', 'U': base = 16 digits = hexadecimalDigits } return } // scanNumber returns the numerical string with specified digits starting here. func (s *ss) scanNumber(digits string, haveDigits bool) string { if !haveDigits { s.notEOF() if !s.accept(digits) { s.errorString("expected integer") } } for s.accept(digits) { } return string(s.buf) } // scanRune returns the next rune value in the input. func (s *ss) scanRune(bitSize int) int64 { s.notEOF() r := int64(s.getRune()) n := uint(bitSize) x := (r << (64 - n)) >> (64 - n) if x != r { s.errorString("overflow on character value " + string(r)) } return r } // scanBasePrefix reports whether the integer begins with a 0 or 0x, // and returns the base, digit string, and whether a zero was found. // It is called only if the verb is %v. func (s *ss) scanBasePrefix() (base int, digits string, found bool) { if !s.peek("0") { return 10, decimalDigits, false } s.accept("0") found = true // We've put a digit into the token buffer. // Special cases for '0' && '0x' base, digits = 8, octalDigits if s.peek("xX") { s.consume("xX", false) base, digits = 16, hexadecimalDigits } return } // scanInt returns the value of the integer represented by the next // token, checking for overflow. Any error is stored in s.err. func (s *ss) scanInt(verb rune, bitSize int) int64 { if verb == 'c' { return s.scanRune(bitSize) } s.skipSpace(false) s.notEOF() base, digits := s.getBase(verb) haveDigits := false if verb == 'U' { if !s.consume("U", false) || !s.consume("+", false) { s.errorString("bad unicode format ") } } else { s.accept(sign) // If there's a sign, it will be left in the token buffer. if verb == 'v' { base, digits, haveDigits = s.scanBasePrefix() } } tok := s.scanNumber(digits, haveDigits) i, err := strconv.ParseInt(tok, base, 64) if err != nil { s.error(err) } n := uint(bitSize) x := (i << (64 - n)) >> (64 - n) if x != i { s.errorString("integer overflow on token " + tok) } return i } // scanUint returns the value of the unsigned integer represented // by the next token, checking for overflow. Any error is stored in s.err. func (s *ss) scanUint(verb rune, bitSize int) uint64 { if verb == 'c' { return uint64(s.scanRune(bitSize)) } s.skipSpace(false) s.notEOF() base, digits := s.getBase(verb) haveDigits := false if verb == 'U' { if !s.consume("U", false) || !s.consume("+", false) { s.errorString("bad unicode format ") } } else if verb == 'v' { base, digits, haveDigits = s.scanBasePrefix() } tok := s.scanNumber(digits, haveDigits) i, err := strconv.ParseUint(tok, base, 64) if err != nil { s.error(err) } n := uint(bitSize) x := (i << (64 - n)) >> (64 - n) if x != i { s.errorString("unsigned integer overflow on token " + tok) } return i } // floatToken returns the floating-point number starting here, no longer than swid // if the width is specified. It's not rigorous about syntax because it doesn't check that // we have at least some digits, but Atof will do that. func (s *ss) floatToken() string { s.buf = s.buf[:0] // NaN? if s.accept("nN") && s.accept("aA") && s.accept("nN") { return string(s.buf) } // leading sign? s.accept(sign) // Inf? if s.accept("iI") && s.accept("nN") && s.accept("fF") { return string(s.buf) } // digits? for s.accept(decimalDigits) { } // decimal point? if s.accept(period) { // fraction? for s.accept(decimalDigits) { } } // exponent? if s.accept(exponent) { // leading sign? s.accept(sign) // digits? for s.accept(decimalDigits) { } } return string(s.buf) } // complexTokens returns the real and imaginary parts of the complex number starting here. // The number might be parenthesized and has the format (N+Ni) where N is a floating-point // number and there are no spaces within. func (s *ss) complexTokens() (real, imag string) { // TODO: accept N and Ni independently? parens := s.accept("(") real = s.floatToken() s.buf = s.buf[:0] // Must now have a sign. if !s.accept("+-") { s.error(complexError) } // Sign is now in buffer imagSign := string(s.buf) imag = s.floatToken() if !s.accept("i") { s.error(complexError) } if parens && !s.accept(")") { s.error(complexError) } return real, imagSign + imag } // convertFloat converts the string to a float64value. func (s *ss) convertFloat(str string, n int) float64 { if p := indexRune(str, 'p'); p >= 0 { // Atof doesn't handle power-of-2 exponents, // but they're easy to evaluate. f, err := strconv.ParseFloat(str[:p], n) if err != nil { // Put full string into error. if e, ok := err.(*strconv.NumError); ok { e.Num = str } s.error(err) } n, err := strconv.Atoi(str[p+1:]) if err != nil { // Put full string into error. if e, ok := err.(*strconv.NumError); ok { e.Num = str } s.error(err) } return math.Ldexp(f, n) } f, err := strconv.ParseFloat(str, n) if err != nil { s.error(err) } return f } // convertComplex converts the next token to a complex128 value. // The atof argument is a type-specific reader for the underlying type. // If we're reading complex64, atof will parse float32s and convert them // to float64's to avoid reproducing this code for each complex type. func (s *ss) scanComplex(verb rune, n int) complex128 { if !s.okVerb(verb, floatVerbs, "complex") { return 0 } s.skipSpace(false) s.notEOF() sreal, simag := s.complexTokens() real := s.convertFloat(sreal, n/2) imag := s.convertFloat(simag, n/2) return complex(real, imag) } // convertString returns the string represented by the next input characters. // The format of the input is determined by the verb. func (s *ss) convertString(verb rune) (str string) { if !s.okVerb(verb, "svqx", "string") { return "" } s.skipSpace(false) s.notEOF() switch verb { case 'q': str = s.quotedString() case 'x': str = s.hexString() default: str = string(s.token(true, notSpace)) // %s and %v just return the next word } return } // quotedString returns the double- or back-quoted string represented by the next input characters. func (s *ss) quotedString() string { s.notEOF() quote := s.getRune() switch quote { case '`': // Back-quoted: Anything goes until EOF or back quote. for { r := s.mustReadRune() if r == quote { break } s.buf.WriteRune(r) } return string(s.buf) case '"': // Double-quoted: Include the quotes and let strconv.Unquote do the backslash escapes. s.buf.WriteRune(quote) for { r := s.mustReadRune() s.buf.WriteRune(r) if r == '\\' { // In a legal backslash escape, no matter how long, only the character // immediately after the escape can itself be a backslash or quote. // Thus we only need to protect the first character after the backslash. r := s.mustReadRune() s.buf.WriteRune(r) } else if r == '"' { break } } result, err := strconv.Unquote(string(s.buf)) if err != nil { s.error(err) } return result default: s.errorString("expected quoted string") } return "" } // hexDigit returns the value of the hexadecimal digit func (s *ss) hexDigit(d rune) int { digit := int(d) switch digit { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': return digit - '0' case 'a', 'b', 'c', 'd', 'e', 'f': return 10 + digit - 'a' case 'A', 'B', 'C', 'D', 'E', 'F': return 10 + digit - 'A' } s.errorString("Scan: illegal hex digit") return 0 } // hexByte returns the next hex-encoded (two-character) byte from the input. // There must be either two hexadecimal digits or a space character in the input. func (s *ss) hexByte() (b byte, ok bool) { rune1 := s.getRune() if rune1 == eof { return } if isSpace(rune1) { s.UnreadRune() return } rune2 := s.mustReadRune() return byte(s.hexDigit(rune1)<<4 | s.hexDigit(rune2)), true } // hexString returns the space-delimited hexpair-encoded string. func (s *ss) hexString() string { s.notEOF() for { b, ok := s.hexByte() if !ok { break } s.buf.WriteByte(b) } if len(s.buf) == 0 { s.errorString("Scan: no hex data for %x string") return "" } return string(s.buf) } const floatVerbs = "beEfFgGv" const hugeWid = 1 << 30 // scanOne scans a single value, deriving the scanner from the type of the argument. func (s *ss) scanOne(verb rune, field interface{}) { s.buf = s.buf[:0] var err error // If the parameter has its own Scan method, use that. if v, ok := field.(Scanner); ok { err = v.Scan(s, verb) if err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } s.error(err) } return } switch v := field.(type) { case *bool: *v = s.scanBool(verb) case *complex64: *v = complex64(s.scanComplex(verb, 64)) case *complex128: *v = s.scanComplex(verb, 128) case *int: *v = int(s.scanInt(verb, intBits)) case *int8: *v = int8(s.scanInt(verb, 8)) case *int16: *v = int16(s.scanInt(verb, 16)) case *int32: *v = int32(s.scanInt(verb, 32)) case *int64: *v = s.scanInt(verb, 64) case *uint: *v = uint(s.scanUint(verb, intBits)) case *uint8: *v = uint8(s.scanUint(verb, 8)) case *uint16: *v = uint16(s.scanUint(verb, 16)) case *uint32: *v = uint32(s.scanUint(verb, 32)) case *uint64: *v = s.scanUint(verb, 64) case *uintptr: *v = uintptr(s.scanUint(verb, uintptrBits)) // Floats are tricky because you want to scan in the precision of the result, not // scan in high precision and convert, in order to preserve the correct error condition. case *float32: if s.okVerb(verb, floatVerbs, "float32") { s.skipSpace(false) s.notEOF() *v = float32(s.convertFloat(s.floatToken(), 32)) } case *float64: if s.okVerb(verb, floatVerbs, "float64") { s.skipSpace(false) s.notEOF() *v = s.convertFloat(s.floatToken(), 64) } case *string: *v = s.convertString(verb) case *[]byte: // We scan to string and convert so we get a copy of the data. // If we scanned to bytes, the slice would point at the buffer. *v = []byte(s.convertString(verb)) default: val := reflect.ValueOf(v) ptr := val if ptr.Kind() != reflect.Ptr { s.errorString("Scan: type not a pointer: " + val.Type().String()) return } switch v := ptr.Elem(); v.Kind() { case reflect.Bool: v.SetBool(s.scanBool(verb)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v.SetInt(s.scanInt(verb, v.Type().Bits())) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: v.SetUint(s.scanUint(verb, v.Type().Bits())) case reflect.String: v.SetString(s.convertString(verb)) case reflect.Slice: // For now, can only handle (renamed) []byte. typ := v.Type() if typ.Elem().Kind() != reflect.Uint8 { s.errorString("Scan: can't handle type: " + val.Type().String()) } str := s.convertString(verb) v.Set(reflect.MakeSlice(typ, len(str), len(str))) for i := 0; i < len(str); i++ { v.Index(i).SetUint(uint64(str[i])) } case reflect.Float32, reflect.Float64: s.skipSpace(false) s.notEOF() v.SetFloat(s.convertFloat(s.floatToken(), v.Type().Bits())) case reflect.Complex64, reflect.Complex128: v.SetComplex(s.scanComplex(verb, v.Type().Bits())) default: s.errorString("Scan: can't handle type: " + val.Type().String()) } } } // errorHandler turns local panics into error returns. func errorHandler(errp *error) { if e := recover(); e != nil { if se, ok := e.(scanError); ok { // catch local error *errp = se.err } else if eof, ok := e.(error); ok && eof == io.EOF { // out of input *errp = eof } else { panic(e) } } } // doScan does the real work for scanning without a format string. func (s *ss) doScan(a []interface{}) (numProcessed int, err error) { defer errorHandler(&err) for _, field := range a { s.scanOne('v', field) numProcessed++ } // Check for newline if required. if !s.nlIsSpace { for { r := s.getRune() if r == '\n' || r == eof { break } if !isSpace(r) { s.errorString("Scan: expected newline") break } } } return } // advance determines whether the next characters in the input match // those of the format. It returns the number of bytes (sic) consumed // in the format. Newlines included, all runs of space characters in // either input or format behave as a single space. This routine also // handles the %% case. If the return value is zero, either format // starts with a % (with no following %) or the input is empty. // If it is negative, the input did not match the string. func (s *ss) advance(format string) (i int) { for i < len(format) { fmtc, w := utf8.DecodeRuneInString(format[i:]) if fmtc == '%' { // %% acts like a real percent nextc, _ := utf8.DecodeRuneInString(format[i+w:]) // will not match % if string is empty if nextc != '%' { return } i += w // skip the first % } sawSpace := false for isSpace(fmtc) && i < len(format) { sawSpace = true i += w fmtc, w = utf8.DecodeRuneInString(format[i:]) } if sawSpace { // There was space in the format, so there should be space (EOF) // in the input. inputc := s.getRune() if inputc == eof || inputc == '\n' { // If we've reached a newline, stop now; don't read ahead. return } if !isSpace(inputc) { // Space in format but not in input: error s.errorString("expected space in input to match format") } s.skipSpace(true) continue } inputc := s.mustReadRune() if fmtc != inputc { s.UnreadRune() return -1 } i += w } return } // doScanf does the real work when scanning with a format string. // At the moment, it handles only pointers to basic types. func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err error) { defer errorHandler(&err) end := len(format) - 1 // We process one item per non-trivial format for i := 0; i <= end; { w := s.advance(format[i:]) if w > 0 { i += w continue } // Either we failed to advance, we have a percent character, or we ran out of input. if format[i] != '%' { // Can't advance format. Why not? if w < 0 { s.errorString("input does not match format") } // Otherwise at EOF; "too many operands" error handled below break } i++ // % is one byte // do we have 20 (width)? var widPresent bool s.maxWid, widPresent, i = parsenum(format, i, end) if !widPresent { s.maxWid = hugeWid } s.fieldLimit = s.limit if f := s.count + s.maxWid; f < s.fieldLimit { s.fieldLimit = f } c, w := utf8.DecodeRuneInString(format[i:]) i += w if numProcessed >= len(a) { // out of operands s.errorString("too few operands for format %" + format[i-w:]) break } field := a[numProcessed] s.scanOne(c, field) numProcessed++ s.fieldLimit = s.limit } if numProcessed < len(a) { s.errorString("too many operands") } return } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/fmt/stringer_test.go ================================================ // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package fmt_test import ( . "fmt" "testing" ) type TI int type TI8 int8 type TI16 int16 type TI32 int32 type TI64 int64 type TU uint type TU8 uint8 type TU16 uint16 type TU32 uint32 type TU64 uint64 type TUI uintptr type TF float64 type TF32 float32 type TF64 float64 type TB bool type TS string func (v TI) String() string { return Sprintf("I: %d", int(v)) } func (v TI8) String() string { return Sprintf("I8: %d", int8(v)) } func (v TI16) String() string { return Sprintf("I16: %d", int16(v)) } func (v TI32) String() string { return Sprintf("I32: %d", int32(v)) } func (v TI64) String() string { return Sprintf("I64: %d", int64(v)) } func (v TU) String() string { return Sprintf("U: %d", uint(v)) } func (v TU8) String() string { return Sprintf("U8: %d", uint8(v)) } func (v TU16) String() string { return Sprintf("U16: %d", uint16(v)) } func (v TU32) String() string { return Sprintf("U32: %d", uint32(v)) } func (v TU64) String() string { return Sprintf("U64: %d", uint64(v)) } func (v TUI) String() string { return Sprintf("UI: %d", uintptr(v)) } func (v TF) String() string { return Sprintf("F: %f", float64(v)) } func (v TF32) String() string { return Sprintf("F32: %f", float32(v)) } func (v TF64) String() string { return Sprintf("F64: %f", float64(v)) } func (v TB) String() string { return Sprintf("B: %t", bool(v)) } func (v TS) String() string { return Sprintf("S: %q", string(v)) } func check(t *testing.T, got, want string) { if got != want { t.Error(got, "!=", want) } } func TestStringer(t *testing.T) { s := Sprintf("%v %v %v %v %v", TI(0), TI8(1), TI16(2), TI32(3), TI64(4)) check(t, s, "I: 0 I8: 1 I16: 2 I32: 3 I64: 4") s = Sprintf("%v %v %v %v %v %v", TU(5), TU8(6), TU16(7), TU32(8), TU64(9), TUI(10)) check(t, s, "U: 5 U8: 6 U16: 7 U32: 8 U64: 9 UI: 10") s = Sprintf("%v %v %v", TF(1.0), TF32(2.0), TF64(3.0)) check(t, s, "F: 1.000000 F32: 2.000000 F64: 3.000000") s = Sprintf("%v %v", TB(true), TS("x")) check(t, s, "B: true S: \"x\"") } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/go/ast/ast.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package ast declares the types used to represent syntax trees for Go // packages. // package ast import ( "go/token" "strings" "unicode" "unicode/utf8" ) // ---------------------------------------------------------------------------- // Interfaces // // There are 3 main classes of nodes: Expressions and type nodes, // statement nodes, and declaration nodes. The node names usually // match the corresponding Go spec production names to which they // correspond. The node fields correspond to the individual parts // of the respective productions. // // All nodes contain position information marking the beginning of // the corresponding source text segment; it is accessible via the // Pos accessor method. Nodes may contain additional position info // for language constructs where comments may be found between parts // of the construct (typically any larger, parenthesized subpart). // That position information is needed to properly position comments // when printing the construct. // All node types implement the Node interface. type Node interface { Pos() token.Pos // position of first character belonging to the node End() token.Pos // position of first character immediately after the node } // All expression nodes implement the Expr interface. type Expr interface { Node exprNode() } // All statement nodes implement the Stmt interface. type Stmt interface { Node stmtNode() } // All declaration nodes implement the Decl interface. type Decl interface { Node declNode() } // ---------------------------------------------------------------------------- // Comments // A Comment node represents a single //-style or /*-style comment. type Comment struct { Slash token.Pos // position of "/" starting the comment Text string // comment text (excluding '\n' for //-style comments) } func (c *Comment) Pos() token.Pos { return c.Slash } func (c *Comment) End() token.Pos { return token.Pos(int(c.Slash) + len(c.Text)) } // A CommentGroup represents a sequence of comments // with no other tokens and no empty lines between. // type CommentGroup struct { List []*Comment // len(List) > 0 } func (g *CommentGroup) Pos() token.Pos { return g.List[0].Pos() } func (g *CommentGroup) End() token.Pos { return g.List[len(g.List)-1].End() } func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' } func stripTrailingWhitespace(s string) string { i := len(s) for i > 0 && isWhitespace(s[i-1]) { i-- } return s[0:i] } // Text returns the text of the comment. // Comment markers (//, /*, and */), the first space of a line comment, and // leading and trailing empty lines are removed. Multiple empty lines are // reduced to one, and trailing space on lines is trimmed. Unless the result // is empty, it is newline-terminated. // func (g *CommentGroup) Text() string { if g == nil { return "" } comments := make([]string, len(g.List)) for i, c := range g.List { comments[i] = string(c.Text) } lines := make([]string, 0, 10) // most comments are less than 10 lines for _, c := range comments { // Remove comment markers. // The parser has given us exactly the comment text. switch c[1] { case '/': //-style comment (no newline at the end) c = c[2:] // strip first space - required for Example tests if len(c) > 0 && c[0] == ' ' { c = c[1:] } case '*': /*-style comment */ c = c[2 : len(c)-2] } // Split on newlines. cl := strings.Split(c, "\n") // Walk lines, stripping trailing white space and adding to list. for _, l := range cl { lines = append(lines, stripTrailingWhitespace(l)) } } // Remove leading blank lines; convert runs of // interior blank lines to a single blank line. n := 0 for _, line := range lines { if line != "" || n > 0 && lines[n-1] != "" { lines[n] = line n++ } } lines = lines[0:n] // Add final "" entry to get trailing newline from Join. if n > 0 && lines[n-1] != "" { lines = append(lines, "") } return strings.Join(lines, "\n") } // ---------------------------------------------------------------------------- // Expressions and types // A Field represents a Field declaration list in a struct type, // a method list in an interface type, or a parameter/result declaration // in a signature. // type Field struct { Doc *CommentGroup // associated documentation; or nil Names []*Ident // field/method/parameter names; or nil if anonymous field Type Expr // field/method/parameter type Tag *BasicLit // field tag; or nil Comment *CommentGroup // line comments; or nil } func (f *Field) Pos() token.Pos { if len(f.Names) > 0 { return f.Names[0].Pos() } return f.Type.Pos() } func (f *Field) End() token.Pos { if f.Tag != nil { return f.Tag.End() } return f.Type.End() } // A FieldList represents a list of Fields, enclosed by parentheses or braces. type FieldList struct { Opening token.Pos // position of opening parenthesis/brace, if any List []*Field // field list; or nil Closing token.Pos // position of closing parenthesis/brace, if any } func (f *FieldList) Pos() token.Pos { if f.Opening.IsValid() { return f.Opening } // the list should not be empty in this case; // be conservative and guard against bad ASTs if len(f.List) > 0 { return f.List[0].Pos() } return token.NoPos } func (f *FieldList) End() token.Pos { if f.Closing.IsValid() { return f.Closing + 1 } // the list should not be empty in this case; // be conservative and guard against bad ASTs if n := len(f.List); n > 0 { return f.List[n-1].End() } return token.NoPos } // NumFields returns the number of (named and anonymous fields) in a FieldList. func (f *FieldList) NumFields() int { n := 0 if f != nil { for _, g := range f.List { m := len(g.Names) if m == 0 { m = 1 // anonymous field } n += m } } return n } // An expression is represented by a tree consisting of one // or more of the following concrete expression nodes. // type ( // A BadExpr node is a placeholder for expressions containing // syntax errors for which no correct expression nodes can be // created. // BadExpr struct { From, To token.Pos // position range of bad expression } // An Ident node represents an identifier. Ident struct { NamePos token.Pos // identifier position Name string // identifier name Obj *Object // denoted object; or nil } // An Ellipsis node stands for the "..." type in a // parameter list or the "..." length in an array type. // Ellipsis struct { Ellipsis token.Pos // position of "..." Elt Expr // ellipsis element type (parameter lists only); or nil } // A BasicLit node represents a literal of basic type. BasicLit struct { ValuePos token.Pos // literal position Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o` } // A FuncLit node represents a function literal. FuncLit struct { Type *FuncType // function type Body *BlockStmt // function body } // A CompositeLit node represents a composite literal. CompositeLit struct { Type Expr // literal type; or nil Lbrace token.Pos // position of "{" Elts []Expr // list of composite elements; or nil Rbrace token.Pos // position of "}" } // A ParenExpr node represents a parenthesized expression. ParenExpr struct { Lparen token.Pos // position of "(" X Expr // parenthesized expression Rparen token.Pos // position of ")" } // A SelectorExpr node represents an expression followed by a selector. SelectorExpr struct { X Expr // expression Sel *Ident // field selector } // An IndexExpr node represents an expression followed by an index. IndexExpr struct { X Expr // expression Lbrack token.Pos // position of "[" Index Expr // index expression Rbrack token.Pos // position of "]" } // An SliceExpr node represents an expression followed by slice indices. SliceExpr struct { X Expr // expression Lbrack token.Pos // position of "[" Low Expr // begin of slice range; or nil High Expr // end of slice range; or nil Max Expr // maximum capacity of slice; or nil Slice3 bool // true if 3-index slice (2 colons present) Rbrack token.Pos // position of "]" } // A TypeAssertExpr node represents an expression followed by a // type assertion. // TypeAssertExpr struct { X Expr // expression Lparen token.Pos // position of "(" Type Expr // asserted type; nil means type switch X.(type) Rparen token.Pos // position of ")" } // A CallExpr node represents an expression followed by an argument list. CallExpr struct { Fun Expr // function expression Lparen token.Pos // position of "(" Args []Expr // function arguments; or nil Ellipsis token.Pos // position of "...", if any Rparen token.Pos // position of ")" } // A StarExpr node represents an expression of the form "*" Expression. // Semantically it could be a unary "*" expression, or a pointer type. // StarExpr struct { Star token.Pos // position of "*" X Expr // operand } // A UnaryExpr node represents a unary expression. // Unary "*" expressions are represented via StarExpr nodes. // UnaryExpr struct { OpPos token.Pos // position of Op Op token.Token // operator X Expr // operand } // A BinaryExpr node represents a binary expression. BinaryExpr struct { X Expr // left operand OpPos token.Pos // position of Op Op token.Token // operator Y Expr // right operand } // A KeyValueExpr node represents (key : value) pairs // in composite literals. // KeyValueExpr struct { Key Expr Colon token.Pos // position of ":" Value Expr } ) // The direction of a channel type is indicated by one // of the following constants. // type ChanDir int const ( SEND ChanDir = 1 << iota RECV ) // A type is represented by a tree consisting of one // or more of the following type-specific expression // nodes. // type ( // An ArrayType node represents an array or slice type. ArrayType struct { Lbrack token.Pos // position of "[" Len Expr // Ellipsis node for [...]T array types, nil for slice types Elt Expr // element type } // A StructType node represents a struct type. StructType struct { Struct token.Pos // position of "struct" keyword Fields *FieldList // list of field declarations Incomplete bool // true if (source) fields are missing in the Fields list } // Pointer types are represented via StarExpr nodes. // A FuncType node represents a function type. FuncType struct { Func token.Pos // position of "func" keyword (token.NoPos if there is no "func") Params *FieldList // (incoming) parameters; non-nil Results *FieldList // (outgoing) results; or nil } // An InterfaceType node represents an interface type. InterfaceType struct { Interface token.Pos // position of "interface" keyword Methods *FieldList // list of methods Incomplete bool // true if (source) methods are missing in the Methods list } // A MapType node represents a map type. MapType struct { Map token.Pos // position of "map" keyword Key Expr Value Expr } // A ChanType node represents a channel type. ChanType struct { Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first) Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-") Dir ChanDir // channel direction Value Expr // value type } ) // Pos and End implementations for expression/type nodes. // func (x *BadExpr) Pos() token.Pos { return x.From } func (x *Ident) Pos() token.Pos { return x.NamePos } func (x *Ellipsis) Pos() token.Pos { return x.Ellipsis } func (x *BasicLit) Pos() token.Pos { return x.ValuePos } func (x *FuncLit) Pos() token.Pos { return x.Type.Pos() } func (x *CompositeLit) Pos() token.Pos { if x.Type != nil { return x.Type.Pos() } return x.Lbrace } func (x *ParenExpr) Pos() token.Pos { return x.Lparen } func (x *SelectorExpr) Pos() token.Pos { return x.X.Pos() } func (x *IndexExpr) Pos() token.Pos { return x.X.Pos() } func (x *SliceExpr) Pos() token.Pos { return x.X.Pos() } func (x *TypeAssertExpr) Pos() token.Pos { return x.X.Pos() } func (x *CallExpr) Pos() token.Pos { return x.Fun.Pos() } func (x *StarExpr) Pos() token.Pos { return x.Star } func (x *UnaryExpr) Pos() token.Pos { return x.OpPos } func (x *BinaryExpr) Pos() token.Pos { return x.X.Pos() } func (x *KeyValueExpr) Pos() token.Pos { return x.Key.Pos() } func (x *ArrayType) Pos() token.Pos { return x.Lbrack } func (x *StructType) Pos() token.Pos { return x.Struct } func (x *FuncType) Pos() token.Pos { if x.Func.IsValid() || x.Params == nil { // see issue 3870 return x.Func } return x.Params.Pos() // interface method declarations have no "func" keyword } func (x *InterfaceType) Pos() token.Pos { return x.Interface } func (x *MapType) Pos() token.Pos { return x.Map } func (x *ChanType) Pos() token.Pos { return x.Begin } func (x *BadExpr) End() token.Pos { return x.To } func (x *Ident) End() token.Pos { return token.Pos(int(x.NamePos) + len(x.Name)) } func (x *Ellipsis) End() token.Pos { if x.Elt != nil { return x.Elt.End() } return x.Ellipsis + 3 // len("...") } func (x *BasicLit) End() token.Pos { return token.Pos(int(x.ValuePos) + len(x.Value)) } func (x *FuncLit) End() token.Pos { return x.Body.End() } func (x *CompositeLit) End() token.Pos { return x.Rbrace + 1 } func (x *ParenExpr) End() token.Pos { return x.Rparen + 1 } func (x *SelectorExpr) End() token.Pos { return x.Sel.End() } func (x *IndexExpr) End() token.Pos { return x.Rbrack + 1 } func (x *SliceExpr) End() token.Pos { return x.Rbrack + 1 } func (x *TypeAssertExpr) End() token.Pos { return x.Rparen + 1 } func (x *CallExpr) End() token.Pos { return x.Rparen + 1 } func (x *StarExpr) End() token.Pos { return x.X.End() } func (x *UnaryExpr) End() token.Pos { return x.X.End() } func (x *BinaryExpr) End() token.Pos { return x.Y.End() } func (x *KeyValueExpr) End() token.Pos { return x.Value.End() } func (x *ArrayType) End() token.Pos { return x.Elt.End() } func (x *StructType) End() token.Pos { return x.Fields.End() } func (x *FuncType) End() token.Pos { if x.Results != nil { return x.Results.End() } return x.Params.End() } func (x *InterfaceType) End() token.Pos { return x.Methods.End() } func (x *MapType) End() token.Pos { return x.Value.End() } func (x *ChanType) End() token.Pos { return x.Value.End() } // exprNode() ensures that only expression/type nodes can be // assigned to an ExprNode. // func (*BadExpr) exprNode() {} func (*Ident) exprNode() {} func (*Ellipsis) exprNode() {} func (*BasicLit) exprNode() {} func (*FuncLit) exprNode() {} func (*CompositeLit) exprNode() {} func (*ParenExpr) exprNode() {} func (*SelectorExpr) exprNode() {} func (*IndexExpr) exprNode() {} func (*SliceExpr) exprNode() {} func (*TypeAssertExpr) exprNode() {} func (*CallExpr) exprNode() {} func (*StarExpr) exprNode() {} func (*UnaryExpr) exprNode() {} func (*BinaryExpr) exprNode() {} func (*KeyValueExpr) exprNode() {} func (*ArrayType) exprNode() {} func (*StructType) exprNode() {} func (*FuncType) exprNode() {} func (*InterfaceType) exprNode() {} func (*MapType) exprNode() {} func (*ChanType) exprNode() {} // ---------------------------------------------------------------------------- // Convenience functions for Idents // NewIdent creates a new Ident without position. // Useful for ASTs generated by code other than the Go parser. // func NewIdent(name string) *Ident { return &Ident{token.NoPos, name, nil} } // IsExported reports whether name is an exported Go symbol // (that is, whether it begins with an upper-case letter). // func IsExported(name string) bool { ch, _ := utf8.DecodeRuneInString(name) return unicode.IsUpper(ch) } // IsExported reports whether id is an exported Go symbol // (that is, whether it begins with an uppercase letter). // func (id *Ident) IsExported() bool { return IsExported(id.Name) } func (id *Ident) String() string { if id != nil { return id.Name } return "" } // ---------------------------------------------------------------------------- // Statements // A statement is represented by a tree consisting of one // or more of the following concrete statement nodes. // type ( // A BadStmt node is a placeholder for statements containing // syntax errors for which no correct statement nodes can be // created. // BadStmt struct { From, To token.Pos // position range of bad statement } // A DeclStmt node represents a declaration in a statement list. DeclStmt struct { Decl Decl // *GenDecl with CONST, TYPE, or VAR token } // An EmptyStmt node represents an empty statement. // The "position" of the empty statement is the position // of the immediately preceding semicolon. // EmptyStmt struct { Semicolon token.Pos // position of preceding ";" } // A LabeledStmt node represents a labeled statement. LabeledStmt struct { Label *Ident Colon token.Pos // position of ":" Stmt Stmt } // An ExprStmt node represents a (stand-alone) expression // in a statement list. // ExprStmt struct { X Expr // expression } // A SendStmt node represents a send statement. SendStmt struct { Chan Expr Arrow token.Pos // position of "<-" Value Expr } // An IncDecStmt node represents an increment or decrement statement. IncDecStmt struct { X Expr TokPos token.Pos // position of Tok Tok token.Token // INC or DEC } // An AssignStmt node represents an assignment or // a short variable declaration. // AssignStmt struct { Lhs []Expr TokPos token.Pos // position of Tok Tok token.Token // assignment token, DEFINE Rhs []Expr } // A GoStmt node represents a go statement. GoStmt struct { Go token.Pos // position of "go" keyword Call *CallExpr } // A DeferStmt node represents a defer statement. DeferStmt struct { Defer token.Pos // position of "defer" keyword Call *CallExpr } // A ReturnStmt node represents a return statement. ReturnStmt struct { Return token.Pos // position of "return" keyword Results []Expr // result expressions; or nil } // A BranchStmt node represents a break, continue, goto, // or fallthrough statement. // BranchStmt struct { TokPos token.Pos // position of Tok Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) Label *Ident // label name; or nil } // A BlockStmt node represents a braced statement list. BlockStmt struct { Lbrace token.Pos // position of "{" List []Stmt Rbrace token.Pos // position of "}" } // An IfStmt node represents an if statement. IfStmt struct { If token.Pos // position of "if" keyword Init Stmt // initialization statement; or nil Cond Expr // condition Body *BlockStmt Else Stmt // else branch; or nil } // A CaseClause represents a case of an expression or type switch statement. CaseClause struct { Case token.Pos // position of "case" or "default" keyword List []Expr // list of expressions or types; nil means default case Colon token.Pos // position of ":" Body []Stmt // statement list; or nil } // A SwitchStmt node represents an expression switch statement. SwitchStmt struct { Switch token.Pos // position of "switch" keyword Init Stmt // initialization statement; or nil Tag Expr // tag expression; or nil Body *BlockStmt // CaseClauses only } // An TypeSwitchStmt node represents a type switch statement. TypeSwitchStmt struct { Switch token.Pos // position of "switch" keyword Init Stmt // initialization statement; or nil Assign Stmt // x := y.(type) or y.(type) Body *BlockStmt // CaseClauses only } // A CommClause node represents a case of a select statement. CommClause struct { Case token.Pos // position of "case" or "default" keyword Comm Stmt // send or receive statement; nil means default case Colon token.Pos // position of ":" Body []Stmt // statement list; or nil } // An SelectStmt node represents a select statement. SelectStmt struct { Select token.Pos // position of "select" keyword Body *BlockStmt // CommClauses only } // A ForStmt represents a for statement. ForStmt struct { For token.Pos // position of "for" keyword Init Stmt // initialization statement; or nil Cond Expr // condition; or nil Post Stmt // post iteration statement; or nil Body *BlockStmt } // A RangeStmt represents a for statement with a range clause. RangeStmt struct { For token.Pos // position of "for" keyword Key, Value Expr // Key, Value may be nil TokPos token.Pos // position of Tok; invalid if Key == nil Tok token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE X Expr // value to range over Body *BlockStmt } ) // Pos and End implementations for statement nodes. // func (s *BadStmt) Pos() token.Pos { return s.From } func (s *DeclStmt) Pos() token.Pos { return s.Decl.Pos() } func (s *EmptyStmt) Pos() token.Pos { return s.Semicolon } func (s *LabeledStmt) Pos() token.Pos { return s.Label.Pos() } func (s *ExprStmt) Pos() token.Pos { return s.X.Pos() } func (s *SendStmt) Pos() token.Pos { return s.Chan.Pos() } func (s *IncDecStmt) Pos() token.Pos { return s.X.Pos() } func (s *AssignStmt) Pos() token.Pos { return s.Lhs[0].Pos() } func (s *GoStmt) Pos() token.Pos { return s.Go } func (s *DeferStmt) Pos() token.Pos { return s.Defer } func (s *ReturnStmt) Pos() token.Pos { return s.Return } func (s *BranchStmt) Pos() token.Pos { return s.TokPos } func (s *BlockStmt) Pos() token.Pos { return s.Lbrace } func (s *IfStmt) Pos() token.Pos { return s.If } func (s *CaseClause) Pos() token.Pos { return s.Case } func (s *SwitchStmt) Pos() token.Pos { return s.Switch } func (s *TypeSwitchStmt) Pos() token.Pos { return s.Switch } func (s *CommClause) Pos() token.Pos { return s.Case } func (s *SelectStmt) Pos() token.Pos { return s.Select } func (s *ForStmt) Pos() token.Pos { return s.For } func (s *RangeStmt) Pos() token.Pos { return s.For } func (s *BadStmt) End() token.Pos { return s.To } func (s *DeclStmt) End() token.Pos { return s.Decl.End() } func (s *EmptyStmt) End() token.Pos { return s.Semicolon + 1 /* len(";") */ } func (s *LabeledStmt) End() token.Pos { return s.Stmt.End() } func (s *ExprStmt) End() token.Pos { return s.X.End() } func (s *SendStmt) End() token.Pos { return s.Value.End() } func (s *IncDecStmt) End() token.Pos { return s.TokPos + 2 /* len("++") */ } func (s *AssignStmt) End() token.Pos { return s.Rhs[len(s.Rhs)-1].End() } func (s *GoStmt) End() token.Pos { return s.Call.End() } func (s *DeferStmt) End() token.Pos { return s.Call.End() } func (s *ReturnStmt) End() token.Pos { if n := len(s.Results); n > 0 { return s.Results[n-1].End() } return s.Return + 6 // len("return") } func (s *BranchStmt) End() token.Pos { if s.Label != nil { return s.Label.End() } return token.Pos(int(s.TokPos) + len(s.Tok.String())) } func (s *BlockStmt) End() token.Pos { return s.Rbrace + 1 } func (s *IfStmt) End() token.Pos { if s.Else != nil { return s.Else.End() } return s.Body.End() } func (s *CaseClause) End() token.Pos { if n := len(s.Body); n > 0 { return s.Body[n-1].End() } return s.Colon + 1 } func (s *SwitchStmt) End() token.Pos { return s.Body.End() } func (s *TypeSwitchStmt) End() token.Pos { return s.Body.End() } func (s *CommClause) End() token.Pos { if n := len(s.Body); n > 0 { return s.Body[n-1].End() } return s.Colon + 1 } func (s *SelectStmt) End() token.Pos { return s.Body.End() } func (s *ForStmt) End() token.Pos { return s.Body.End() } func (s *RangeStmt) End() token.Pos { return s.Body.End() } // stmtNode() ensures that only statement nodes can be // assigned to a StmtNode. // func (*BadStmt) stmtNode() {} func (*DeclStmt) stmtNode() {} func (*EmptyStmt) stmtNode() {} func (*LabeledStmt) stmtNode() {} func (*ExprStmt) stmtNode() {} func (*SendStmt) stmtNode() {} func (*IncDecStmt) stmtNode() {} func (*AssignStmt) stmtNode() {} func (*GoStmt) stmtNode() {} func (*DeferStmt) stmtNode() {} func (*ReturnStmt) stmtNode() {} func (*BranchStmt) stmtNode() {} func (*BlockStmt) stmtNode() {} func (*IfStmt) stmtNode() {} func (*CaseClause) stmtNode() {} func (*SwitchStmt) stmtNode() {} func (*TypeSwitchStmt) stmtNode() {} func (*CommClause) stmtNode() {} func (*SelectStmt) stmtNode() {} func (*ForStmt) stmtNode() {} func (*RangeStmt) stmtNode() {} // ---------------------------------------------------------------------------- // Declarations // A Spec node represents a single (non-parenthesized) import, // constant, type, or variable declaration. // type ( // The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec. Spec interface { Node specNode() } // An ImportSpec node represents a single package import. ImportSpec struct { Doc *CommentGroup // associated documentation; or nil Name *Ident // local package name (including "."); or nil Path *BasicLit // import path Comment *CommentGroup // line comments; or nil EndPos token.Pos // end of spec (overrides Path.Pos if nonzero) } // A ValueSpec node represents a constant or variable declaration // (ConstSpec or VarSpec production). // ValueSpec struct { Doc *CommentGroup // associated documentation; or nil Names []*Ident // value names (len(Names) > 0) Type Expr // value type; or nil Values []Expr // initial values; or nil Comment *CommentGroup // line comments; or nil } // A TypeSpec node represents a type declaration (TypeSpec production). TypeSpec struct { Doc *CommentGroup // associated documentation; or nil Name *Ident // type name Type Expr // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes Comment *CommentGroup // line comments; or nil } ) // Pos and End implementations for spec nodes. // func (s *ImportSpec) Pos() token.Pos { if s.Name != nil { return s.Name.Pos() } return s.Path.Pos() } func (s *ValueSpec) Pos() token.Pos { return s.Names[0].Pos() } func (s *TypeSpec) Pos() token.Pos { return s.Name.Pos() } func (s *ImportSpec) End() token.Pos { if s.EndPos != 0 { return s.EndPos } return s.Path.End() } func (s *ValueSpec) End() token.Pos { if n := len(s.Values); n > 0 { return s.Values[n-1].End() } if s.Type != nil { return s.Type.End() } return s.Names[len(s.Names)-1].End() } func (s *TypeSpec) End() token.Pos { return s.Type.End() } // specNode() ensures that only spec nodes can be // assigned to a Spec. // func (*ImportSpec) specNode() {} func (*ValueSpec) specNode() {} func (*TypeSpec) specNode() {} // A declaration is represented by one of the following declaration nodes. // type ( // A BadDecl node is a placeholder for declarations containing // syntax errors for which no correct declaration nodes can be // created. // BadDecl struct { From, To token.Pos // position range of bad declaration } // A GenDecl node (generic declaration node) represents an import, // constant, type or variable declaration. A valid Lparen position // (Lparen.Line > 0) indicates a parenthesized declaration. // // Relationship between Tok value and Specs element type: // // token.IMPORT *ImportSpec // token.CONST *ValueSpec // token.TYPE *TypeSpec // token.VAR *ValueSpec // GenDecl struct { Doc *CommentGroup // associated documentation; or nil TokPos token.Pos // position of Tok Tok token.Token // IMPORT, CONST, TYPE, VAR Lparen token.Pos // position of '(', if any Specs []Spec Rparen token.Pos // position of ')', if any } // A FuncDecl node represents a function declaration. FuncDecl struct { Doc *CommentGroup // associated documentation; or nil Recv *FieldList // receiver (methods); or nil (functions) Name *Ident // function/method name Type *FuncType // function signature: parameters, results, and position of "func" keyword Body *BlockStmt // function body; or nil (forward declaration) } ) // Pos and End implementations for declaration nodes. // func (d *BadDecl) Pos() token.Pos { return d.From } func (d *GenDecl) Pos() token.Pos { return d.TokPos } func (d *FuncDecl) Pos() token.Pos { return d.Type.Pos() } func (d *BadDecl) End() token.Pos { return d.To } func (d *GenDecl) End() token.Pos { if d.Rparen.IsValid() { return d.Rparen + 1 } return d.Specs[0].End() } func (d *FuncDecl) End() token.Pos { if d.Body != nil { return d.Body.End() } return d.Type.End() } // declNode() ensures that only declaration nodes can be // assigned to a DeclNode. // func (*BadDecl) declNode() {} func (*GenDecl) declNode() {} func (*FuncDecl) declNode() {} // ---------------------------------------------------------------------------- // Files and packages // A File node represents a Go source file. // // The Comments list contains all comments in the source file in order of // appearance, including the comments that are pointed to from other nodes // via Doc and Comment fields. // type File struct { Doc *CommentGroup // associated documentation; or nil Package token.Pos // position of "package" keyword Name *Ident // package name Decls []Decl // top-level declarations; or nil Scope *Scope // package scope (this file only) Imports []*ImportSpec // imports in this file Unresolved []*Ident // unresolved identifiers in this file Comments []*CommentGroup // list of all comments in the source file } func (f *File) Pos() token.Pos { return f.Package } func (f *File) End() token.Pos { if n := len(f.Decls); n > 0 { return f.Decls[n-1].End() } return f.Name.End() } // A Package node represents a set of source files // collectively building a Go package. // type Package struct { Name string // package name Scope *Scope // package scope across all files Imports map[string]*Object // map of package id -> package object Files map[string]*File // Go source files by filename } func (p *Package) Pos() token.Pos { return token.NoPos } func (p *Package) End() token.Pos { return token.NoPos } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/gopkg.in/check.v1/gocheck_stub.go ================================================ package check ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/idea_io/io.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package io provides basic interfaces to I/O primitives. // Its primary job is to wrap existing implementations of such primitives, // such as those in package os, into shared public interfaces that // abstract the functionality, plus some other related primitives. // // Because these interfaces and primitives wrap lower-level operations with // various implementations, unless otherwise informed clients should not // assume they are safe for parallel execution. package idea_io import ( "errors" ) // ErrShortWrite means that a write accepted fewer bytes than requested // but failed to return an explicit error. var ErrShortWrite = errors.New("short write") // ErrShortBuffer means that a read required a longer buffer than was provided. var ErrShortBuffer = errors.New("short buffer") // EOF is the error returned by Read when no more input is available. // Functions should return EOF only to signal a graceful end of input. // If the EOF occurs unexpectedly in a structured data stream, // the appropriate error is either ErrUnexpectedEOF or some other error // giving more detail. var EOF = errors.New("EOF") // ErrUnexpectedEOF means that EOF was encountered in the // middle of reading a fixed-size block or data structure. var ErrUnexpectedEOF = errors.New("unexpected EOF") // ErrNoProgress is returned by some clients of an io.Reader when // many calls to Read have failed to return any data or error, // usually the sign of a broken io.Reader implementation. var ErrNoProgress = errors.New("multiple Read calls return no data or error") // Reader is the interface that wraps the basic Read method. // // Read reads up to len(p) bytes into p. It returns the number of bytes // read (0 <= n <= len(p)) and any error encountered. Even if Read // returns n < len(p), it may use all of p as scratch space during the call. // If some data is available but not len(p) bytes, Read conventionally // returns what is available instead of waiting for more. // // When Read encounters an error or end-of-file condition after // successfully reading n > 0 bytes, it returns the number of // bytes read. It may return the (non-nil) error from the same call // or return the error (and n == 0) from a subsequent call. // An instance of this general case is that a Reader returning // a non-zero number of bytes at the end of the input stream may // return either err == EOF or err == nil. The next Read should // return 0, EOF regardless. // // Callers should always process the n > 0 bytes returned before // considering the error err. Doing so correctly handles I/O errors // that happen after reading some bytes and also both of the // allowed EOF behaviors. // // Implementations of Read are discouraged from returning a // zero byte count with a nil error, and callers should treat // that situation as a no-op. type Reader interface { Read(p []byte) (n int, err error) } // Writer is the interface that wraps the basic Write method. // // Write writes len(p) bytes from p to the underlying data stream. // It returns the number of bytes written from p (0 <= n <= len(p)) // and any error encountered that caused the write to stop early. // Write must return a non-nil error if it returns n < len(p). type Writer interface { Write(p []byte) (n int, err error) } // Closer is the interface that wraps the basic Close method. // // The behavior of Close after the first call is undefined. // Specific implementations may document their own behavior. type Closer interface { Close() error } // Seeker is the interface that wraps the basic Seek method. // // Seek sets the offset for the next Read or Write to offset, // interpreted according to whence: 0 means relative to the origin of // the file, 1 means relative to the current offset, and 2 means // relative to the end. Seek returns the new offset and an Error, if // any. type Seeker interface { Seek(offset int64, whence int) (ret int64, err error) } // ReadWriter is the interface that groups the basic Read and Write methods. type ReadWriter interface { Reader Writer } // ReadCloser is the interface that groups the basic Read and Close methods. type ReadCloser interface { Reader Closer } // WriteCloser is the interface that groups the basic Write and Close methods. type WriteCloser interface { Writer Closer } // ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. type ReadWriteCloser interface { Reader Writer Closer } // ReadSeeker is the interface that groups the basic Read and Seek methods. type ReadSeeker interface { Reader Seeker } // WriteSeeker is the interface that groups the basic Write and Seek methods. type WriteSeeker interface { Writer Seeker } // ReadWriteSeekerCustom is the interface that groups the basic Read, Write and Seek methods. type ReadWriteSeekerCustom interface { Reader Writer Seeker } // ReaderFrom is the interface that wraps the ReadFrom method. // // ReadFrom reads data from r until EOF or error. // The return value n is the number of bytes read. // Any error except io.EOF encountered during the read is also returned. // // The Copy function uses ReaderFrom if available. type ReaderFrom interface { ReadFrom(r Reader) (n int64, err error) } // WriterTo is the interface that wraps the WriteTo method. // // WriteTo writes data to w until there's no more data to write or // when an error occurs. The return value n is the number of bytes // written. Any error encountered during the write is also returned. // // The Copy function uses WriterTo if available. type WriterTo interface { WriteTo(w Writer) (n int64, err error) } // ReaderAt is the interface that wraps the basic ReadAt method. // // ReadAt reads len(p) bytes into p starting at offset off in the // underlying input source. It returns the number of bytes // read (0 <= n <= len(p)) and any error encountered. // // When ReadAt returns n < len(p), it returns a non-nil error // explaining why more bytes were not returned. In this respect, // ReadAt is stricter than Read. // // Even if ReadAt returns n < len(p), it may use all of p as scratch // space during the call. If some data is available but not len(p) bytes, // ReadAt blocks until either all the data is available or an error occurs. // In this respect ReadAt is different from Read. // // If the n = len(p) bytes returned by ReadAt are at the end of the // input source, ReadAt may return either err == EOF or err == nil. // // If ReadAt is reading from an input source with a seek offset, // ReadAt should not affect nor be affected by the underlying // seek offset. // // Clients of ReadAt can execute parallel ReadAt calls on the // same input source. type ReaderAtCustom interface { ReadAt(p []byte, off int64) (n int, err error) } // WriterAt is the interface that wraps the basic WriteAt method. // // WriteAt writes len(p) bytes from p to the underlying data stream // at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) // and any error encountered that caused the write to stop early. // WriteAt must return a non-nil error if it returns n < len(p). // // If WriteAt is writing to a destination with a seek offset, // WriteAt should not affect nor be affected by the underlying // seek offset. // // Clients of WriteAt can execute parallel WriteAt calls on the same // destination if the ranges do not overlap. type WriterAt interface { WriteAt(p []byte, off int64) (n int, err error) } // ByteReader is the interface that wraps the ReadByte method. // // ReadByte reads and returns the next byte from the input. // If no byte is available, err will be set. type ByteReader interface { ReadByte() (c byte, err error) } // ByteScanner is the interface that adds the UnreadByte method to the // basic ReadByte method. // // UnreadByte causes the next call to ReadByte to return the same byte // as the previous call to ReadByte. // It may be an error to call UnreadByte twice without an intervening // call to ReadByte. type ByteScanner interface { ByteReader UnreadByte() error } // ByteWriter is the interface that wraps the WriteByte method. type ByteWriter interface { WriteByte(c byte) error } // RuneReader is the interface that wraps the ReadRune method. // // ReadRune reads a single UTF-8 encoded Unicode character // and returns the rune and its size in bytes. If no character is // available, err will be set. type RuneReader interface { ReadRune() (r rune, size int, err error) } // RuneScanner is the interface that adds the UnreadRune method to the // basic ReadRune method. // // UnreadRune causes the next call to ReadRune to return the same rune // as the previous call to ReadRune. // It may be an error to call UnreadRune twice without an intervening // call to ReadRune. type RuneScanner interface { RuneReader UnreadRune() error } // stringWriter is the interface that wraps the WriteString method. type stringWriter interface { WriteString(s string) (n int, err error) } // WriteString writes the contents of the string s to w, which accepts an array of bytes. // If w already implements a WriteString method, it is invoked directly. func WriteString(w Writer, s string) (n int, err error) { if sw, ok := w.(stringWriter); ok { return sw.WriteString(s) } return w.Write([]byte(s)) } // ReadAtLeastCustom reads from r into buf until it has read at least min bytes. // It returns the number of bytes copied and an error if fewer bytes were read. // The error is EOF only if no bytes were read. // If an EOF happens after reading fewer than min bytes, // ReadAtLeastCustom returns ErrUnexpectedEOF. // If min is greater than the length of buf, ReadAtLeastCustom returns ErrShortBuffer. // On return, n >= min if and only if err == nil. func ReadAtLeastCustom(r Reader, buf []byte, min int) (n int, err error) { if len(buf) < min { return 0, ErrShortBuffer } for n < min && err == nil { var nn int nn, err = r.Read(buf[n:]) n += nn } if n >= min { err = nil } else if n > 0 && err == EOF { err = ErrUnexpectedEOF } return } // ReadFull reads exactly len(buf) bytes from r into buf. // It returns the number of bytes copied and an error if fewer bytes were read. // The error is EOF only if no bytes were read. // If an EOF happens after reading some but not all the bytes, // ReadFull returns ErrUnexpectedEOF. // On return, n == len(buf) if and only if err == nil. func ReadFull(r Reader, buf []byte) (n int, err error) { return ReadAtLeastCustom(r, buf, len(buf)) } // CopyN copies n bytes (or until an error) from src to dst. // It returns the number of bytes copied and the earliest // error encountered while copying. // On return, written == n if and only if err == nil. // // If dst implements the ReaderFrom interface, // the copy is implemented using it. func CopyN(dst Writer, src Reader, n int64) (written int64, err error) { written, err = Copy(dst, LimitReader(src, n)) if written == n { return n, nil } if written < n && err == nil { // src stopped early; must have been EOF. err = EOF } return } // Copy copies from src to dst until either EOF is reached // on src or an error occurs. It returns the number of bytes // copied and the first error encountered while copying, if any. // // A successful Copy returns err == nil, not err == EOF. // Because Copy is defined to read from src until EOF, it does // not treat an EOF from Read as an error to be reported. // // If dst implements the ReaderFrom interface, // the copy is implemented by calling dst.ReadFrom(src). // Otherwise, if src implements the WriterTo interface, // the copy is implemented by calling src.WriteTo(dst). func Copy(dst Writer, src Reader) (written int64, err error) { // If the writer has a ReadFrom method, use it to do the copy. // Avoids an allocation and a copy. if rt, ok := dst.(ReaderFrom); ok { return rt.ReadFrom(src) } // Similarly, if the reader has a WriteTo method, use it to do the copy. if wt, ok := src.(WriterTo); ok { return wt.WriteTo(dst) } buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = ErrShortWrite break } } if er == EOF { break } if er != nil { err = er break } } return written, err } // LimitReader returns a Reader that reads from r // but stops with EOF after n bytes. // The underlying implementation is a *LimitedReader. func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} } // A LimitedReader reads from R but limits the amount of // data returned to just N bytes. Each call to Read // updates N to reflect the new amount remaining. type LimitedReader struct { R Reader // underlying reader N int64 // max bytes remaining } func (l *LimitedReader) Read(p []byte) (n int, err error) { if l.N <= 0 { return 0, EOF } if int64(len(p)) > l.N { p = p[0:l.N] } n, err = l.R.Read(p) l.N -= int64(n) return } // NewSectionReader returns a SectionReader that reads from r // starting at offset off and stops with EOF after n bytes. func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { return &SectionReader{r, off, off, off + n} } // SectionReader implements Read, Seek, and ReadAt on a section // of an underlying ReaderAt. type SectionReader struct { r ReaderAt base int64 off int64 limit int64 } func (s *SectionReader) Read(p []byte) (n int, err error) { if s.off >= s.limit { return 0, EOF } if max := s.limit - s.off; int64(len(p)) > max { p = p[0:max] } n, err = s.r.ReadAt(p, s.off) s.off += int64(n) return } var errWhence = errors.New("Seek: invalid whence") var errOffset = errors.New("Seek: invalid offset") func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err error) { switch whence { default: return 0, errWhence case 0: offset += s.base case 1: offset += s.off case 2: offset += s.limit } if offset < s.base || offset > s.limit { return 0, errOffset } s.off = offset return offset - s.base, nil } func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) { if off < 0 || off >= s.limit-s.base { return 0, EOF } off += s.base if max := s.limit - off; int64(len(p)) > max { p = p[0:max] n, err = s.r.ReadAt(p, off) if err == nil { err = EOF } return n, err } return s.r.ReadAt(p, off) } // Size returns the size of the section in bytes. func (s *SectionReader) Size() int64 { return s.limit - s.base } // TeeReader returns a Reader that writes to w what it reads from r. // All reads from r performed through it are matched with // corresponding writes to w. There is no internal buffering - // the write must complete before the read completes. // Any error encountered while writing is reported as a read error. func TeeReader(r Reader, w Writer) Reader { return &teeReader{r, w} } type teeReader struct { r Reader w Writer } func (t *teeReader) Read(p []byte) (n int, err error) { n, err = t.r.Read(p) if n > 0 { if n, err := t.w.Write(p[:n]); err != nil { return n, err } } return } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/io/io.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package io provides basic interfaces to I/O primitives. // Its primary job is to wrap existing implementations of such primitives, // such as those in package os, into shared public interfaces that // abstract the functionality, plus some other related primitives. // // Because these interfaces and primitives wrap lower-level operations with // various implementations, unless otherwise informed clients should not // assume they are safe for parallel execution. package io import ( "errors" ) // ErrShortWrite means that a write accepted fewer bytes than requested // but failed to return an explicit error. var ErrShortWrite = errors.New("short write") // ErrShortBuffer means that a read required a longer buffer than was provided. var ErrShortBuffer = errors.New("short buffer") // EOF is the error returned by Read when no more input is available. // Functions should return EOF only to signal a graceful end of input. // If the EOF occurs unexpectedly in a structured data stream, // the appropriate error is either ErrUnexpectedEOF or some other error // giving more detail. var EOF = errors.New("EOF") // ErrUnexpectedEOF means that EOF was encountered in the // middle of reading a fixed-size block or data structure. var ErrUnexpectedEOF = errors.New("unexpected EOF") // ErrNoProgress is returned by some clients of an io.Reader when // many calls to Read have failed to return any data or error, // usually the sign of a broken io.Reader implementation. var ErrNoProgress = errors.New("multiple Read calls return no data or error") // Reader is the interface that wraps the basic Read method. // // Read reads up to len(p) bytes into p. It returns the number of bytes // read (0 <= n <= len(p)) and any error encountered. Even if Read // returns n < len(p), it may use all of p as scratch space during the call. // If some data is available but not len(p) bytes, Read conventionally // returns what is available instead of waiting for more. // // When Read encounters an error or end-of-file condition after // successfully reading n > 0 bytes, it returns the number of // bytes read. It may return the (non-nil) error from the same call // or return the error (and n == 0) from a subsequent call. // An instance of this general case is that a Reader returning // a non-zero number of bytes at the end of the input stream may // return either err == EOF or err == nil. The next Read should // return 0, EOF regardless. // // Callers should always process the n > 0 bytes returned before // considering the error err. Doing so correctly handles I/O errors // that happen after reading some bytes and also both of the // allowed EOF behaviors. // // Implementations of Read are discouraged from returning a // zero byte count with a nil error, and callers should treat // that situation as a no-op. type Reader interface { Read(p []byte) (n int, err error) } // Writer is the interface that wraps the basic Write method. // // Write writes len(p) bytes from p to the underlying data stream. // It returns the number of bytes written from p (0 <= n <= len(p)) // and any error encountered that caused the write to stop early. // Write must return a non-nil error if it returns n < len(p). type Writer interface { Write(p []byte) (n int, err error) } // Closer is the interface that wraps the basic Close method. // // The behavior of Close after the first call is undefined. // Specific implementations may document their own behavior. type Closer interface { Close() error } // Seeker is the interface that wraps the basic Seek method. // // Seek sets the offset for the next Read or Write to offset, // interpreted according to whence: 0 means relative to the origin of // the file, 1 means relative to the current offset, and 2 means // relative to the end. Seek returns the new offset and an Error, if // any. type Seeker interface { Seek(offset int64, whence int) (ret int64, err error) } // ReadWriter is the interface that groups the basic Read and Write methods. type ReadWriter interface { Reader Writer } // ReadCloser is the interface that groups the basic Read and Close methods. type ReadCloser interface { Reader Closer } // WriteCloser is the interface that groups the basic Write and Close methods. type WriteCloser interface { Writer Closer } // ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. type ReadWriteCloser interface { Reader Writer Closer } // ReadSeeker is the interface that groups the basic Read and Seek methods. type ReadSeeker interface { Reader Seeker } // WriteSeeker is the interface that groups the basic Write and Seek methods. type WriteSeeker interface { Writer Seeker } // ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. type ReadWriteSeeker interface { Reader Writer Seeker } // ReaderFrom is the interface that wraps the ReadFrom method. // // ReadFrom reads data from r until EOF or error. // The return value n is the number of bytes read. // Any error except io.EOF encountered during the read is also returned. // // The Copy function uses ReaderFrom if available. type ReaderFrom interface { ReadFrom(r Reader) (n int64, err error) } // WriterTo is the interface that wraps the WriteTo method. // // WriteTo writes data to w until there's no more data to write or // when an error occurs. The return value n is the number of bytes // written. Any error encountered during the write is also returned. // // The Copy function uses WriterTo if available. type WriterTo interface { WriteTo(w Writer) (n int64, err error) } // ReaderAt is the interface that wraps the basic ReadAt method. // // ReadAt reads len(p) bytes into p starting at offset off in the // underlying input source. It returns the number of bytes // read (0 <= n <= len(p)) and any error encountered. // // When ReadAt returns n < len(p), it returns a non-nil error // explaining why more bytes were not returned. In this respect, // ReadAt is stricter than Read. // // Even if ReadAt returns n < len(p), it may use all of p as scratch // space during the call. If some data is available but not len(p) bytes, // ReadAt blocks until either all the data is available or an error occurs. // In this respect ReadAt is different from Read. // // If the n = len(p) bytes returned by ReadAt are at the end of the // input source, ReadAt may return either err == EOF or err == nil. // // If ReadAt is reading from an input source with a seek offset, // ReadAt should not affect nor be affected by the underlying // seek offset. // // Clients of ReadAt can execute parallel ReadAt calls on the // same input source. type ReaderAt interface { ReadAt(p []byte, off int64) (n int, err error) } // WriterAt is the interface that wraps the basic WriteAt method. // // WriteAt writes len(p) bytes from p to the underlying data stream // at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) // and any error encountered that caused the write to stop early. // WriteAt must return a non-nil error if it returns n < len(p). // // If WriteAt is writing to a destination with a seek offset, // WriteAt should not affect nor be affected by the underlying // seek offset. // // Clients of WriteAt can execute parallel WriteAt calls on the same // destination if the ranges do not overlap. type WriterAt interface { WriteAt(p []byte, off int64) (n int, err error) } // ByteReader is the interface that wraps the ReadByte method. // // ReadByte reads and returns the next byte from the input. // If no byte is available, err will be set. type ByteReader interface { ReadByte() (c byte, err error) } // ByteScanner is the interface that adds the UnreadByte method to the // basic ReadByte method. // // UnreadByte causes the next call to ReadByte to return the same byte // as the previous call to ReadByte. // It may be an error to call UnreadByte twice without an intervening // call to ReadByte. type ByteScanner interface { ByteReader UnreadByte() error } // ByteWriter is the interface that wraps the WriteByte method. type ByteWriter interface { WriteByte(c byte) error } // RuneReader is the interface that wraps the ReadRune method. // // ReadRune reads a single UTF-8 encoded Unicode character // and returns the rune and its size in bytes. If no character is // available, err will be set. type RuneReader interface { ReadRune() (r rune, size int, err error) } // RuneScanner is the interface that adds the UnreadRune method to the // basic ReadRune method. // // UnreadRune causes the next call to ReadRune to return the same rune // as the previous call to ReadRune. // It may be an error to call UnreadRune twice without an intervening // call to ReadRune. type RuneScanner interface { RuneReader UnreadRune() error } // stringWriter is the interface that wraps the WriteString method. type stringWriter interface { WriteString(s string) (n int, err error) } // WriteString writes the contents of the string s to w, which accepts an array of bytes. // If w already implements a WriteString method, it is invoked directly. func WriteString(w Writer, s string) (n int, err error) { if sw, ok := w.(stringWriter); ok { return sw.WriteString(s) } return w.Write([]byte(s)) } // ReadAtLeast reads from r into buf until it has read at least min bytes. // It returns the number of bytes copied and an error if fewer bytes were read. // The error is EOF only if no bytes were read. // If an EOF happens after reading fewer than min bytes, // ReadAtLeast returns ErrUnexpectedEOF. // If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. // On return, n >= min if and only if err == nil. func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) { if len(buf) < min { return 0, ErrShortBuffer } for n < min && err == nil { var nn int nn, err = r.Read(buf[n:]) n += nn } if n >= min { err = nil } else if n > 0 && err == EOF { err = ErrUnexpectedEOF } return } // ReadFull reads exactly len(buf) bytes from r into buf. // It returns the number of bytes copied and an error if fewer bytes were read. // The error is EOF only if no bytes were read. // If an EOF happens after reading some but not all the bytes, // ReadFull returns ErrUnexpectedEOF. // On return, n == len(buf) if and only if err == nil. func ReadFull(r Reader, buf []byte) (n int, err error) { return ReadAtLeast(r, buf, len(buf)) } // CopyN copies n bytes (or until an error) from src to dst. // It returns the number of bytes copied and the earliest // error encountered while copying. // On return, written == n if and only if err == nil. // // If dst implements the ReaderFrom interface, // the copy is implemented using it. func CopyN(dst Writer, src Reader, n int64) (written int64, err error) { written, err = Copy(dst, LimitReader(src, n)) if written == n { return n, nil } if written < n && err == nil { // src stopped early; must have been EOF. err = EOF } return } // Copy copies from src to dst until either EOF is reached // on src or an error occurs. It returns the number of bytes // copied and the first error encountered while copying, if any. // // A successful Copy returns err == nil, not err == EOF. // Because Copy is defined to read from src until EOF, it does // not treat an EOF from Read as an error to be reported. // // If dst implements the ReaderFrom interface, // the copy is implemented by calling dst.ReadFrom(src). // Otherwise, if src implements the WriterTo interface, // the copy is implemented by calling src.WriteTo(dst). func Copy(dst Writer, src Reader) (written int64, err error) { // If the writer has a ReadFrom method, use it to do the copy. // Avoids an allocation and a copy. if rt, ok := dst.(ReaderFrom); ok { return rt.ReadFrom(src) } // Similarly, if the reader has a WriteTo method, use it to do the copy. if wt, ok := src.(WriterTo); ok { return wt.WriteTo(dst) } buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { err = ew break } if nr != nw { err = ErrShortWrite break } } if er == EOF { break } if er != nil { err = er break } } return written, err } // LimitReader returns a Reader that reads from r // but stops with EOF after n bytes. // The underlying implementation is a *LimitedReader. func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} } // A LimitedReader reads from R but limits the amount of // data returned to just N bytes. Each call to Read // updates N to reflect the new amount remaining. type LimitedReader struct { R Reader // underlying reader N int64 // max bytes remaining } func (l *LimitedReader) Read(p []byte) (n int, err error) { if l.N <= 0 { return 0, EOF } if int64(len(p)) > l.N { p = p[0:l.N] } n, err = l.R.Read(p) l.N -= int64(n) return } // NewSectionReader returns a SectionReader that reads from r // starting at offset off and stops with EOF after n bytes. func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader { return &SectionReader{r, off, off, off + n} } // SectionReader implements Read, Seek, and ReadAt on a section // of an underlying ReaderAt. type SectionReader struct { r ReaderAt base int64 off int64 limit int64 } func (s *SectionReader) Read(p []byte) (n int, err error) { if s.off >= s.limit { return 0, EOF } if max := s.limit - s.off; int64(len(p)) > max { p = p[0:max] } n, err = s.r.ReadAt(p, s.off) s.off += int64(n) return } var errWhence = errors.New("Seek: invalid whence") var errOffset = errors.New("Seek: invalid offset") func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err error) { switch whence { default: return 0, errWhence case 0: offset += s.base case 1: offset += s.off case 2: offset += s.limit } if offset < s.base || offset > s.limit { return 0, errOffset } s.off = offset return offset - s.base, nil } func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) { if off < 0 || off >= s.limit-s.base { return 0, EOF } off += s.base if max := s.limit - off; int64(len(p)) > max { p = p[0:max] n, err = s.r.ReadAt(p, off) if err == nil { err = EOF } return n, err } return s.r.ReadAt(p, off) } // Size returns the size of the section in bytes. func (s *SectionReader) Size() int64 { return s.limit - s.base } // TeeReader returns a Reader that writes to w what it reads from r. // All reads from r performed through it are matched with // corresponding writes to w. There is no internal buffering - // the write must complete before the read completes. // Any error encountered while writing is reported as a read error. func TeeReader(r Reader, w Writer) Reader { return &teeReader{r, w} } type teeReader struct { r Reader w Writer } func (t *teeReader) Read(p []byte) (n int, err error) { n, err = t.r.Read(p) if n > 0 { if n, err := t.w.Write(p[:n]); err != nil { return n, err } } return } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/log/log.go ================================================ package log func Fatalf(format string, v ...interface{}) {} func Panicf(format string, v ...interface{}) {} func Printf(format string, v ...interface{}) {} ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/math/abs.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package math // Abs returns the absolute value of x. // // Special cases are: // Abs(±Inf) = +Inf // Abs(NaN) = NaN func Abs(x float64) float64 func abs(x float64) float64 { switch { case x < 0: return -x case x == 0: return 0 // return correctly abs(-0) } return x } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/net/http/request.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // HTTP Request reading and parsing. package http import ( "bufio" "bytes" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "mime" "mime/multipart" "net/textproto" "net/url" "strconv" "strings" ) const ( maxValueLength = 4096 maxHeaderLines = 1024 chunkSize = 4 << 10 // 4 KB chunks defaultMaxMemory = 32 << 20 // 32 MB ) // ErrMissingFile is returned by FormFile when the provided file field name // is either not present in the request or not a file field. var ErrMissingFile = errors.New("http: no such file") // HTTP request parsing errors. type ProtocolError struct { ErrorString string } func (err *ProtocolError) Error() string { return err.ErrorString } var ( ErrHeaderTooLong = &ProtocolError{"header too long"} ErrShortBody = &ProtocolError{"entity body too short"} ErrNotSupported = &ProtocolError{"feature not supported"} ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} ) type badStringError struct { what string str string } func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } // Headers that Request.Write handles itself and should be skipped. var reqWriteExcludeHeader = map[string]bool{ "Host": true, // not in Header map anyway "User-Agent": true, "Content-Length": true, "Transfer-Encoding": true, "Trailer": true, } // A Request represents an HTTP request received by a server // or to be sent by a client. type Request struct { Method string // GET, POST, PUT, etc. // URL is created from the URI supplied on the Request-Line // as stored in RequestURI. // // For most requests, fields other than Path and RawQuery // will be empty. (See RFC 2616, Section 5.1.2) URL *url.URL // The protocol version for incoming requests. // Outgoing requests always use HTTP/1.1. Proto string // "HTTP/1.0" ProtoMajor int // 1 ProtoMinor int // 0 // A header maps request lines to their values. // If the header says // // accept-encoding: gzip, deflate // Accept-Language: en-us // Connection: keep-alive // // then // // Header = map[string][]string{ // "Accept-Encoding": {"gzip, deflate"}, // "Accept-Language": {"en-us"}, // "Connection": {"keep-alive"}, // } // // HTTP defines that header names are case-insensitive. // The request parser implements this by canonicalizing the // name, making the first character and any characters // following a hyphen uppercase and the rest lowercase. Header Header // The message body. Body io.ReadCloser // ContentLength records the length of the associated content. // The value -1 indicates that the length is unknown. // Values >= 0 indicate that the given number of bytes may // be read from Body. // For outgoing requests, a value of 0 means unknown if Body is not nil. ContentLength int64 // TransferEncoding lists the transfer encodings from outermost to // innermost. An empty list denotes the "identity" encoding. // TransferEncoding can usually be ignored; chunked encoding is // automatically added and removed as necessary when sending and // receiving requests. TransferEncoding []string // Close indicates whether to close the connection after // replying to this request. Close bool // The host on which the URL is sought. // Per RFC 2616, this is either the value of the Host: header // or the host name given in the URL itself. // It may be of the form "host:port". Host string // Form contains the parsed form data, including both the URL // field's query parameters and the POST or PUT form data. // This field is only available after ParseForm is called. // The HTTP client ignores Form and uses Body instead. Form url.Values // PostForm contains the parsed form data from POST or PUT // body parameters. // This field is only available after ParseForm is called. // The HTTP client ignores PostForm and uses Body instead. PostForm url.Values // MultipartForm is the parsed multipart form, including file uploads. // This field is only available after ParseMultipartForm is called. // The HTTP client ignores MultipartForm and uses Body instead. MultipartForm *multipart.Form // Trailer maps trailer keys to values. Like for Header, if the // response has multiple trailer lines with the same key, they will be // concatenated, delimited by commas. // For server requests, Trailer is only populated after Body has been // closed or fully consumed. // Trailer support is only partially complete. Trailer Header // RemoteAddr allows HTTP servers and other software to record // the network address that sent the request, usually for // logging. This field is not filled in by ReadRequest and // has no defined format. The HTTP server in this package // sets RemoteAddr to an "IP:port" address before invoking a // handler. // This field is ignored by the HTTP client. RemoteAddr string // RequestURI is the unmodified Request-URI of the // Request-Line (RFC 2616, Section 5.1) as sent by the client // to a server. Usually the URL field should be used instead. // It is an error to set this field in an HTTP client request. RequestURI string // TLS allows HTTP servers and other software to record // information about the TLS connection on which the request // was received. This field is not filled in by ReadRequest. // The HTTP server in this package sets the field for // TLS-enabled connections before invoking a handler; // otherwise it leaves the field nil. // This field is ignored by the HTTP client. TLS *tls.ConnectionState } // ProtoAtLeast returns whether the HTTP protocol used // in the request is at least major.minor. func (r *Request) ProtoAtLeast(major, minor int) bool { return r.ProtoMajor > major || r.ProtoMajor == major && r.ProtoMinor >= minor } // UserAgent returns the client's User-Agent, if sent in the request. func (r *Request) UserAgent() string { return r.Header.Get("User-Agent") } // Cookies parses and returns the HTTP cookies sent with the request. func (r *Request) Cookies() []*Cookie { return readCookies(r.Header, "") } var ErrNoCookie = errors.New("http: named cookie not present") // Cookie returns the named cookie provided in the request or // ErrNoCookie if not found. func (r *Request) Cookie(name string) (*Cookie, error) { for _, c := range readCookies(r.Header, name) { return c, nil } return nil, ErrNoCookie } // AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, // AddCookie does not attach more than one Cookie header field. That // means all cookies, if any, are written into the same line, // separated by semicolon. func (r *Request) AddCookie(c *Cookie) { s := fmt.Sprintf("%s=%s", sanitizeName(c.Name), sanitizeValue(c.Value)) if c := r.Header.Get("Cookie"); c != "" { r.Header.Set("Cookie", c+"; "+s) } else { r.Header.Set("Cookie", s) } } // Referer returns the referring URL, if sent in the request. // // Referer is misspelled as in the request itself, a mistake from the // earliest days of HTTP. This value can also be fetched from the // Header map as Header["Referer"]; the benefit of making it available // as a method is that the compiler can diagnose programs that use the // alternate (correct English) spelling req.Referrer() but cannot // diagnose programs that use Header["Referrer"]. func (r *Request) Referer() string { return r.Header.Get("Referer") } // multipartByReader is a sentinel value. // Its presence in Request.MultipartForm indicates that parsing of the request // body has been handed off to a MultipartReader instead of ParseMultipartFrom. var multipartByReader = &multipart.Form{ Value: make(map[string][]string), File: make(map[string][]*multipart.FileHeader), } // MultipartReader returns a MIME multipart reader if this is a // multipart/form-data POST request, else returns nil and an error. // Use this function instead of ParseMultipartForm to // process the request body as a stream. func (r *Request) MultipartReader() (*multipart.Reader, error) { if r.MultipartForm == multipartByReader { return nil, errors.New("http: MultipartReader called twice") } if r.MultipartForm != nil { return nil, errors.New("http: multipart handled by ParseMultipartForm") } r.MultipartForm = multipartByReader return r.multipartReader() } func (r *Request) multipartReader() (*multipart.Reader, error) { v := r.Header.Get("Content-Type") if v == "" { return nil, ErrNotMultipart } d, params, err := mime.ParseMediaType(v) if err != nil || d != "multipart/form-data" { return nil, ErrNotMultipart } boundary, ok := params["boundary"] if !ok { return nil, ErrMissingBoundary } return multipart.NewReader(r.Body, boundary), nil } // Return value if nonempty, def otherwise. func valueOrDefault(value, def string) string { if value != "" { return value } return def } const defaultUserAgent = "Go 1.1 package http" // Write writes an HTTP/1.1 request -- header and body -- in wire format. // This method consults the following fields of the request: // Host // URL // Method (defaults to "GET") // Header // ContentLength // TransferEncoding // Body // // If Body is present, Content-Length is <= 0 and TransferEncoding // hasn't been set to "identity", Write adds "Transfer-Encoding: // chunked" to the header. Body is closed after it is sent. func (r *Request) Write(w io.Writer) error { return r.write(w, false, nil) } // WriteProxy is like Write but writes the request in the form // expected by an HTTP proxy. In particular, WriteProxy writes the // initial Request-URI line of the request with an absolute URI, per // section 5.1.2 of RFC 2616, including the scheme and host. // In either case, WriteProxy also writes a Host header, using // either r.Host or r.URL.Host. func (r *Request) WriteProxy(w io.Writer) error { return r.write(w, true, nil) } // extraHeaders may be nil func (req *Request) write(w io.Writer, usingProxy bool, extraHeaders Header) error { host := req.Host if host == "" { if req.URL == nil { return errors.New("http: Request.Write on Request with no Host or URL set") } host = req.URL.Host } ruri := req.URL.RequestURI() if usingProxy && req.URL.Scheme != "" && req.URL.Opaque == "" { ruri = req.URL.Scheme + "://" + host + ruri } else if req.Method == "CONNECT" && req.URL.Path == "" { // CONNECT requests normally give just the host and port, not a full URL. ruri = host } // TODO(bradfitz): escape at least newlines in ruri? // Wrap the writer in a bufio Writer if it's not already buffered. // Don't always call NewWriter, as that forces a bytes.Buffer // and other small bufio Writers to have a minimum 4k buffer // size. var bw *bufio.Writer if _, ok := w.(io.ByteWriter); !ok { bw = bufio.NewWriter(w) w = bw } fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(req.Method, "GET"), ruri) // Header lines fmt.Fprintf(w, "Host: %s\r\n", host) // Use the defaultUserAgent unless the Header contains one, which // may be blank to not send the header. userAgent := defaultUserAgent if req.Header != nil { if ua := req.Header["User-Agent"]; len(ua) > 0 { userAgent = ua[0] } } if userAgent != "" { fmt.Fprintf(w, "User-Agent: %s\r\n", userAgent) } // Process Body,ContentLength,Close,Trailer tw, err := newTransferWriter(req) if err != nil { return err } err = tw.WriteHeader(w) if err != nil { return err } // TODO: split long values? (If so, should share code with Conn.Write) err = req.Header.WriteSubset(w, reqWriteExcludeHeader) if err != nil { return err } if extraHeaders != nil { err = extraHeaders.Write(w) if err != nil { return err } } io.WriteString(w, "\r\n") // Write body and trailer err = tw.WriteBody(w) if err != nil { return err } if bw != nil { return bw.Flush() } return nil } // ParseHTTPVersion parses a HTTP version string. // "HTTP/1.0" returns (1, 0, true). func ParseHTTPVersion(vers string) (major, minor int, ok bool) { const Big = 1000000 // arbitrary upper bound switch vers { case "HTTP/1.1": return 1, 1, true case "HTTP/1.0": return 1, 0, true } if !strings.HasPrefix(vers, "HTTP/") { return 0, 0, false } dot := strings.Index(vers, ".") if dot < 0 { return 0, 0, false } major, err := strconv.Atoi(vers[5:dot]) if err != nil || major < 0 || major > Big { return 0, 0, false } minor, err = strconv.Atoi(vers[dot+1:]) if err != nil || minor < 0 || minor > Big { return 0, 0, false } return major, minor, true } // NewRequest returns a new Request given a method, URL, and optional body. func NewRequest(method, urlStr string, body io.Reader) (*Request, error) { u, err := url.Parse(urlStr) if err != nil { return nil, err } rc, ok := body.(io.ReadCloser) if !ok && body != nil { rc = ioutil.NopCloser(body) } req := &Request{ Method: method, URL: u, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(Header), Body: rc, Host: u.Host, } if body != nil { switch v := body.(type) { case *bytes.Buffer: req.ContentLength = int64(v.Len()) case *bytes.Reader: req.ContentLength = int64(v.Len()) case *strings.Reader: req.ContentLength = int64(v.Len()) } } return req, nil } // SetBasicAuth sets the request's Authorization header to use HTTP // Basic Authentication with the provided username and password. // // With HTTP Basic Authentication the provided username and password // are not encrypted. func (r *Request) SetBasicAuth(username, password string) { s := username + ":" + password r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(s))) } // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) { s1 := strings.Index(line, " ") s2 := strings.Index(line[s1+1:], " ") if s1 < 0 || s2 < 0 { return } s2 += s1 + 1 return line[:s1], line[s1+1 : s2], line[s2+1:], true } // TODO(bradfitz): use a sync.Cache when available var textprotoReaderCache = make(chan *textproto.Reader, 4) func newTextprotoReader(br *bufio.Reader) *textproto.Reader { select { case r := <-textprotoReaderCache: r.R = br return r default: return textproto.NewReader(br) } } func putTextprotoReader(r *textproto.Reader) { r.R = nil select { case textprotoReaderCache <- r: default: } } // ReadRequest reads and parses a request from b. func ReadRequest(b *bufio.Reader) (req *Request, err error) { tp := newTextprotoReader(b) req = new(Request) // First line: GET /index.html HTTP/1.0 var s string if s, err = tp.ReadLine(); err != nil { return nil, err } defer func() { putTextprotoReader(tp) if err == io.EOF { err = io.ErrUnexpectedEOF } }() var ok bool req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(s) if !ok { return nil, &badStringError{"malformed HTTP request", s} } rawurl := req.RequestURI if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok { return nil, &badStringError{"malformed HTTP version", req.Proto} } // CONNECT requests are used two different ways, and neither uses a full URL: // The standard use is to tunnel HTTPS through an HTTP proxy. // It looks like "CONNECT www.google.com:443 HTTP/1.1", and the parameter is // just the authority section of a URL. This information should go in req.URL.Host. // // The net/rpc package also uses CONNECT, but there the parameter is a path // that starts with a slash. It can be parsed with the regular URL parser, // and the path will end up in req.URL.Path, where it needs to be in order for // RPC to work. justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/") if justAuthority { rawurl = "http://" + rawurl } if req.URL, err = url.ParseRequestURI(rawurl); err != nil { return nil, err } if justAuthority { // Strip the bogus "http://" back off. req.URL.Scheme = "" } // Subsequent lines: Key: value. mimeHeader, err := tp.ReadMIMEHeader() if err != nil { return nil, err } req.Header = Header(mimeHeader) // RFC2616: Must treat // GET /index.html HTTP/1.1 // Host: www.google.com // and // GET http://www.google.com/index.html HTTP/1.1 // Host: doesntmatter // the same. In the second case, any Host line is ignored. req.Host = req.URL.Host if req.Host == "" { req.Host = req.Header.get("Host") } delete(req.Header, "Host") fixPragmaCacheControl(req.Header) // TODO: Parse specific header values: // Accept // Accept-Encoding // Accept-Language // Authorization // Cache-Control // Connection // Date // Expect // From // If-Match // If-Modified-Since // If-None-Match // If-Range // If-Unmodified-Since // Max-Forwards // Proxy-Authorization // Referer [sic] // TE (transfer-codings) // Trailer // Transfer-Encoding // Upgrade // User-Agent // Via // Warning err = readTransfer(req, b) if err != nil { return nil, err } return req, nil } // MaxBytesReader is similar to io.LimitReader but is intended for // limiting the size of incoming request bodies. In contrast to // io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a // non-EOF error for a Read beyond the limit, and Closes the // underlying reader when its Close method is called. // // MaxBytesReader prevents clients from accidentally or maliciously // sending a large request and wasting server resources. func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser { return &maxBytesReader{w: w, r: r, n: n} } type maxBytesReader struct { w ResponseWriter r io.ReadCloser // underlying reader n int64 // max bytes remaining stopped bool } func (l *maxBytesReader) Read(p []byte) (n int, err error) { if l.n <= 0 { if !l.stopped { l.stopped = true if res, ok := l.w.(*response); ok { res.requestTooLarge() } } return 0, errors.New("http: request body too large") } if int64(len(p)) > l.n { p = p[:l.n] } n, err = l.r.Read(p) l.n -= int64(n) return } func (l *maxBytesReader) Close() error { return l.r.Close() } func copyValues(dst, src url.Values) { for k, vs := range src { for _, value := range vs { dst.Add(k, value) } } } func parsePostForm(r *Request) (vs url.Values, err error) { if r.Body == nil { err = errors.New("missing form body") return } ct := r.Header.Get("Content-Type") ct, _, err = mime.ParseMediaType(ct) switch { case ct == "application/x-www-form-urlencoded": var reader io.Reader = r.Body maxFormSize := int64(1<<63 - 1) if _, ok := r.Body.(*maxBytesReader); !ok { maxFormSize = int64(10 << 20) // 10 MB is a lot of text. reader = io.LimitReader(r.Body, maxFormSize+1) } b, e := ioutil.ReadAll(reader) if e != nil { if err == nil { err = e } break } if int64(len(b)) > maxFormSize { err = errors.New("http: POST too large") return } vs, e = url.ParseQuery(string(b)) if err == nil { err = e } case ct == "multipart/form-data": // handled by ParseMultipartForm (which is calling us, or should be) // TODO(bradfitz): there are too many possible // orders to call too many functions here. // Clean this up and write more tests. // request_test.go contains the start of this, // in TestRequestMultipartCallOrder. } return } // ParseForm parses the raw query from the URL and updates r.Form. // // For POST or PUT requests, it also parses the request body as a form and // put the results into both r.PostForm and r.Form. // POST and PUT body parameters take precedence over URL query string values // in r.Form. // // If the request Body's size has not already been limited by MaxBytesReader, // the size is capped at 10MB. // // ParseMultipartForm calls ParseForm automatically. // It is idempotent. func (r *Request) ParseForm() error { var err error if r.PostForm == nil { if r.Method == "POST" || r.Method == "PUT" { r.PostForm, err = parsePostForm(r) } if r.PostForm == nil { r.PostForm = make(url.Values) } } if r.Form == nil { if len(r.PostForm) > 0 { r.Form = make(url.Values) copyValues(r.Form, r.PostForm) } var newValues url.Values if r.URL != nil { var e error newValues, e = url.ParseQuery(r.URL.RawQuery) if err == nil { err = e } } if newValues == nil { newValues = make(url.Values) } if r.Form == nil { r.Form = newValues } else { copyValues(r.Form, newValues) } } return err } // ParseMultipartForm parses a request body as multipart/form-data. // The whole request body is parsed and up to a total of maxMemory bytes of // its file parts are stored in memory, with the remainder stored on // disk in temporary files. // ParseMultipartForm calls ParseForm if necessary. // After one call to ParseMultipartForm, subsequent calls have no effect. func (r *Request) ParseMultipartForm(maxMemory int64) error { if r.MultipartForm == multipartByReader { return errors.New("http: multipart handled by MultipartReader") } if r.Form == nil { err := r.ParseForm() if err != nil { return err } } if r.MultipartForm != nil { return nil } mr, err := r.multipartReader() if err == ErrNotMultipart { return nil } else if err != nil { return err } f, err := mr.ReadForm(maxMemory) if err != nil { return err } for k, v := range f.Value { r.Form[k] = append(r.Form[k], v...) } r.MultipartForm = f return nil } // FormValue returns the first value for the named component of the query. // POST and PUT body parameters take precedence over URL query string values. // FormValue calls ParseMultipartForm and ParseForm if necessary. // To access multiple values of the same key use ParseForm. func (r *Request) FormValue(key string) string { if r.Form == nil { r.ParseMultipartForm(defaultMaxMemory) } if vs := r.Form[key]; len(vs) > 0 { return vs[0] } return "" } // PostFormValue returns the first value for the named component of the POST // or PUT request body. URL query parameters are ignored. // PostFormValue calls ParseMultipartForm and ParseForm if necessary. func (r *Request) PostFormValue(key string) string { if r.PostForm == nil { r.ParseMultipartForm(defaultMaxMemory) } if vs := r.PostForm[key]; len(vs) > 0 { return vs[0] } return "" } // FormFile returns the first file for the provided form key. // FormFile calls ParseMultipartForm and ParseForm if necessary. func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) { if r.MultipartForm == multipartByReader { return nil, nil, errors.New("http: multipart handled by MultipartReader") } if r.MultipartForm == nil { err := r.ParseMultipartForm(defaultMaxMemory) if err != nil { return nil, nil, err } } if r.MultipartForm != nil && r.MultipartForm.File != nil { if fhs := r.MultipartForm.File[key]; len(fhs) > 0 { f, err := fhs[0].Open() return f, fhs[0], err } } return nil, nil, ErrMissingFile } func (r *Request) expectsContinue() bool { return hasToken(r.Header.get("Expect"), "100-continue") } func (r *Request) wantsHttp10KeepAlive() bool { if r.ProtoMajor != 1 || r.ProtoMinor != 0 { return false } return hasToken(r.Header.get("Connection"), "keep-alive") } func (r *Request) wantsClose() bool { return hasToken(r.Header.get("Connection"), "close") } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/net/internal/internal.go ================================================ package internalSdkPackage import "fmt" func InternalSdkFunction() { fmt.Println("I'm internal SDK function") } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/net/url/url.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package url parses URLs and implements query escaping. // See RFC 3986. package url import ( "bytes" "errors" "sort" "strconv" "strings" ) // Error reports an error and the operation and URL that caused it. type Error struct { Op string URL string Err error } func (e *Error) Error() string { return e.Op + " " + e.URL + ": " + e.Err.Error() } func ishex(c byte) bool { switch { case '0' <= c && c <= '9': return true case 'a' <= c && c <= 'f': return true case 'A' <= c && c <= 'F': return true } return false } func unhex(c byte) byte { switch { case '0' <= c && c <= '9': return c - '0' case 'a' <= c && c <= 'f': return c - 'a' + 10 case 'A' <= c && c <= 'F': return c - 'A' + 10 } return 0 } type encoding int const ( encodePath encoding = 1 + iota encodeUserPassword encodeQueryComponent encodeFragment ) type EscapeError string func (e EscapeError) Error() string { return "invalid URL escape " + strconv.Quote(string(e)) } // Return true if the specified character should be escaped when // appearing in a URL string, according to RFC 3986. func shouldEscape(c byte, mode encoding) bool { // §2.3 Unreserved characters (alphanum) if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { return false } switch c { case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) return false case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) // Different sections of the URL allow a few of // the reserved characters to appear unescaped. switch mode { case encodePath: // §3.3 // The RFC allows : @ & = + $ but saves / ; , for assigning // meaning to individual path segments. This package // only manipulates the path as a whole, so we allow those // last two as well. That leaves only ? to escape. return c == '?' case encodeUserPassword: // §3.2.1 // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in // userinfo, so we must escape only '@', '/', and '?'. // The parsing of userinfo treats ':' as special so we must escape // that too. return c == '@' || c == '/' || c == '?' || c == ':' case encodeQueryComponent: // §3.4 // The RFC reserves (so we must escape) everything. return true case encodeFragment: // §4.1 // The RFC text is silent but the grammar allows // everything, so escape nothing. return false } } // Everything else must be escaped. return true } // QueryUnescape does the inverse transformation of QueryEscape, converting // %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if // any % is not followed by two hexadecimal digits. func QueryUnescape(s string) (string, error) { return unescape(s, encodeQueryComponent) } // unescape unescapes a string; the mode specifies // which section of the URL string is being unescaped. func unescape(s string, mode encoding) (string, error) { // Count %, check that they're well-formed. n := 0 hasPlus := false for i := 0; i < len(s); { switch s[i] { case '%': n++ if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { s = s[i:] if len(s) > 3 { s = s[0:3] } return "", EscapeError(s) } i += 3 case '+': hasPlus = mode == encodeQueryComponent i++ default: i++ } } if n == 0 && !hasPlus { return s, nil } t := make([]byte, len(s)-2*n) j := 0 for i := 0; i < len(s); { switch s[i] { case '%': t[j] = unhex(s[i+1])<<4 | unhex(s[i+2]) j++ i += 3 case '+': if mode == encodeQueryComponent { t[j] = ' ' } else { t[j] = '+' } j++ i++ default: t[j] = s[i] j++ i++ } } return string(t), nil } // QueryEscape escapes the string so it can be safely placed // inside a URL query. func QueryEscape(s string) string { return escape(s, encodeQueryComponent) } func escape(s string, mode encoding) string { spaceCount, hexCount := 0, 0 for i := 0; i < len(s); i++ { c := s[i] if shouldEscape(c, mode) { if c == ' ' && mode == encodeQueryComponent { spaceCount++ } else { hexCount++ } } } if spaceCount == 0 && hexCount == 0 { return s } t := make([]byte, len(s)+2*hexCount) j := 0 for i := 0; i < len(s); i++ { switch c := s[i]; { case c == ' ' && mode == encodeQueryComponent: t[j] = '+' j++ case shouldEscape(c, mode): t[j] = '%' t[j+1] = "0123456789ABCDEF"[c>>4] t[j+2] = "0123456789ABCDEF"[c&15] j += 3 default: t[j] = s[i] j++ } } return string(t) } // A URL represents a parsed URL (technically, a URI reference). // The general form represented is: // // scheme://[userinfo@]host/path[?query][#fragment] // // URLs that do not start with a slash after the scheme are interpreted as: // // scheme:opaque[?query][#fragment] // // Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. // A consequence is that it is impossible to tell which slashes in the Path were // slashes in the raw URL and which were %2f. This distinction is rarely important, // but when it is a client must use other routines to parse the raw URL or construct // the parsed URL. For example, an HTTP server can consult req.RequestURI, and // an HTTP client can use URL{Host: "example.com", Opaque: "//example.com/Go%2f"} // instead of URL{Host: "example.com", Path: "/Go/"}. type URL struct { Scheme string Opaque string // encoded opaque data User *Userinfo // username and password information Host string // host or host:port Path string RawQuery string // encoded query values, without '?' Fragment string // fragment for references, without '#' } // User returns a Userinfo containing the provided username // and no password set. func User(username string) *Userinfo { return &Userinfo{username, "", false} } // UserPassword returns a Userinfo containing the provided username // and password. // This functionality should only be used with legacy web sites. // RFC 2396 warns that interpreting Userinfo this way // ``is NOT RECOMMENDED, because the passing of authentication // information in clear text (such as URI) has proven to be a // security risk in almost every case where it has been used.'' func UserPassword(username, password string) *Userinfo { return &Userinfo{username, password, true} } // The Userinfo type is an immutable encapsulation of username and // password details for a URL. An existing Userinfo value is guaranteed // to have a username set (potentially empty, as allowed by RFC 2396), // and optionally a password. type Userinfo struct { username string password string passwordSet bool } // Username returns the username. func (u *Userinfo) Username() string { return u.username } // Password returns the password in case it is set, and whether it is set. func (u *Userinfo) Password() (string, bool) { if u.passwordSet { return u.password, true } return "", false } // String returns the encoded userinfo information in the standard form // of "username[:password]". func (u *Userinfo) String() string { s := escape(u.username, encodeUserPassword) if u.passwordSet { s += ":" + escape(u.password, encodeUserPassword) } return s } // Maybe rawurl is of the form scheme:path. // (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*) // If so, return scheme, path; else return "", rawurl. func getscheme(rawurl string) (scheme, path string, err error) { for i := 0; i < len(rawurl); i++ { c := rawurl[i] switch { case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z': // do nothing case '0' <= c && c <= '9' || c == '+' || c == '-' || c == '.': if i == 0 { return "", rawurl, nil } case c == ':': if i == 0 { return "", "", errors.New("missing protocol scheme") } return rawurl[0:i], rawurl[i+1:], nil default: // we have encountered an invalid character, // so there is no valid scheme return "", rawurl, nil } } return "", rawurl, nil } // Maybe s is of the form t c u. // If so, return t, c u (or t, u if cutc == true). // If not, return s, "". func split(s string, c string, cutc bool) (string, string) { i := strings.Index(s, c) if i < 0 { return s, "" } if cutc { return s[0:i], s[i+len(c):] } return s[0:i], s[i:] } // Parse parses rawurl into a URL structure. // The rawurl may be relative or absolute. func Parse(rawurl string) (url *URL, err error) { // Cut off #frag u, frag := split(rawurl, "#", true) if url, err = parse(u, false); err != nil { return nil, err } if frag == "" { return url, nil } if url.Fragment, err = unescape(frag, encodeFragment); err != nil { return nil, &Error{"parse", rawurl, err} } return url, nil } // ParseRequestURI parses rawurl into a URL structure. It assumes that // rawurl was received in an HTTP request, so the rawurl is interpreted // only as an absolute URI or an absolute path. // The string rawurl is assumed not to have a #fragment suffix. // (Web browsers strip #fragment before sending the URL to a web server.) func ParseRequestURI(rawurl string) (url *URL, err error) { return parse(rawurl, true) } // parse parses a URL from a string in one of two contexts. If // viaRequest is true, the URL is assumed to have arrived via an HTTP request, // in which case only absolute URLs or path-absolute relative URLs are allowed. // If viaRequest is false, all forms of relative URLs are allowed. func parse(rawurl string, viaRequest bool) (url *URL, err error) { var rest string if rawurl == "" && viaRequest { err = errors.New("empty url") goto Error } url = new(URL) if rawurl == "*" { url.Path = "*" return } // Split off possible leading "http:", "mailto:", etc. // Cannot contain escaped characters. if url.Scheme, rest, err = getscheme(rawurl); err != nil { goto Error } url.Scheme = strings.ToLower(url.Scheme) rest, url.RawQuery = split(rest, "?", true) if !strings.HasPrefix(rest, "/") { if url.Scheme != "" { // We consider rootless paths per RFC 3986 as opaque. url.Opaque = rest return url, nil } if viaRequest { err = errors.New("invalid URI for request") goto Error } } if (url.Scheme != "" || !viaRequest && !strings.HasPrefix(rest, "///")) && strings.HasPrefix(rest, "//") { var authority string authority, rest = split(rest[2:], "/", false) url.User, url.Host, err = parseAuthority(authority) if err != nil { goto Error } if strings.Contains(url.Host, "%") { err = errors.New("hexadecimal escape in host") goto Error } } if url.Path, err = unescape(rest, encodePath); err != nil { goto Error } return url, nil Error: return nil, &Error{"parse", rawurl, err} } func parseAuthority(authority string) (user *Userinfo, host string, err error) { i := strings.LastIndex(authority, "@") if i < 0 { host = authority return } userinfo, host := authority[:i], authority[i+1:] if strings.Index(userinfo, ":") < 0 { if userinfo, err = unescape(userinfo, encodeUserPassword); err != nil { return } user = User(userinfo) } else { username, password := split(userinfo, ":", true) if username, err = unescape(username, encodeUserPassword); err != nil { return } if password, err = unescape(password, encodeUserPassword); err != nil { return } user = UserPassword(username, password) } return } // String reassembles the URL into a valid URL string. // The general form of the result is one of: // // scheme:opaque // scheme://userinfo@host/path?query#fragment // // If u.Opaque is non-empty, String uses the first form; // otherwise it uses the second form. // // In the second form, the following rules apply: // - if u.Scheme is empty, scheme: is omitted. // - if u.User is nil, userinfo@ is omitted. // - if u.Host is empty, host/ is omitted. // - if u.Scheme and u.Host are empty and u.User is nil, // the entire scheme://userinfo@host/ is omitted. // - if u.Host is non-empty and u.Path begins with a /, // the form host/path does not add its own /. // - if u.RawQuery is empty, ?query is omitted. // - if u.Fragment is empty, #fragment is omitted. func (u *URL) String() string { var buf bytes.Buffer if u.Scheme != "" { buf.WriteString(u.Scheme) buf.WriteByte(':') } if u.Opaque != "" { buf.WriteString(u.Opaque) } else { if u.Scheme != "" || u.Host != "" || u.User != nil { buf.WriteString("//") if ui := u.User; ui != nil { buf.WriteString(ui.String()) buf.WriteByte('@') } if h := u.Host; h != "" { buf.WriteString(h) } } if u.Path != "" && u.Path[0] != '/' && u.Host != "" { buf.WriteByte('/') } buf.WriteString(escape(u.Path, encodePath)) } if u.RawQuery != "" { buf.WriteByte('?') buf.WriteString(u.RawQuery) } if u.Fragment != "" { buf.WriteByte('#') buf.WriteString(escape(u.Fragment, encodeFragment)) } return buf.String() } // Values maps a string key to a list of values. // It is typically used for query parameters and form values. // Unlike in the http.Header map, the keys in a Values map // are case-sensitive. type Values map[string][]string // Get gets the first value associated with the given key. // If there are no values associated with the key, Get returns // the empty string. To access multiple values, use the map // directly. func (v Values) Get(key string) string { if v == nil { return "" } vs, ok := v[key] if !ok || len(vs) == 0 { return "" } return vs[0] } // Set sets the key to value. It replaces any existing // values. func (v Values) Set(key, value string) { v[key] = []string{value} } // Add adds the value to key. It appends to any existing // values associated with key. func (v Values) Add(key, value string) { v[key] = append(v[key], value) } // Del deletes the values associated with key. func (v Values) Del(key string) { delete(v, key) } // ParseQuery parses the URL-encoded query string and returns // a map listing the values specified for each key. // ParseQuery always returns a non-nil map containing all the // valid query parameters found; err describes the first decoding error // encountered, if any. func ParseQuery(query string) (m Values, err error) { m = make(Values) err = parseQuery(m, query) return } func parseQuery(m Values, query string) (err error) { for query != "" { key := query if i := strings.IndexAny(key, "&;"); i >= 0 { key, query = key[:i], key[i+1:] } else { query = "" } if key == "" { continue } value := "" if i := strings.Index(key, "="); i >= 0 { key, value = key[:i], key[i+1:] } key, err1 := QueryUnescape(key) if err1 != nil { if err == nil { err = err1 } continue } value, err1 = QueryUnescape(value) if err1 != nil { if err == nil { err = err1 } continue } m[key] = append(m[key], value) } return err } // Encode encodes the values into ``URL encoded'' form // ("bar=baz&foo=quux") sorted by key. func (v Values) Encode() string { if v == nil { return "" } var buf bytes.Buffer keys := make([]string, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { vs := v[k] prefix := QueryEscape(k) + "=" for _, v := range vs { if buf.Len() > 0 { buf.WriteByte('&') } buf.WriteString(prefix) buf.WriteString(QueryEscape(v)) } } return buf.String() } // resolvePath applies special path segments from refs and applies // them to base, per RFC 3986. func resolvePath(base, ref string) string { var full string if ref == "" { full = base } else if ref[0] != '/' { i := strings.LastIndex(base, "/") full = base[:i+1] + ref } else { full = ref } if full == "" { return "" } var dst []string src := strings.Split(full, "/") for _, elem := range src { switch elem { case ".": // drop case "..": if len(dst) > 0 { dst = dst[:len(dst)-1] } default: dst = append(dst, elem) } } if last := src[len(src)-1]; last == "." || last == ".." { // Add final slash to the joined path. dst = append(dst, "") } return "/" + strings.TrimLeft(strings.Join(dst, "/"), "/") } // IsAbs returns true if the URL is absolute. func (u *URL) IsAbs() bool { return u.Scheme != "" } // Parse parses a URL in the context of the receiver. The provided URL // may be relative or absolute. Parse returns nil, err on parse // failure, otherwise its return value is the same as ResolveReference. func (u *URL) Parse(ref string) (*URL, error) { refurl, err := Parse(ref) if err != nil { return nil, err } return u.ResolveReference(refurl), nil } // ResolveReference resolves a URI reference to an absolute URI from // an absolute base URI, per RFC 3986 Section 5.2. The URI reference // may be relative or absolute. ResolveReference always returns a new // URL instance, even if the returned URL is identical to either the // base or reference. If ref is an absolute URL, then ResolveReference // ignores base and returns a copy of ref. func (u *URL) ResolveReference(ref *URL) *URL { url := *ref if ref.Scheme == "" { url.Scheme = u.Scheme } if ref.Scheme != "" || ref.Host != "" || ref.User != nil { // The "absoluteURI" or "net_path" cases. url.Path = resolvePath(ref.Path, "") return &url } if ref.Opaque != "" { url.User = nil url.Host = "" url.Path = "" return &url } if ref.Path == "" { if ref.RawQuery == "" { url.RawQuery = u.RawQuery if ref.Fragment == "" { url.Fragment = u.Fragment } } } // The "abs_path" or "rel_path" cases. url.Host = u.Host url.User = u.User url.Path = resolvePath(u.Path, ref.Path) return &url } // Query parses RawQuery and returns the corresponding values. func (u *URL) Query() Values { v, _ := ParseQuery(u.RawQuery) return v } // RequestURI returns the encoded path?query or opaque?query // string that would be used in an HTTP request for u. func (u *URL) RequestURI() string { result := u.Opaque if result == "" { result = escape(u.Path, encodePath) if result == "" { result = "/" } } else { if strings.HasPrefix(result, "//") { result = u.Scheme + ":" + result } } if u.RawQuery != "" { result += "?" + u.RawQuery } return result } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/os/file.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package os provides a platform-independent interface to operating system // functionality. The design is Unix-like, although the error handling is // Go-like; failing calls return values of type error rather than error numbers. // Often, more information is available within the error. For example, // if a call that takes a file name fails, such as Open or Stat, the error // will include the failing file name when printed and will be of type // *PathError, which may be unpacked for more information. // // The os interface is intended to be uniform across all operating systems. // Features not generally available appear in the system-specific package syscall. // // Here is a simple example, opening a file and reading some of it. // // file, err := os.Open("file.go") // For read access. // if err != nil { // log.Fatal(err) // } // // If the open fails, the error string will be self-explanatory, like // // open file.go: no such file or directory // // The file's data can then be read into a slice of bytes. Read and // Write take their byte counts from the length of the argument slice. // // data := make([]byte, 100) // count, err := file.Read(data) // if err != nil { // log.Fatal(err) // } // fmt.Printf("read %d bytes: %q\n", count, data[:count]) // package os import ( "io" "syscall" ) type File struct { *file } func (file *File) Close() error { if file == nil { return ErrInvalid } return file.file.close() } // file is the real representation of *File. // The extra level of indirection ensures that no clients of os // can overwrite this data, which could cause the finalizer // to close the wrong file descriptor. type file struct { fd int name string dirinfo *dirInfo // nil unless directory being read nepipe int32 // number of consecutive EPIPE in Write } // Name returns the name of the file as presented to Open. func (f *File) Name() string { return f.name } // Stdin, Stdout, and Stderr are open Files pointing to the standard input, // standard output, and standard error file descriptors. var ( Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") ) // Flags to Open wrapping those of the underlying system. Not all flags // may be implemented on a given system. const ( O_RDONLY int = syscall.O_RDONLY // open the file read-only. O_WRONLY int = syscall.O_WRONLY // open the file write-only. O_RDWR int = syscall.O_RDWR // open the file read-write. O_APPEND int = syscall.O_APPEND // append data to the file when writing. O_CREATE int = syscall.O_CREAT // create a new file if none exists. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist O_SYNC int = syscall.O_SYNC // open for synchronous I/O. O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened. ) // Seek whence values. const ( SEEK_SET int = 0 // seek relative to the origin of the file SEEK_CUR int = 1 // seek relative to the current offset SEEK_END int = 2 // seek relative to the end ) // LinkError records an error during a link or symlink or rename // system call and the paths that caused it. type LinkError struct { Op string Old string New string Err error } func (e *LinkError) Error() string { return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error() } // Read reads up to len(b) bytes from the File. // It returns the number of bytes read and an error, if any. // EOF is signaled by a zero count with err set to io.EOF. func (f *File) Read(b []byte) (n int, err error) { if f == nil { return 0, ErrInvalid } n, e := f.read(b) if n < 0 { n = 0 } if n == 0 && len(b) > 0 && e == nil { return 0, io.EOF } if e != nil { err = &PathError{"read", f.name, e} } return n, err } // ReadAt reads len(b) bytes from the File starting at byte offset off. // It returns the number of bytes read and the error, if any. // ReadAt always returns a non-nil error when n < len(b). // At end of file, that error is io.EOF. func (f *File) ReadAt(b []byte, off int64) (n int, err error) { if f == nil { return 0, ErrInvalid } for len(b) > 0 { m, e := f.pread(b, off) if m == 0 && e == nil { return n, io.EOF } if e != nil { err = &PathError{"read", f.name, e} break } n += m b = b[m:] off += int64(m) } return } // Write writes len(b) bytes to the File. // It returns the number of bytes written and an error, if any. // Write returns a non-nil error when n != len(b). func (f *File) Write(b []byte) (n int, err error) { if f == nil { return 0, ErrInvalid } n, e := f.write(b) if n < 0 { n = 0 } if n != len(b) { err = io.ErrShortWrite } epipecheck(f, e) if e != nil { err = &PathError{"write", f.name, e} } return n, err } // WriteAt writes len(b) bytes to the File starting at byte offset off. // It returns the number of bytes written and an error, if any. // WriteAt returns a non-nil error when n != len(b). func (f *File) WriteAt(b []byte, off int64) (n int, err error) { if f == nil { return 0, ErrInvalid } for len(b) > 0 { m, e := f.pwrite(b, off) if e != nil { err = &PathError{"write", f.name, e} break } n += m b = b[m:] off += int64(m) } return } // Seek sets the offset for the next Read or Write on file to offset, interpreted // according to whence: 0 means relative to the origin of the file, 1 means // relative to the current offset, and 2 means relative to the end. // It returns the new offset and an error, if any. func (f *File) Seek(offset int64, whence int) (ret int64, err error) { if f == nil { return 0, ErrInvalid } r, e := f.seek(offset, whence) if e == nil && f.dirinfo != nil && r != 0 { e = syscall.EISDIR } if e != nil { return 0, &PathError{"seek", f.name, e} } return r, nil } // WriteString is like Write, but writes the contents of string s rather than // a slice of bytes. func (f *File) WriteString(s string) (ret int, err error) { if f == nil { return 0, ErrInvalid } return f.Write([]byte(s)) } // Mkdir creates a new directory with the specified name and permission bits. // If there is an error, it will be of type *PathError. func Mkdir(name string, perm FileMode) error { e := syscall.Mkdir(name, syscallMode(perm)) if e != nil { return &PathError{"mkdir", name, e} } return nil } // Chdir changes the current working directory to the named directory. // If there is an error, it will be of type *PathError. func Chdir(dir string) error { if e := syscall.Chdir(dir); e != nil { return &PathError{"chdir", dir, e} } return nil } // Chdir changes the current working directory to the file, // which must be a directory. // If there is an error, it will be of type *PathError. func (f *File) Chdir() error { if f == nil { return ErrInvalid } if e := syscall.Fchdir(f.fd); e != nil { return &PathError{"chdir", f.name, e} } return nil } // Open opens the named file for reading. If successful, methods on // the returned file can be used for reading; the associated file // descriptor has mode O_RDONLY. // If there is an error, it will be of type *PathError. func Open(name string) (file *File, err error) { return OpenFile(name, O_RDONLY, 0) } // Create creates the named file mode 0666 (before umask), truncating // it if it already exists. If successful, methods on the returned // File can be used for I/O; the associated file descriptor has mode // O_RDWR. // If there is an error, it will be of type *PathError. func Create(name string) (file *File, err error) { return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666) } // lstat is overridden in tests. var lstat = Lstat // Rename renames (moves) a file. OS-specific restrictions might apply. func Rename(oldpath, newpath string) error { return rename(oldpath, newpath) } // Many functions in package syscall return a count of -1 instead of 0. // Using fixCount(call()) instead of call() corrects the count. func fixCount(n int, err error) (int, error) { if n < 0 { n = 0 } return n, err } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/regexp/regexp.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package regexp implements regular expression search. // // The syntax of the regular expressions accepted is the same // general syntax used by Perl, Python, and other languages. // More precisely, it is the syntax accepted by RE2 and described at // https://golang.org/s/re2syntax, except for \C. // For an overview of the syntax, run // go doc regexp/syntax // // The regexp implementation provided by this package is // guaranteed to run in time linear in the size of the input. // (This is a property not guaranteed by most open source // implementations of regular expressions.) For more information // about this property, see // http://swtch.com/~rsc/regexp/regexp1.html // or any book about automata theory. // // All characters are UTF-8-encoded code points. // // There are 16 methods of Regexp that match a regular expression and identify // the matched text. Their names are matched by this regular expression: // // Find(All)?(String)?(Submatch)?(Index)? // // If 'All' is present, the routine matches successive non-overlapping // matches of the entire expression. Empty matches abutting a preceding // match are ignored. The return value is a slice containing the successive // return values of the corresponding non-'All' routine. These routines take // an extra integer argument, n; if n >= 0, the function returns at most n // matches/submatches. // // If 'String' is present, the argument is a string; otherwise it is a slice // of bytes; return values are adjusted as appropriate. // // If 'Submatch' is present, the return value is a slice identifying the // successive submatches of the expression. Submatches are matches of // parenthesized subexpressions (also known as capturing groups) within the // regular expression, numbered from left to right in order of opening // parenthesis. Submatch 0 is the match of the entire expression, submatch 1 // the match of the first parenthesized subexpression, and so on. // // If 'Index' is present, matches and submatches are identified by byte index // pairs within the input string: result[2*n:2*n+1] identifies the indexes of // the nth submatch. The pair for n==0 identifies the match of the entire // expression. If 'Index' is not present, the match is identified by the // text of the match/submatch. If an index is negative, it means that // subexpression did not match any string in the input. // // There is also a subset of the methods that can be applied to text read // from a RuneReader: // // MatchReader, FindReaderIndex, FindReaderSubmatchIndex // // This set may grow. Note that regular expression matches may need to // examine text beyond the text returned by a match, so the methods that // match text from a RuneReader may read arbitrarily far into the input // before returning. // // (There are a few other methods that do not match this pattern.) // package regexp import ( "bytes" "io" "regexp/syntax" "strconv" "strings" "sync" "unicode" "unicode/utf8" ) var debug = false // Regexp is the representation of a compiled regular expression. // A Regexp is safe for concurrent use by multiple goroutines. type Regexp struct { // read-only after Compile expr string // as passed to Compile prog *syntax.Prog // compiled program onepass *onePassProg // onepass program or nil prefix string // required prefix in unanchored matches prefixBytes []byte // prefix, as a []byte prefixComplete bool // prefix is the entire regexp prefixRune rune // first rune in prefix prefixEnd uint32 // pc for last rune in prefix cond syntax.EmptyOp // empty-width conditions required at start of match numSubexp int subexpNames []string longest bool // cache of machines for running regexp mu sync.Mutex machine []*machine } // String returns the source text used to compile the regular expression. func (re *Regexp) String() string { return re.expr } // Copy returns a new Regexp object copied from re. // // When using a Regexp in multiple goroutines, giving each goroutine // its own copy helps to avoid lock contention. func (re *Regexp) Copy() *Regexp { r := *re r.mu = sync.Mutex{} r.machine = nil return &r } // Compile parses a regular expression and returns, if successful, // a Regexp object that can be used to match against text. // // When matching against text, the regexp returns a match that // begins as early as possible in the input (leftmost), and among those // it chooses the one that a backtracking search would have found first. // This so-called leftmost-first matching is the same semantics // that Perl, Python, and other implementations use, although this // package implements it without the expense of backtracking. // For POSIX leftmost-longest matching, see CompilePOSIX. func Compile(expr string) (*Regexp, error) { return compile(expr, syntax.Perl, false) } // CompilePOSIX is like Compile but restricts the regular expression // to POSIX ERE (egrep) syntax and changes the match semantics to // leftmost-longest. // // That is, when matching against text, the regexp returns a match that // begins as early as possible in the input (leftmost), and among those // it chooses a match that is as long as possible. // This so-called leftmost-longest matching is the same semantics // that early regular expression implementations used and that POSIX // specifies. // // However, there can be multiple leftmost-longest matches, with different // submatch choices, and here this package diverges from POSIX. // Among the possible leftmost-longest matches, this package chooses // the one that a backtracking search would have found first, while POSIX // specifies that the match be chosen to maximize the length of the first // subexpression, then the second, and so on from left to right. // The POSIX rule is computationally prohibitive and not even well-defined. // See http://swtch.com/~rsc/regexp/regexp2.html#posix for details. func CompilePOSIX(expr string) (*Regexp, error) { return compile(expr, syntax.POSIX, true) } // Longest makes future searches prefer the leftmost-longest match. // That is, when matching against text, the regexp returns a match that // begins as early as possible in the input (leftmost), and among those // it chooses a match that is as long as possible. func (re *Regexp) Longest() { re.longest = true } func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) { re, err := syntax.Parse(expr, mode) if err != nil { return nil, err } maxCap := re.MaxCap() capNames := re.CapNames() re = re.Simplify() prog, err := syntax.Compile(re) if err != nil { return nil, err } regexp := &Regexp{ expr: expr, prog: prog, onepass: compileOnePass(prog), numSubexp: maxCap, subexpNames: capNames, cond: prog.StartCond(), longest: longest, } if regexp.onepass == notOnePass { regexp.prefix, regexp.prefixComplete = prog.Prefix() } else { regexp.prefix, regexp.prefixComplete, regexp.prefixEnd = onePassPrefix(prog) } if regexp.prefix != "" { // TODO(rsc): Remove this allocation by adding // IndexString to package bytes. regexp.prefixBytes = []byte(regexp.prefix) regexp.prefixRune, _ = utf8.DecodeRuneInString(regexp.prefix) } return regexp, nil } // get returns a machine to use for matching re. // It uses the re's machine cache if possible, to avoid // unnecessary allocation. func (re *Regexp) get() *machine { re.mu.Lock() if n := len(re.machine); n > 0 { z := re.machine[n-1] re.machine = re.machine[:n-1] re.mu.Unlock() return z } re.mu.Unlock() z := progMachine(re.prog, re.onepass) z.re = re return z } // put returns a machine to the re's machine cache. // There is no attempt to limit the size of the cache, so it will // grow to the maximum number of simultaneous matches // run using re. (The cache empties when re gets garbage collected.) func (re *Regexp) put(z *machine) { re.mu.Lock() re.machine = append(re.machine, z) re.mu.Unlock() } // MustCompile is like Compile but panics if the expression cannot be parsed. // It simplifies safe initialization of global variables holding compiled regular // expressions. func MustCompile(str string) *Regexp { regexp, error := Compile(str) if error != nil { panic(`regexp: Compile(` + quote(str) + `): ` + error.Error()) } return regexp } // MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed. // It simplifies safe initialization of global variables holding compiled regular // expressions. func MustCompilePOSIX(str string) *Regexp { regexp, error := CompilePOSIX(str) if error != nil { panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.Error()) } return regexp } func quote(s string) string { if strconv.CanBackquote(s) { return "`" + s + "`" } return strconv.Quote(s) } // NumSubexp returns the number of parenthesized subexpressions in this Regexp. func (re *Regexp) NumSubexp() int { return re.numSubexp } // SubexpNames returns the names of the parenthesized subexpressions // in this Regexp. The name for the first sub-expression is names[1], // so that if m is a match slice, the name for m[i] is SubexpNames()[i]. // Since the Regexp as a whole cannot be named, names[0] is always // the empty string. The slice should not be modified. func (re *Regexp) SubexpNames() []string { return re.subexpNames } const endOfText rune = -1 // input abstracts different representations of the input text. It provides // one-character lookahead. type input interface { step(pos int) (r rune, width int) // advance one rune canCheckPrefix() bool // can we look ahead without losing info? hasPrefix(re *Regexp) bool index(re *Regexp, pos int) int context(pos int) syntax.EmptyOp } // inputString scans a string. type inputString struct { str string } func (i *inputString) step(pos int) (rune, int) { if pos < len(i.str) { c := i.str[pos] if c < utf8.RuneSelf { return rune(c), 1 } return utf8.DecodeRuneInString(i.str[pos:]) } return endOfText, 0 } func (i *inputString) canCheckPrefix() bool { return true } func (i *inputString) hasPrefix(re *Regexp) bool { return strings.HasPrefix(i.str, re.prefix) } func (i *inputString) index(re *Regexp, pos int) int { return strings.Index(i.str[pos:], re.prefix) } func (i *inputString) context(pos int) syntax.EmptyOp { r1, r2 := endOfText, endOfText if pos > 0 && pos <= len(i.str) { r1, _ = utf8.DecodeLastRuneInString(i.str[:pos]) } if pos < len(i.str) { r2, _ = utf8.DecodeRuneInString(i.str[pos:]) } return syntax.EmptyOpContext(r1, r2) } // inputBytes scans a byte slice. type inputBytes struct { str []byte } func (i *inputBytes) step(pos int) (rune, int) { if pos < len(i.str) { c := i.str[pos] if c < utf8.RuneSelf { return rune(c), 1 } return utf8.DecodeRune(i.str[pos:]) } return endOfText, 0 } func (i *inputBytes) canCheckPrefix() bool { return true } func (i *inputBytes) hasPrefix(re *Regexp) bool { return bytes.HasPrefix(i.str, re.prefixBytes) } func (i *inputBytes) index(re *Regexp, pos int) int { return bytes.Index(i.str[pos:], re.prefixBytes) } func (i *inputBytes) context(pos int) syntax.EmptyOp { r1, r2 := endOfText, endOfText if pos > 0 && pos <= len(i.str) { r1, _ = utf8.DecodeLastRune(i.str[:pos]) } if pos < len(i.str) { r2, _ = utf8.DecodeRune(i.str[pos:]) } return syntax.EmptyOpContext(r1, r2) } // inputReader scans a RuneReader. type inputReader struct { r io.RuneReader atEOT bool pos int } func (i *inputReader) step(pos int) (rune, int) { if !i.atEOT && pos != i.pos { return endOfText, 0 } r, w, err := i.r.ReadRune() if err != nil { i.atEOT = true return endOfText, 0 } i.pos += w return r, w } func (i *inputReader) canCheckPrefix() bool { return false } func (i *inputReader) hasPrefix(re *Regexp) bool { return false } func (i *inputReader) index(re *Regexp, pos int) int { return -1 } func (i *inputReader) context(pos int) syntax.EmptyOp { return 0 } // LiteralPrefix returns a literal string that must begin any match // of the regular expression re. It returns the boolean true if the // literal string comprises the entire regular expression. func (re *Regexp) LiteralPrefix() (prefix string, complete bool) { return re.prefix, re.prefixComplete } // MatchReader reports whether the Regexp matches the text read by the // RuneReader. func (re *Regexp) MatchReader(r io.RuneReader) bool { return re.doExecute(r, nil, "", 0, 0) != nil } // MatchString reports whether the Regexp matches the string s. func (re *Regexp) MatchString(s string) bool { return re.doExecute(nil, nil, s, 0, 0) != nil } // Match reports whether the Regexp matches the byte slice b. func (re *Regexp) Match(b []byte) bool { return re.doExecute(nil, b, "", 0, 0) != nil } // MatchReader checks whether a textual regular expression matches the text // read by the RuneReader. More complicated queries need to use Compile and // the full Regexp interface. func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) { re, err := Compile(pattern) if err != nil { return false, err } return re.MatchReader(r), nil } // MatchString checks whether a textual regular expression // matches a string. More complicated queries need // to use Compile and the full Regexp interface. func MatchString(pattern string, s string) (matched bool, err error) { re, err := Compile(pattern) if err != nil { return false, err } return re.MatchString(s), nil } // Match checks whether a textual regular expression // matches a byte slice. More complicated queries need // to use Compile and the full Regexp interface. func Match(pattern string, b []byte) (matched bool, err error) { re, err := Compile(pattern) if err != nil { return false, err } return re.Match(b), nil } // ReplaceAllString returns a copy of src, replacing matches of the Regexp // with the replacement string repl. Inside repl, $ signs are interpreted as // in Expand, so for instance $1 represents the text of the first submatch. func (re *Regexp) ReplaceAllString(src, repl string) string { n := 2 if strings.Index(repl, "$") >= 0 { n = 2 * (re.numSubexp + 1) } b := re.replaceAll(nil, src, n, func(dst []byte, match []int) []byte { return re.expand(dst, repl, nil, src, match) }) return string(b) } // ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp // with the replacement string repl. The replacement repl is substituted directly, // without using Expand. func (re *Regexp) ReplaceAllLiteralString(src, repl string) string { return string(re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte { return append(dst, repl...) })) } // ReplaceAllStringFunc returns a copy of src in which all matches of the // Regexp have been replaced by the return value of function repl applied // to the matched substring. The replacement returned by repl is substituted // directly, without using Expand. func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string { b := re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte { return append(dst, repl(src[match[0]:match[1]])...) }) return string(b) } func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst []byte, m []int) []byte) []byte { lastMatchEnd := 0 // end position of the most recent match searchPos := 0 // position where we next look for a match var buf []byte var endPos int if bsrc != nil { endPos = len(bsrc) } else { endPos = len(src) } if nmatch > re.prog.NumCap { nmatch = re.prog.NumCap } for searchPos <= endPos { a := re.doExecute(nil, bsrc, src, searchPos, nmatch) if len(a) == 0 { break // no more matches } // Copy the unmatched characters before this match. if bsrc != nil { buf = append(buf, bsrc[lastMatchEnd:a[0]]...) } else { buf = append(buf, src[lastMatchEnd:a[0]]...) } // Now insert a copy of the replacement string, but not for a // match of the empty string immediately after another match. // (Otherwise, we get double replacement for patterns that // match both empty and nonempty strings.) if a[1] > lastMatchEnd || a[0] == 0 { buf = repl(buf, a) } lastMatchEnd = a[1] // Advance past this match; always advance at least one character. var width int if bsrc != nil { _, width = utf8.DecodeRune(bsrc[searchPos:]) } else { _, width = utf8.DecodeRuneInString(src[searchPos:]) } if searchPos+width > a[1] { searchPos += width } else if searchPos+1 > a[1] { // This clause is only needed at the end of the input // string. In that case, DecodeRuneInString returns width=0. searchPos++ } else { searchPos = a[1] } } // Copy the unmatched characters after the last match. if bsrc != nil { buf = append(buf, bsrc[lastMatchEnd:]...) } else { buf = append(buf, src[lastMatchEnd:]...) } return buf } // ReplaceAll returns a copy of src, replacing matches of the Regexp // with the replacement text repl. Inside repl, $ signs are interpreted as // in Expand, so for instance $1 represents the text of the first submatch. func (re *Regexp) ReplaceAll(src, repl []byte) []byte { n := 2 if bytes.IndexByte(repl, '$') >= 0 { n = 2 * (re.numSubexp + 1) } srepl := "" b := re.replaceAll(src, "", n, func(dst []byte, match []int) []byte { if len(srepl) != len(repl) { srepl = string(repl) } return re.expand(dst, srepl, src, "", match) }) return b } // ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp // with the replacement bytes repl. The replacement repl is substituted directly, // without using Expand. func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte { return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte { return append(dst, repl...) }) } // ReplaceAllFunc returns a copy of src in which all matches of the // Regexp have been replaced by the return value of function repl applied // to the matched byte slice. The replacement returned by repl is substituted // directly, without using Expand. func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte { return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte { return append(dst, repl(src[match[0]:match[1]])...) }) } var specialBytes = []byte(`\.+*?()|[]{}^$`) func special(b byte) bool { return bytes.IndexByte(specialBytes, b) >= 0 } // QuoteMeta returns a string that quotes all regular expression metacharacters // inside the argument text; the returned string is a regular expression matching // the literal text. For example, QuoteMeta(`[foo]`) returns `\[foo\]`. func QuoteMeta(s string) string { b := make([]byte, 2*len(s)) // A byte loop is correct because all metacharacters are ASCII. j := 0 for i := 0; i < len(s); i++ { if special(s[i]) { b[j] = '\\' j++ } b[j] = s[i] j++ } return string(b[0:j]) } // The number of capture values in the program may correspond // to fewer capturing expressions than are in the regexp. // For example, "(a){0}" turns into an empty program, so the // maximum capture in the program is 0 but we need to return // an expression for \1. Pad appends -1s to the slice a as needed. func (re *Regexp) pad(a []int) []int { if a == nil { // No match. return nil } n := (1 + re.numSubexp) * 2 for len(a) < n { a = append(a, -1) } return a } // Find matches in slice b if b is non-nil, otherwise find matches in string s. func (re *Regexp) allMatches(s string, b []byte, n int, deliver func([]int)) { var end int if b == nil { end = len(s) } else { end = len(b) } for pos, i, prevMatchEnd := 0, 0, -1; i < n && pos <= end; { matches := re.doExecute(nil, b, s, pos, re.prog.NumCap) if len(matches) == 0 { break } accept := true if matches[1] == pos { // We've found an empty match. if matches[0] == prevMatchEnd { // We don't allow an empty match right // after a previous match, so ignore it. accept = false } var width int // TODO: use step() if b == nil { _, width = utf8.DecodeRuneInString(s[pos:end]) } else { _, width = utf8.DecodeRune(b[pos:end]) } if width > 0 { pos += width } else { pos = end + 1 } } else { pos = matches[1] } prevMatchEnd = matches[1] if accept { deliver(re.pad(matches)) i++ } } } // Find returns a slice holding the text of the leftmost match in b of the regular expression. // A return value of nil indicates no match. func (re *Regexp) Find(b []byte) []byte { a := re.doExecute(nil, b, "", 0, 2) if a == nil { return nil } return b[a[0]:a[1]] } // FindIndex returns a two-element slice of integers defining the location of // the leftmost match in b of the regular expression. The match itself is at // b[loc[0]:loc[1]]. // A return value of nil indicates no match. func (re *Regexp) FindIndex(b []byte) (loc []int) { a := re.doExecute(nil, b, "", 0, 2) if a == nil { return nil } return a[0:2] } // FindString returns a string holding the text of the leftmost match in s of the regular // expression. If there is no match, the return value is an empty string, // but it will also be empty if the regular expression successfully matches // an empty string. Use FindStringIndex or FindStringSubmatch if it is // necessary to distinguish these cases. func (re *Regexp) FindString(s string) string { a := re.doExecute(nil, nil, s, 0, 2) if a == nil { return "" } return s[a[0]:a[1]] } // FindStringIndex returns a two-element slice of integers defining the // location of the leftmost match in s of the regular expression. The match // itself is at s[loc[0]:loc[1]]. // A return value of nil indicates no match. func (re *Regexp) FindStringIndex(s string) (loc []int) { a := re.doExecute(nil, nil, s, 0, 2) if a == nil { return nil } return a[0:2] } // FindReaderIndex returns a two-element slice of integers defining the // location of the leftmost match of the regular expression in text read from // the RuneReader. The match text was found in the input stream at // byte offset loc[0] through loc[1]-1. // A return value of nil indicates no match. func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int) { a := re.doExecute(r, nil, "", 0, 2) if a == nil { return nil } return a[0:2] } // FindSubmatch returns a slice of slices holding the text of the leftmost // match of the regular expression in b and the matches, if any, of its // subexpressions, as defined by the 'Submatch' descriptions in the package // comment. // A return value of nil indicates no match. func (re *Regexp) FindSubmatch(b []byte) [][]byte { a := re.doExecute(nil, b, "", 0, re.prog.NumCap) if a == nil { return nil } ret := make([][]byte, 1+re.numSubexp) for i := range ret { if 2*i < len(a) && a[2*i] >= 0 { ret[i] = b[a[2*i]:a[2*i+1]] } } return ret } // Expand appends template to dst and returns the result; during the // append, Expand replaces variables in the template with corresponding // matches drawn from src. The match slice should have been returned by // FindSubmatchIndex. // // In the template, a variable is denoted by a substring of the form // $name or ${name}, where name is a non-empty sequence of letters, // digits, and underscores. A purely numeric name like $1 refers to // the submatch with the corresponding index; other names refer to // capturing parentheses named with the (?P...) syntax. A // reference to an out of range or unmatched index or a name that is not // present in the regular expression is replaced with an empty slice. // // In the $name form, name is taken to be as long as possible: $1x is // equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0. // // To insert a literal $ in the output, use $$ in the template. func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte { return re.expand(dst, string(template), src, "", match) } // ExpandString is like Expand but the template and source are strings. // It appends to and returns a byte slice in order to give the calling // code control over allocation. func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte { return re.expand(dst, template, nil, src, match) } func (re *Regexp) expand(dst []byte, template string, bsrc []byte, src string, match []int) []byte { for len(template) > 0 { i := strings.Index(template, "$") if i < 0 { break } dst = append(dst, template[:i]...) template = template[i:] if len(template) > 1 && template[1] == '$' { // Treat $$ as $. dst = append(dst, '$') template = template[2:] continue } name, num, rest, ok := extract(template) if !ok { // Malformed; treat $ as raw text. dst = append(dst, '$') template = template[1:] continue } template = rest if num >= 0 { if 2*num+1 < len(match) && match[2*num] >= 0 { if bsrc != nil { dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...) } else { dst = append(dst, src[match[2*num]:match[2*num+1]]...) } } } else { for i, namei := range re.subexpNames { if name == namei && 2*i+1 < len(match) && match[2*i] >= 0 { if bsrc != nil { dst = append(dst, bsrc[match[2*i]:match[2*i+1]]...) } else { dst = append(dst, src[match[2*i]:match[2*i+1]]...) } break } } } } dst = append(dst, template...) return dst } // extract returns the name from a leading "$name" or "${name}" in str. // If it is a number, extract returns num set to that number; otherwise num = -1. func extract(str string) (name string, num int, rest string, ok bool) { if len(str) < 2 || str[0] != '$' { return } brace := false if str[1] == '{' { brace = true str = str[2:] } else { str = str[1:] } i := 0 for i < len(str) { rune, size := utf8.DecodeRuneInString(str[i:]) if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) && rune != '_' { break } i += size } if i == 0 { // empty name is not okay return } name = str[:i] if brace { if i >= len(str) || str[i] != '}' { // missing closing brace return } i++ } // Parse number. num = 0 for i := 0; i < len(name); i++ { if name[i] < '0' || '9' < name[i] || num >= 1e8 { num = -1 break } num = num*10 + int(name[i]) - '0' } // Disallow leading zeros. if name[0] == '0' && len(name) > 1 { num = -1 } rest = str[i:] ok = true return } // FindSubmatchIndex returns a slice holding the index pairs identifying the // leftmost match of the regular expression in b and the matches, if any, of // its subexpressions, as defined by the 'Submatch' and 'Index' descriptions // in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindSubmatchIndex(b []byte) []int { return re.pad(re.doExecute(nil, b, "", 0, re.prog.NumCap)) } // FindStringSubmatch returns a slice of strings holding the text of the // leftmost match of the regular expression in s and the matches, if any, of // its subexpressions, as defined by the 'Submatch' description in the // package comment. // A return value of nil indicates no match. func (re *Regexp) FindStringSubmatch(s string) []string { a := re.doExecute(nil, nil, s, 0, re.prog.NumCap) if a == nil { return nil } ret := make([]string, 1+re.numSubexp) for i := range ret { if 2*i < len(a) && a[2*i] >= 0 { ret[i] = s[a[2*i]:a[2*i+1]] } } return ret } // FindStringSubmatchIndex returns a slice holding the index pairs // identifying the leftmost match of the regular expression in s and the // matches, if any, of its subexpressions, as defined by the 'Submatch' and // 'Index' descriptions in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindStringSubmatchIndex(s string) []int { return re.pad(re.doExecute(nil, nil, s, 0, re.prog.NumCap)) } // FindReaderSubmatchIndex returns a slice holding the index pairs // identifying the leftmost match of the regular expression of text read by // the RuneReader, and the matches, if any, of its subexpressions, as defined // by the 'Submatch' and 'Index' descriptions in the package comment. A // return value of nil indicates no match. func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int { return re.pad(re.doExecute(r, nil, "", 0, re.prog.NumCap)) } const startSize = 10 // The size at which to start a slice in the 'All' routines. // FindAll is the 'All' version of Find; it returns a slice of all successive // matches of the expression, as defined by the 'All' description in the // package comment. // A return value of nil indicates no match. func (re *Regexp) FindAll(b []byte, n int) [][]byte { if n < 0 { n = len(b) + 1 } result := make([][]byte, 0, startSize) re.allMatches("", b, n, func(match []int) { result = append(result, b[match[0]:match[1]]) }) if len(result) == 0 { return nil } return result } // FindAllIndex is the 'All' version of FindIndex; it returns a slice of all // successive matches of the expression, as defined by the 'All' description // in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllIndex(b []byte, n int) [][]int { if n < 0 { n = len(b) + 1 } result := make([][]int, 0, startSize) re.allMatches("", b, n, func(match []int) { result = append(result, match[0:2]) }) if len(result) == 0 { return nil } return result } // FindAllString is the 'All' version of FindString; it returns a slice of all // successive matches of the expression, as defined by the 'All' description // in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllString(s string, n int) []string { if n < 0 { n = len(s) + 1 } result := make([]string, 0, startSize) re.allMatches(s, nil, n, func(match []int) { result = append(result, s[match[0]:match[1]]) }) if len(result) == 0 { return nil } return result } // FindAllStringIndex is the 'All' version of FindStringIndex; it returns a // slice of all successive matches of the expression, as defined by the 'All' // description in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllStringIndex(s string, n int) [][]int { if n < 0 { n = len(s) + 1 } result := make([][]int, 0, startSize) re.allMatches(s, nil, n, func(match []int) { result = append(result, match[0:2]) }) if len(result) == 0 { return nil } return result } // FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice // of all successive matches of the expression, as defined by the 'All' // description in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte { if n < 0 { n = len(b) + 1 } result := make([][][]byte, 0, startSize) re.allMatches("", b, n, func(match []int) { slice := make([][]byte, len(match)/2) for j := range slice { if match[2*j] >= 0 { slice[j] = b[match[2*j]:match[2*j+1]] } } result = append(result, slice) }) if len(result) == 0 { return nil } return result } // FindAllSubmatchIndex is the 'All' version of FindSubmatchIndex; it returns // a slice of all successive matches of the expression, as defined by the // 'All' description in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int { if n < 0 { n = len(b) + 1 } result := make([][]int, 0, startSize) re.allMatches("", b, n, func(match []int) { result = append(result, match) }) if len(result) == 0 { return nil } return result } // FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it // returns a slice of all successive matches of the expression, as defined by // the 'All' description in the package comment. // A return value of nil indicates no match. func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string { if n < 0 { n = len(s) + 1 } result := make([][]string, 0, startSize) re.allMatches(s, nil, n, func(match []int) { slice := make([]string, len(match)/2) for j := range slice { if match[2*j] >= 0 { slice[j] = s[match[2*j]:match[2*j+1]] } } result = append(result, slice) }) if len(result) == 0 { return nil } return result } // FindAllStringSubmatchIndex is the 'All' version of // FindStringSubmatchIndex; it returns a slice of all successive matches of // the expression, as defined by the 'All' description in the package // comment. // A return value of nil indicates no match. func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int { if n < 0 { n = len(s) + 1 } result := make([][]int, 0, startSize) re.allMatches(s, nil, n, func(match []int) { result = append(result, match) }) if len(result) == 0 { return nil } return result } // Split slices s into substrings separated by the expression and returns a slice of // the substrings between those expression matches. // // The slice returned by this method consists of all the substrings of s // not contained in the slice returned by FindAllString. When called on an expression // that contains no metacharacters, it is equivalent to strings.SplitN. // // Example: // s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5) // // s: ["", "b", "b", "c", "cadaaae"] // // The count determines the number of substrings to return: // n > 0: at most n substrings; the last substring will be the unsplit remainder. // n == 0: the result is nil (zero substrings) // n < 0: all substrings func (re *Regexp) Split(s string, n int) []string { if n == 0 { return nil } if len(re.expr) > 0 && len(s) == 0 { return []string{""} } matches := re.FindAllStringIndex(s, n) strings := make([]string, 0, len(matches)) beg := 0 end := 0 for _, match := range matches { if n > 0 && len(strings) >= n-1 { break } end = match[0] if match[1] != 0 { strings = append(strings, s[beg:end]) } beg = match[1] } if end != len(s) { strings = append(strings, s[beg:]) } return strings } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/sync/mutex.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package sync provides basic synchronization primitives such as mutual // exclusion locks. Other than the Once and WaitGroup types, most are intended // for use by low-level library routines. Higher-level synchronization is // better done via channels and communication. // // Values containing the types defined in this package should not be copied. package sync // A Mutex is a mutual exclusion lock. // Mutexes can be created as part of other structures; // the zero value for a Mutex is an unlocked mutex. // // A Mutex must not be copied after first use. type Mutex struct { state int32 sema uint32 } // A Locker represents an object that can be locked and unlocked. type Locker interface { Lock() Unlock() } func (m *Mutex) Lock() {} func (m *Mutex) Unlock() {} ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/sync/rwmutex.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sync // An RWMutex is a reader/writer mutual exclusion lock. // The lock can be held by an arbitrary number of readers or a single writer. // RWMutexes can be created as part of other structures; // the zero value for a RWMutex is an unlocked mutex. // // An RWMutex must not be copied after first use. // // If a goroutine holds a RWMutex for reading, it must not expect this or any // other goroutine to be able to also take the read lock until the first read // lock is released. In particular, this prohibits recursive read locking. // This is to ensure that the lock eventually becomes available; // a blocked Lock call excludes new readers from acquiring the lock. type RWMutex struct { w Mutex // held if there are pending writers writerSem uint32 // semaphore for writers to wait for completing readers readerSem uint32 // semaphore for readers to wait for completing writers readerCount int32 // number of pending readers readerWait int32 // number of departing readers } // RLock locks rw for reading. func (rw *RWMutex) RLock() {} // RUnlock undoes a single RLock call; // it does not affect other simultaneous readers. // It is a run-time error if rw is not locked for reading // on entry to RUnlock. func (rw *RWMutex) RUnlock() {} // Lock locks rw for writing. // If the lock is already locked for reading or writing, // Lock blocks until the lock is available. func (rw *RWMutex) Lock() {} // Unlock unlocks rw for writing. It is a run-time error if rw is // not locked for writing on entry to Unlock. // // As with Mutexes, a locked RWMutex is not associated with a particular // goroutine. One goroutine may RLock (Lock) an RWMutex and then // arrange for another goroutine to RUnlock (Unlock) it. func (rw *RWMutex) Unlock() {} // RLocker returns a Locker interface that implements // the Lock and Unlock methods by calling rw.RLock and rw.RUnlock. func (rw *RWMutex) RLocker() Locker { return (*rlocker)(rw) } type rlocker RWMutex func (r *rlocker) Lock() { (*RWMutex)(r).RLock() } func (r *rlocker) Unlock() { (*RWMutex)(r).RUnlock() } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/testing/testing.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package testing provides support for automated testing of Go packages. // It is intended to be used in concert with the ``go test'' command, which automates // execution of any function of the form // func TestXxx(*testing.T) // where Xxx can be any alphanumeric string (but the first letter must not be in // [a-z]) and serves to identify the test routine. // // Within these functions, use the Error, Fail or related methods to signal failure. // // To write a new test suite, create a file whose name ends _test.go that // contains the TestXxx functions as described here. Put the file in the same // package as the one being tested. The file will be excluded from regular // package builds but will be included when the ``go test'' command is run. // For more detail, run ``go help test'' and ``go help testflag''. // // Tests and benchmarks may be skipped if not applicable with a call to // the Skip method of *T and *B: // func TestTimeConsuming(t *testing.T) { // if testing.Short() { // t.Skip("skipping test in short mode.") // } // ... // } // // Benchmarks // // Functions of the form // func BenchmarkXxx(*testing.B) // are considered benchmarks, and are executed by the "go test" command when // its -bench flag is provided. Benchmarks are run sequentially. // // For a description of the testing flags, see // http://golang.org/cmd/go/#hdr-Description_of_testing_flags. // // A sample benchmark function looks like this: // func BenchmarkHello(b *testing.B) { // for i := 0; i < b.N; i++ { // fmt.Sprintf("hello") // } // } // // The benchmark function must run the target code b.N times. // During benchark execution, b.N is adjusted until the benchmark function lasts // long enough to be timed reliably. The output // BenchmarkHello 10000000 282 ns/op // means that the loop ran 10000000 times at a speed of 282 ns per loop. // // If a benchmark needs some expensive setup before running, the timer // may be reset: // // func BenchmarkBigLen(b *testing.B) { // big := NewBig() // b.ResetTimer() // for i := 0; i < b.N; i++ { // big.Len() // } // } // // If a benchmark needs to test performance in a parallel setting, it may use // the RunParallel helper function; such benchmarks are intended to be used with // the go test -cpu flag: // // func BenchmarkTemplateParallel(b *testing.B) { // templ := template.Must(template.New("test").Parse("Hello, {{.}}!")) // b.RunParallel(func(pb *testing.PB) { // var buf bytes.Buffer // for pb.Next() { // buf.Reset() // templ.Execute(&buf, "World") // } // }) // } // // Examples // // The package also runs and verifies example code. Example functions may // include a concluding line comment that begins with "Output:" and is compared with // the standard output of the function when the tests are run. (The comparison // ignores leading and trailing space.) These are examples of an example: // // func ExampleHello() { // fmt.Println("hello") // // Output: hello // } // // func ExampleSalutations() { // fmt.Println("hello, and") // fmt.Println("goodbye") // // Output: // // hello, and // // goodbye // } // // Example functions without output comments are compiled but not executed. // // The naming convention to declare examples for the package, a function F, a type T and // method M on type T are: // // func Example() { ... } // func ExampleF() { ... } // func ExampleT() { ... } // func ExampleT_M() { ... } // // Multiple example functions for a package/type/function/method may be provided by // appending a distinct suffix to the name. The suffix must start with a // lower-case letter. // // func Example_suffix() { ... } // func ExampleF_suffix() { ... } // func ExampleT_suffix() { ... } // func ExampleT_M_suffix() { ... } // // The entire test file is presented as the example when it contains a single // example function, at least one other function, type, variable, or constant // declaration, and no test or benchmark functions. // // Main // // It is sometimes necessary for a test program to do extra setup or teardown // before or after testing. It is also sometimes necessary for a test to control // which code runs on the main thread. To support these and other cases, // if a test file contains a function: // // func TestMain(m *testing.M) // // then the generated test will call TestMain(m) instead of running the tests // directly. TestMain runs in the main goroutine and can do whatever setup // and teardown is necessary around a call to m.Run. It should then call // os.Exit with the result of m.Run. // // The minimal implementation of TestMain is: // // func TestMain(m *testing.M) { os.Exit(m.Run()) } // // In effect, that is the implementation used when no TestMain is explicitly defined. package testing import ( "bytes" "flag" "fmt" "os" "runtime" "runtime/pprof" "strconv" "strings" "sync" "time" ) var ( // The short flag requests that tests run more quickly, but its functionality // is provided by test writers themselves. The testing package is just its // home. The all.bash installation script sets it to make installation more // efficient, but by default the flag is off so a plain "go test" will do a // full test of the package. short = flag.Bool("test.short", false, "run smaller test suite to save time") // The directory in which to create profile files and the like. When run from // "go test", the binary always runs in the source directory for the package; // this flag lets "go test" tell the binary to write the files in the directory where // the "go test" command is run. outputDir = flag.String("test.outputdir", "", "directory in which to write profiles") // Report as tests are run; default is silent for success. chatty = flag.Bool("test.v", false, "verbose: print additional output") coverProfile = flag.String("test.coverprofile", "", "write a coverage profile to the named file after execution") match = flag.String("test.run", "", "regular expression to select tests and examples to run") memProfile = flag.String("test.memprofile", "", "write a memory profile to the named file after execution") memProfileRate = flag.Int("test.memprofilerate", 0, "if >=0, sets runtime.MemProfileRate") cpuProfile = flag.String("test.cpuprofile", "", "write a cpu profile to the named file during execution") blockProfile = flag.String("test.blockprofile", "", "write a goroutine blocking profile to the named file after execution") blockProfileRate = flag.Int("test.blockprofilerate", 1, "if >= 0, calls runtime.SetBlockProfileRate()") timeout = flag.Duration("test.timeout", 0, "if positive, sets an aggregate time limit for all tests") cpuListStr = flag.String("test.cpu", "", "comma-separated list of number of CPUs to use for each test") parallel = flag.Int("test.parallel", runtime.GOMAXPROCS(0), "maximum test parallelism") haveExamples bool // are there examples? cpuList []int ) // common holds the elements common between T and B and // captures common methods such as Errorf. type common struct { mu sync.RWMutex // guards output and failed output []byte // Output generated by test or benchmark. failed bool // Test or benchmark has failed. skipped bool // Test of benchmark has been skipped. finished bool start time.Time // Time test or benchmark started duration time.Duration self interface{} // To be sent on signal channel when done. signal chan interface{} // Output for serial tests. } // Short reports whether the -test.short flag is set. func Short() bool { return *short } // Verbose reports whether the -test.v flag is set. func Verbose() bool { return *chatty } // decorate prefixes the string with the file and line of the call site // and inserts the final newline if needed and indentation tabs for formatting. func decorate(s string) string { _, file, line, ok := runtime.Caller(3) // decorate + log + public function. if ok { // Truncate file name at last file name separator. if index := strings.LastIndex(file, "/"); index >= 0 { file = file[index+1:] } else if index = strings.LastIndex(file, "\\"); index >= 0 { file = file[index+1:] } } else { file = "???" line = 1 } buf := new(bytes.Buffer) // Every line is indented at least one tab. buf.WriteByte('\t') fmt.Fprintf(buf, "%s:%d: ", file, line) lines := strings.Split(s, "\n") if l := len(lines); l > 1 && lines[l-1] == "" { lines = lines[:l-1] } for i, line := range lines { if i > 0 { // Second and subsequent lines are indented an extra tab. buf.WriteString("\n\t\t") } buf.WriteString(line) } buf.WriteByte('\n') return buf.String() } // fmtDuration returns a string representing d in the form "87.00s". func fmtDuration(d time.Duration) string { return fmt.Sprintf("%.2fs", d.Seconds()) } // TB is the interface common to T and B. type TB interface { Error(args ...interface{}) Errorf(format string, args ...interface{}) Fail() FailNow() Failed() bool Fatal(args ...interface{}) Fatalf(format string, args ...interface{}) Log(args ...interface{}) Logf(format string, args ...interface{}) Skip(args ...interface{}) SkipNow() Skipf(format string, args ...interface{}) Skipped() bool // A private method to prevent users implementing the // interface and so future additions to it will not // violate Go 1 compatibility. private() } var _ TB = (*T)(nil) var _ TB = (*B)(nil) // T is a type passed to Test functions to manage test state and support formatted test logs. // Logs are accumulated during execution and dumped to standard error when done. type T struct { common name string // Name of test. startParallel chan bool // Parallel tests will wait on this. } func (c *common) private() {} // Fail marks the function as having failed but continues execution. func (c *common) Fail() { c.mu.Lock() defer c.mu.Unlock() c.failed = true } // Failed reports whether the function has failed. func (c *common) Failed() bool { c.mu.RLock() defer c.mu.RUnlock() return c.failed } // FailNow marks the function as having failed and stops its execution. // Execution will continue at the next test or benchmark. // FailNow must be called from the goroutine running the // test or benchmark function, not from other goroutines // created during the test. Calling FailNow does not stop // those other goroutines. func (c *common) FailNow() { c.Fail() // Calling runtime.Goexit will exit the goroutine, which // will run the deferred functions in this goroutine, // which will eventually run the deferred lines in tRunner, // which will signal to the test loop that this test is done. // // A previous version of this code said: // // c.duration = ... // c.signal <- c.self // runtime.Goexit() // // This previous version duplicated code (those lines are in // tRunner no matter what), but worse the goroutine teardown // implicit in runtime.Goexit was not guaranteed to complete // before the test exited. If a test deferred an important cleanup // function (like removing temporary files), there was no guarantee // it would run on a test failure. Because we send on c.signal during // a top-of-stack deferred function now, we know that the send // only happens after any other stacked defers have completed. c.finished = true runtime.Goexit() } // log generates the output. It's always at the same stack depth. func (c *common) log(s string) { c.mu.Lock() defer c.mu.Unlock() c.output = append(c.output, decorate(s)...) } // Log formats its arguments using default formatting, analogous to Println, // and records the text in the error log. The text will be printed only if // the test fails or the -test.v flag is set. func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) } // Logf formats its arguments according to the format, analogous to Printf, // and records the text in the error log. The text will be printed only if // the test fails or the -test.v flag is set. func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) } // Error is equivalent to Log followed by Fail. func (c *common) Error(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.Fail() } // Errorf is equivalent to Logf followed by Fail. func (c *common) Errorf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.Fail() } // Fatal is equivalent to Log followed by FailNow. func (c *common) Fatal(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.FailNow() } // Fatalf is equivalent to Logf followed by FailNow. func (c *common) Fatalf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.FailNow() } // Skip is equivalent to Log followed by SkipNow. func (c *common) Skip(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.SkipNow() } // Skipf is equivalent to Logf followed by SkipNow. func (c *common) Skipf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.SkipNow() } // SkipNow marks the test as having been skipped and stops its execution. // Execution will continue at the next test or benchmark. See also FailNow. // SkipNow must be called from the goroutine running the test, not from // other goroutines created during the test. Calling SkipNow does not stop // those other goroutines. func (c *common) SkipNow() { c.skip() c.finished = true runtime.Goexit() } func (c *common) skip() { c.mu.Lock() defer c.mu.Unlock() c.skipped = true } // Skipped reports whether the test was skipped. func (c *common) Skipped() bool { c.mu.RLock() defer c.mu.RUnlock() return c.skipped } // Parallel signals that this test is to be run in parallel with (and only with) // other parallel tests. func (t *T) Parallel() { t.signal <- (*T)(nil) // Release main testing loop <-t.startParallel // Wait for serial tests to finish // Assuming Parallel is the first thing a test does, which is reasonable, // reinitialize the test's start time because it's actually starting now. t.start = time.Now() } // An internal type but exported because it is cross-package; part of the implementation // of the "go test" command. type InternalTest struct { Name string F func(*T) } func tRunner(t *T, test *InternalTest) { // When this goroutine is done, either because test.F(t) // returned normally or because a test failure triggered // a call to runtime.Goexit, record the duration and send // a signal saying that the test is done. defer func() { t.duration = time.Now().Sub(t.start) // If the test panicked, print any test output before dying. err := recover() if !t.finished && err == nil { err = fmt.Errorf("test executed panic(nil) or runtime.Goexit") } if err != nil { t.Fail() t.report() panic(err) } t.signal <- t }() t.start = time.Now() test.F(t) t.finished = true } // An internal function but exported because it is cross-package; part of the implementation // of the "go test" command. func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { os.Exit(MainStart(matchString, tests, benchmarks, examples).Run()) } // M is a type passed to a TestMain function to run the actual tests. type M struct { matchString func(pat, str string) (bool, error) tests []InternalTest benchmarks []InternalBenchmark examples []InternalExample } // MainStart is meant for use by tests generated by 'go test'. // It is not meant to be called directly and is not subject to the Go 1 compatibility document. // It may change signature from release to release. func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M { return &M{ matchString: matchString, tests: tests, benchmarks: benchmarks, examples: examples, } } // Run runs the tests. It returns an exit code to pass to os.Exit. func (m *M) Run() int { flag.Parse() parseCpuList() before() startAlarm() haveExamples = len(m.examples) > 0 testOk := RunTests(m.matchString, m.tests) exampleOk := RunExamples(m.matchString, m.examples) stopAlarm() if !testOk || !exampleOk { fmt.Println("FAIL") after() return 1 } fmt.Println("PASS") RunBenchmarks(m.matchString, m.benchmarks) after() return 0 } func (t *T) report() { dstr := fmtDuration(t.duration) format := "--- %s: %s (%s)\n%s" if t.Failed() { fmt.Printf(format, "FAIL", t.name, dstr, t.output) } else if *chatty { if t.Skipped() { fmt.Printf(format, "SKIP", t.name, dstr, t.output) } else { fmt.Printf(format, "PASS", t.name, dstr, t.output) } } } func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) { ok = true if len(tests) == 0 && !haveExamples { fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") return } for _, procs := range cpuList { runtime.GOMAXPROCS(procs) // We build a new channel tree for each run of the loop. // collector merges in one channel all the upstream signals from parallel tests. // If all tests pump to the same channel, a bug can occur where a test // kicks off a goroutine that Fails, yet the test still delivers a completion signal, // which skews the counting. var collector = make(chan interface{}) numParallel := 0 startParallel := make(chan bool) for i := 0; i < len(tests); i++ { matched, err := matchString(*match, tests[i].Name) if err != nil { fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.run: %s\n", err) os.Exit(1) } if !matched { continue } testName := tests[i].Name if procs != 1 { testName = fmt.Sprintf("%s-%d", tests[i].Name, procs) } t := &T{ common: common{ signal: make(chan interface{}), }, name: testName, startParallel: startParallel, } t.self = t if *chatty { fmt.Printf("=== RUN %s\n", t.name) } go tRunner(t, &tests[i]) out := (<-t.signal).(*T) if out == nil { // Parallel run. go func() { collector <- <-t.signal }() numParallel++ continue } t.report() ok = ok && !out.Failed() } running := 0 for numParallel+running > 0 { if running < *parallel && numParallel > 0 { startParallel <- true running++ numParallel-- continue } t := (<-collector).(*T) t.report() ok = ok && !t.Failed() running-- } } return } // before runs before all testing. func before() { if *memProfileRate > 0 { runtime.MemProfileRate = *memProfileRate } if *cpuProfile != "" { f, err := os.Create(toOutputDir(*cpuProfile)) if err != nil { fmt.Fprintf(os.Stderr, "testing: %s", err) return } if err := pprof.StartCPUProfile(f); err != nil { fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s", err) f.Close() return } // Could save f so after can call f.Close; not worth the effort. } if *blockProfile != "" && *blockProfileRate >= 0 { runtime.SetBlockProfileRate(*blockProfileRate) } if *coverProfile != "" && cover.Mode == "" { fmt.Fprintf(os.Stderr, "testing: cannot use -test.coverprofile because test binary was not built with coverage enabled\n") os.Exit(2) } } // after runs after all testing. func after() { if *cpuProfile != "" { pprof.StopCPUProfile() // flushes profile to disk } if *memProfile != "" { f, err := os.Create(toOutputDir(*memProfile)) if err != nil { fmt.Fprintf(os.Stderr, "testing: %s\n", err) os.Exit(2) } runtime.GC() // materialize all statistics if err = pprof.WriteHeapProfile(f); err != nil { fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *memProfile, err) os.Exit(2) } f.Close() } if *blockProfile != "" && *blockProfileRate >= 0 { f, err := os.Create(toOutputDir(*blockProfile)) if err != nil { fmt.Fprintf(os.Stderr, "testing: %s\n", err) os.Exit(2) } if err = pprof.Lookup("block").WriteTo(f, 0); err != nil { fmt.Fprintf(os.Stderr, "testing: can't write %s: %s\n", *blockProfile, err) os.Exit(2) } f.Close() } if cover.Mode != "" { coverReport() } } // toOutputDir returns the file name relocated, if required, to outputDir. // Simple implementation to avoid pulling in path/filepath. func toOutputDir(path string) string { if *outputDir == "" || path == "" { return path } if runtime.GOOS == "windows" { // On Windows, it's clumsy, but we can be almost always correct // by just looking for a drive letter and a colon. // Absolute paths always have a drive letter (ignoring UNC). // Problem: if path == "C:A" and outputdir == "C:\Go" it's unclear // what to do, but even then path/filepath doesn't help. // TODO: Worth doing better? Probably not, because we're here only // under the management of go test. if len(path) >= 2 { letter, colon := path[0], path[1] if ('a' <= letter && letter <= 'z' || 'A' <= letter && letter <= 'Z') && colon == ':' { // If path starts with a drive letter we're stuck with it regardless. return path } } } if os.IsPathSeparator(path[0]) { return path } return fmt.Sprintf("%s%c%s", *outputDir, os.PathSeparator, path) } var timer *time.Timer // startAlarm starts an alarm if requested. func startAlarm() { if *timeout > 0 { timer = time.AfterFunc(*timeout, func() { panic(fmt.Sprintf("test timed out after %v", *timeout)) }) } } // stopAlarm turns off the alarm. func stopAlarm() { if *timeout > 0 { timer.Stop() } } func parseCpuList() { for _, val := range strings.Split(*cpuListStr, ",") { val = strings.TrimSpace(val) if val == "" { continue } cpu, err := strconv.Atoi(val) if err != nil || cpu <= 0 { fmt.Fprintf(os.Stderr, "testing: invalid value %q for -test.cpu\n", val) os.Exit(1) } cpuList = append(cpuList, cpu) } if cpuList == nil { cpuList = append(cpuList, runtime.GOMAXPROCS(-1)) } } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/text/template/helper.go ================================================ // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Helper functions to make constructing templates easier. package template import ( "fmt" "io/ioutil" "path/filepath" ) // Functions and methods to parse templates. // Must is a helper that wraps a call to a function returning (*Template, error) // and panics if the error is non-nil. It is intended for use in variable // initializations such as // var t = template.Must(template.New("name").Parse("text")) func Must(t *Template, err error) *Template { if err != nil { panic(err) } return t } // ParseFiles creates a new Template and parses the template definitions from // the named files. The returned template's name will have the (base) name and // (parsed) contents of the first file. There must be at least one file. // If an error occurs, parsing stops and the returned *Template is nil. func ParseFiles(filenames ...string) (*Template, error) { return parseFiles(nil, filenames...) } // ParseFiles parses the named files and associates the resulting templates with // t. If an error occurs, parsing stops and the returned template is nil; // otherwise it is t. There must be at least one file. func (t *Template) ParseFiles(filenames ...string) (*Template, error) { return parseFiles(t, filenames...) } // parseFiles is the helper for the method and function. If the argument // template is nil, it is created from the first file. func parseFiles(t *Template, filenames ...string) (*Template, error) { if len(filenames) == 0 { // Not really a problem, but be consistent. return nil, fmt.Errorf("template: no files named in call to ParseFiles") } for _, filename := range filenames { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err } s := string(b) name := filepath.Base(filename) // First template becomes return value if not already defined, // and we use that one for subsequent New calls to associate // all the templates together. Also, if this file has the same name // as t, this file becomes the contents of t, so // t, err := New(name).Funcs(xxx).ParseFiles(name) // works. Otherwise we create a new template associated with t. var tmpl *Template if t == nil { t = New(name) } if name == t.Name() { tmpl = t } else { tmpl = t.New(name) } _, err = tmpl.Parse(s) if err != nil { return nil, err } } return t, nil } // ParseGlob creates a new Template and parses the template definitions from the // files identified by the pattern, which must match at least one file. The // returned template will have the (base) name and (parsed) contents of the // first file matched by the pattern. ParseGlob is equivalent to calling // ParseFiles with the list of files matched by the pattern. func ParseGlob(pattern string) (*Template, error) { return parseGlob(nil, pattern) } // ParseGlob parses the template definitions in the files identified by the // pattern and associates the resulting templates with t. The pattern is // processed by filepath.Glob and must match at least one file. ParseGlob is // equivalent to calling t.ParseFiles with the list of files matched by the // pattern. func (t *Template) ParseGlob(pattern string) (*Template, error) { return parseGlob(t, pattern) } // parseGlob is the implementation of the function and method ParseGlob. func parseGlob(t *Template, pattern string) (*Template, error) { filenames, err := filepath.Glob(pattern) if err != nil { return nil, err } if len(filenames) == 0 { return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) } return parseFiles(t, filenames...) } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/text/template/template.go ================================================ // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package template import ( "fmt" "reflect" "text/template/parse" ) // common holds the information shared by related templates. type common struct { tmpl map[string]*Template // We use two maps, one for parsing and one for execution. // This separation makes the API cleaner since it doesn't // expose reflection to the client. parseFuncs FuncMap execFuncs map[string]reflect.Value } // Template is the representation of a parsed template. The *parse.Tree // field is exported only for use by html/template and should be treated // as unexported by all other clients. type Template struct { name string *parse.Tree *common leftDelim string rightDelim string } // New allocates a new template with the given name. func New(name string) *Template { return &Template{ name: name, } } // Name returns the name of the template. func (t *Template) Name() string { return t.name } // New allocates a new template associated with the given one and with the same // delimiters. The association, which is transitive, allows one template to // invoke another with a {{template}} action. func (t *Template) New(name string) *Template { t.init() return &Template{ name: name, common: t.common, leftDelim: t.leftDelim, rightDelim: t.rightDelim, } } func (t *Template) init() { if t.common == nil { t.common = new(common) t.tmpl = make(map[string]*Template) t.parseFuncs = make(FuncMap) t.execFuncs = make(map[string]reflect.Value) } } // Clone returns a duplicate of the template, including all associated // templates. The actual representation is not copied, but the name space of // associated templates is, so further calls to Parse in the copy will add // templates to the copy but not to the original. Clone can be used to prepare // common templates and use them with variant definitions for other templates // by adding the variants after the clone is made. func (t *Template) Clone() (*Template, error) { nt := t.copy(nil) nt.init() nt.tmpl[t.name] = nt for k, v := range t.tmpl { if k == t.name { // Already installed. continue } // The associated templates share nt's common structure. tmpl := v.copy(nt.common) nt.tmpl[k] = tmpl } for k, v := range t.parseFuncs { nt.parseFuncs[k] = v } for k, v := range t.execFuncs { nt.execFuncs[k] = v } return nt, nil } // copy returns a shallow copy of t, with common set to the argument. func (t *Template) copy(c *common) *Template { nt := New(t.name) nt.Tree = t.Tree nt.common = c nt.leftDelim = t.leftDelim nt.rightDelim = t.rightDelim return nt } // AddParseTree creates a new template with the name and parse tree // and associates it with t. func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) { if t.common != nil && t.tmpl[name] != nil { return nil, fmt.Errorf("template: redefinition of template %q", name) } nt := t.New(name) nt.Tree = tree t.tmpl[name] = nt return nt, nil } // Templates returns a slice of the templates associated with t, including t // itself. func (t *Template) Templates() []*Template { if t.common == nil { return nil } // Return a slice so we don't expose the map. m := make([]*Template, 0, len(t.tmpl)) for _, v := range t.tmpl { m = append(m, v) } return m } // Delims sets the action delimiters to the specified strings, to be used in // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template // definitions will inherit the settings. An empty delimiter stands for the // corresponding default: {{ or }}. // The return value is the template, so calls can be chained. func (t *Template) Delims(left, right string) *Template { t.leftDelim = left t.rightDelim = right return t } // Funcs adds the elements of the argument map to the template's function map. // It panics if a value in the map is not a function with appropriate return // type. However, it is legal to overwrite elements of the map. The return // value is the template, so calls can be chained. func (t *Template) Funcs(funcMap FuncMap) *Template { t.init() addValueFuncs(t.execFuncs, funcMap) addFuncs(t.parseFuncs, funcMap) return t } // Lookup returns the template with the given name that is associated with t, // or nil if there is no such template. func (t *Template) Lookup(name string) *Template { if t.common == nil { return nil } return t.tmpl[name] } // Parse parses a string into a template. Nested template definitions will be // associated with the top-level template t. Parse may be called multiple times // to parse definitions of templates to associate with t. It is an error if a // resulting template is non-empty (contains content other than template // definitions) and would replace a non-empty template with the same name. // (In multiple calls to Parse with the same receiver template, only one call // can contain text other than space, comments, and template definitions.) func (t *Template) Parse(text string) (*Template, error) { t.init() trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins) if err != nil { return nil, err } // Add the newly parsed trees, including the one for t, into our common structure. for name, tree := range trees { // If the name we parsed is the name of this template, overwrite this template. // The associate method checks it's not a redefinition. tmpl := t if name != t.name { tmpl = t.New(name) } // Even if t == tmpl, we need to install it in the common.tmpl map. if replace, err := t.associate(tmpl, tree); err != nil { return nil, err } else if replace { tmpl.Tree = tree } tmpl.leftDelim = t.leftDelim tmpl.rightDelim = t.rightDelim } return t, nil } // associate installs the new template into the group of templates associated // with t. It is an error to reuse a name except to overwrite an empty // template. The two are already known to share the common structure. // The boolean return value reports wither to store this tree as t.Tree. func (t *Template) associate(new *Template, tree *parse.Tree) (bool, error) { if new.common != t.common { panic("internal error: associate not common") } name := new.name if old := t.tmpl[name]; old != nil { oldIsEmpty := parse.IsEmptyTree(old.Root) newIsEmpty := parse.IsEmptyTree(tree.Root) if newIsEmpty { // Whether old is empty or not, new is empty; no reason to replace old. return false, nil } if !oldIsEmpty { return false, fmt.Errorf("template: redefinition of template %q", name) } } t.tmpl[name] = new return true, nil } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/time/tick.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package time import "errors" // A Ticker holds a channel that delivers `ticks' of a clock // at intervals. type Ticker struct { C <-chan Time // The channel on which the ticks are delivered. r runtimeTimer } // NewTicker returns a new Ticker containing a channel that will send the // time with a period specified by the duration argument. // It adjusts the intervals or drops ticks to make up for slow receivers. // The duration d must be greater than zero; if not, NewTicker will panic. // Stop the ticker to release associated resources. func NewTicker(d Duration) *Ticker { if d <= 0 { panic(errors.New("non-positive interval for NewTicker")) } // Give the channel a 1-element time buffer. // If the client falls behind while reading, we drop ticks // on the floor until the client catches up. c := make(chan Time, 1) t := &Ticker{ C: c, r: runtimeTimer{ when: when(d), period: int64(d), f: sendTime, arg: c, }, } startTimer(&t.r) return t } // Stop turns off a ticker. After Stop, no more ticks will be sent. // Stop does not close the channel, to prevent a read from the channel succeeding // incorrectly. func (t *Ticker) Stop() { stopTimer(&t.r) } // Tick is a convenience wrapper for NewTicker providing access to the ticking // channel only. Useful for clients that have no need to shut down the ticker. func Tick(d Duration) <-chan Time { if d <= 0 { return nil } return NewTicker(d).C } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/time/time.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package time provides functionality for measuring and displaying time. // // The calendrical calculations always assume a Gregorian calendar. package time import "errors" // A Time represents an instant in time with nanosecond precision. // // Programs using times should typically store and pass them as values, // not pointers. That is, time variables and struct fields should be of // type time.Time, not *time.Time. A Time value can be used by // multiple goroutines simultaneously. // // Time instants can be compared using the Before, After, and Equal methods. // The Sub method subtracts two instants, producing a Duration. // The Add method adds a Time and a Duration, producing a Time. // // The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. // As this time is unlikely to come up in practice, the IsZero method gives // a simple way of detecting a time that has not been initialized explicitly. // // Each Time has associated with it a Location, consulted when computing the // presentation form of the time, such as in the Format, Hour, and Year methods. // The methods Local, UTC, and In return a Time with a specific location. // Changing the location in this way changes only the presentation; it does not // change the instant in time being denoted and therefore does not affect the // computations described in earlier paragraphs. // // Note that the Go == operator compares not just the time instant but also the // Location. Therefore, Time values should not be used as map or database keys // without first guaranteeing that the identical Location has been set for all // values, which can be achieved through use of the UTC or Local method. // type Time struct { // sec gives the number of seconds elapsed since // January 1, year 1 00:00:00 UTC. sec int64 // nsec specifies a non-negative nanosecond // offset within the second named by Seconds. // It must be in the range [0, 999999999]. nsec int32 // loc specifies the Location that should be used to // determine the minute, hour, month, day, and year // that correspond to this Time. // Only the zero Time has a nil Location. // In that case it is interpreted to mean UTC. loc *Location } // After reports whether the time instant t is after u. func (t Time) After(u Time) bool { return t.sec > u.sec || t.sec == u.sec && t.nsec > u.nsec } // Before reports whether the time instant t is before u. func (t Time) Before(u Time) bool { return t.sec < u.sec || t.sec == u.sec && t.nsec < u.nsec } // Equal reports whether t and u represent the same time instant. // Two times can be equal even if they are in different locations. // For example, 6:00 +0200 CEST and 4:00 UTC are Equal. // This comparison is different from using t == u, which also compares // the locations. func (t Time) Equal(u Time) bool { return t.sec == u.sec && t.nsec == u.nsec } // A Month specifies a month of the year (January = 1, ...). type Month int const ( January Month = 1 + iota February March April May June July August September October November December ) var months = [...]string{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", } // String returns the English name of the month ("January", "February", ...). func (m Month) String() string { return months[m-1] } // A Weekday specifies a day of the week (Sunday = 0, ...). type Weekday int const ( Sunday Weekday = iota Monday Tuesday Wednesday Thursday Friday Saturday ) var days = [...]string{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", } // String returns the English name of the day ("Sunday", "Monday", ...). func (d Weekday) String() string { return days[d] } // Computations on time. // // The zero value for a Time is defined to be // January 1, year 1, 00:00:00.000000000 UTC // which (1) looks like a zero, or as close as you can get in a date // (1-1-1 00:00:00 UTC), (2) is unlikely enough to arise in practice to // be a suitable "not set" sentinel, unlike Jan 1 1970, and (3) has a // non-negative year even in time zones west of UTC, unlike 1-1-0 // 00:00:00 UTC, which would be 12-31-(-1) 19:00:00 in New York. // // The zero Time value does not force a specific epoch for the time // representation. For example, to use the Unix epoch internally, we // could define that to distinguish a zero value from Jan 1 1970, that // time would be represented by sec=-1, nsec=1e9. However, it does // suggest a representation, namely using 1-1-1 00:00:00 UTC as the // epoch, and that's what we do. // // The Add and Sub computations are oblivious to the choice of epoch. // // The presentation computations - year, month, minute, and so on - all // rely heavily on division and modulus by positive constants. For // calendrical calculations we want these divisions to round down, even // for negative values, so that the remainder is always positive, but // Go's division (like most hardware division instructions) rounds to // zero. We can still do those computations and then adjust the result // for a negative numerator, but it's annoying to write the adjustment // over and over. Instead, we can change to a different epoch so long // ago that all the times we care about will be positive, and then round // to zero and round down coincide. These presentation routines already // have to add the zone offset, so adding the translation to the // alternate epoch is cheap. For example, having a non-negative time t // means that we can write // // sec = t % 60 // // instead of // // sec = t % 60 // if sec < 0 { // sec += 60 // } // // everywhere. // // The calendar runs on an exact 400 year cycle: a 400-year calendar // printed for 1970-2469 will apply as well to 2470-2869. Even the days // of the week match up. It simplifies the computations to choose the // cycle boundaries so that the exceptional years are always delayed as // long as possible. That means choosing a year equal to 1 mod 400, so // that the first leap year is the 4th year, the first missed leap year // is the 100th year, and the missed missed leap year is the 400th year. // So we'd prefer instead to print a calendar for 2001-2400 and reuse it // for 2401-2800. // // Finally, it's convenient if the delta between the Unix epoch and // long-ago epoch is representable by an int64 constant. // // These three considerations—choose an epoch as early as possible, that // uses a year equal to 1 mod 400, and that is no more than 2⁶³ seconds // earlier than 1970—bring us to the year -292277022399. We refer to // this year as the absolute zero year, and to times measured as a uint64 // seconds since this year as absolute times. // // Times measured as an int64 seconds since the year 1—the representation // used for Time's sec field—are called internal times. // // Times measured as an int64 seconds since the year 1970 are called Unix // times. // // It is tempting to just use the year 1 as the absolute epoch, defining // that the routines are only valid for years >= 1. However, the // routines would then be invalid when displaying the epoch in time zones // west of UTC, since it is year 0. It doesn't seem tenable to say that // printing the zero time correctly isn't supported in half the time // zones. By comparison, it's reasonable to mishandle some times in // the year -292277022399. // // All this is opaque to clients of the API and can be changed if a // better implementation presents itself. const ( // The unsigned zero year for internal calculations. // Must be 1 mod 400, and times before it will not compute correctly, // but otherwise can be changed at will. absoluteZeroYear = -292277022399 // The year of the zero Time. // Assumed by the unixToInternal computation below. internalYear = 1 // The year of the zero Unix time. unixYear = 1970 // Offsets to convert between internal and absolute or Unix times. absoluteToInternal int64 = (absoluteZeroYear - internalYear) * 365.2425 * secondsPerDay internalToAbsolute = -absoluteToInternal unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay internalToUnix int64 = -unixToInternal ) // IsZero reports whether t represents the zero time instant, // January 1, year 1, 00:00:00 UTC. func (t Time) IsZero() bool { return t.sec == 0 && t.nsec == 0 } // abs returns the time t as an absolute time, adjusted by the zone offset. // It is called when computing a presentation property like Month or Hour. func (t Time) abs() uint64 { l := t.loc // Avoid function calls when possible. if l == nil || l == &localLoc { l = l.get() } sec := t.sec + internalToUnix if l != &utcLoc { if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { sec += int64(l.cacheZone.offset) } else { _, offset, _, _, _ := l.lookup(sec) sec += int64(offset) } } return uint64(sec + (unixToInternal + internalToAbsolute)) } // locabs is a combination of the Zone and abs methods, // extracting both return values from a single zone lookup. func (t Time) locabs() (name string, offset int, abs uint64) { l := t.loc if l == nil || l == &localLoc { l = l.get() } // Avoid function call if we hit the local time cache. sec := t.sec + internalToUnix if l != &utcLoc { if l.cacheZone != nil && l.cacheStart <= sec && sec < l.cacheEnd { name = l.cacheZone.name offset = l.cacheZone.offset } else { name, offset, _, _, _ = l.lookup(sec) } sec += int64(offset) } else { name = "UTC" } abs = uint64(sec + (unixToInternal + internalToAbsolute)) return } // Date returns the year, month, and day in which t occurs. func (t Time) Date() (year int, month Month, day int) { year, month, day, _ = t.date(true) return } // Year returns the year in which t occurs. func (t Time) Year() int { year, _, _, _ := t.date(false) return year } // Month returns the month of the year specified by t. func (t Time) Month() Month { _, month, _, _ := t.date(true) return month } // Day returns the day of the month specified by t. func (t Time) Day() int { _, _, day, _ := t.date(true) return day } // Weekday returns the day of the week specified by t. func (t Time) Weekday() Weekday { return absWeekday(t.abs()) } // absWeekday is like Weekday but operates on an absolute time. func absWeekday(abs uint64) Weekday { // January 1 of the absolute year, like January 1 of 2001, was a Monday. sec := (abs + uint64(Monday)*secondsPerDay) % secondsPerWeek return Weekday(int(sec) / secondsPerDay) } // ISOWeek returns the ISO 8601 year and week number in which t occurs. // Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to // week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 // of year n+1. func (t Time) ISOWeek() (year, week int) { year, month, day, yday := t.date(true) wday := int(t.Weekday()+6) % 7 // weekday but Monday = 0. const ( Mon int = iota Tue Wed Thu Fri Sat Sun ) // Calculate week as number of Mondays in year up to // and including today, plus 1 because the first week is week 0. // Putting the + 1 inside the numerator as a + 7 keeps the // numerator from being negative, which would cause it to // round incorrectly. week = (yday - wday + 7) / 7 // The week number is now correct under the assumption // that the first Monday of the year is in week 1. // If Jan 1 is a Tuesday, Wednesday, or Thursday, the first Monday // is actually in week 2. jan1wday := (wday - yday + 7*53) % 7 if Tue <= jan1wday && jan1wday <= Thu { week++ } // If the week number is still 0, we're in early January but in // the last week of last year. if week == 0 { year-- week = 52 // A year has 53 weeks when Jan 1 or Dec 31 is a Thursday, // meaning Jan 1 of the next year is a Friday // or it was a leap year and Jan 1 of the next year is a Saturday. if jan1wday == Fri || (jan1wday == Sat && isLeap(year)) { week++ } } // December 29 to 31 are in week 1 of next year if // they are after the last Thursday of the year and // December 31 is a Monday, Tuesday, or Wednesday. if month == December && day >= 29 && wday < Thu { if dec31wday := (wday + 31 - day) % 7; Mon <= dec31wday && dec31wday <= Wed { year++ week = 1 } } return } // Clock returns the hour, minute, and second within the day specified by t. func (t Time) Clock() (hour, min, sec int) { return absClock(t.abs()) } // absClock is like clock but operates on an absolute time. func absClock(abs uint64) (hour, min, sec int) { sec = int(abs % secondsPerDay) hour = sec / secondsPerHour sec -= hour * secondsPerHour min = sec / secondsPerMinute sec -= min * secondsPerMinute return } // Hour returns the hour within the day specified by t, in the range [0, 23]. func (t Time) Hour() int { return int(t.abs()%secondsPerDay) / secondsPerHour } // Minute returns the minute offset within the hour specified by t, in the range [0, 59]. func (t Time) Minute() int { return int(t.abs()%secondsPerHour) / secondsPerMinute } // Second returns the second offset within the minute specified by t, in the range [0, 59]. func (t Time) Second() int { return int(t.abs() % secondsPerMinute) } // Nanosecond returns the nanosecond offset within the second specified by t, // in the range [0, 999999999]. func (t Time) Nanosecond() int { return int(t.nsec) } // YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, // and [1,366] in leap years. func (t Time) YearDay() int { _, _, _, yday := t.date(false) return yday + 1 } // A Duration represents the elapsed time between two instants // as an int64 nanosecond count. The representation limits the // largest representable duration to approximately 290 years. type Duration int64 const ( minDuration Duration = -1 << 63 maxDuration Duration = 1<<63 - 1 ) // Common durations. There is no definition for units of Day or larger // to avoid confusion across daylight savings time zone transitions. // // To count the number of units in a Duration, divide: // second := time.Second // fmt.Print(int64(second/time.Millisecond)) // prints 1000 // // To convert an integer number of units to a Duration, multiply: // seconds := 10 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s // const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute ) // String returns a string representing the duration in the form "72h3m0.5s". // Leading zero units are omitted. As a special case, durations less than one // second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure // that the leading digit is non-zero. The zero duration formats as 0, // with no unit. func (d Duration) String() string { // Largest time is 2540400h10m10.000000000s var buf [32]byte w := len(buf) u := uint64(d) neg := d < 0 if neg { u = -u } if u < uint64(Second) { // Special case: if duration is smaller than a second, // use smaller units, like 1.2ms var prec int w-- buf[w] = 's' w-- switch { case u == 0: return "0" case u < uint64(Microsecond): // print nanoseconds prec = 0 buf[w] = 'n' case u < uint64(Millisecond): // print microseconds prec = 3 // U+00B5 'µ' micro sign == 0xC2 0xB5 w-- // Need room for two bytes. copy(buf[w:], "µ") default: // print milliseconds prec = 6 buf[w] = 'm' } w, u = fmtFrac(buf[:w], u, prec) w = fmtInt(buf[:w], u) } else { w-- buf[w] = 's' w, u = fmtFrac(buf[:w], u, 9) // u is now integer seconds w = fmtInt(buf[:w], u%60) u /= 60 // u is now integer minutes if u > 0 { w-- buf[w] = 'm' w = fmtInt(buf[:w], u%60) u /= 60 // u is now integer hours // Stop at hours because days can be different lengths. if u > 0 { w-- buf[w] = 'h' w = fmtInt(buf[:w], u) } } } if neg { w-- buf[w] = '-' } return string(buf[w:]) } // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the // tail of buf, omitting trailing zeros. it omits the decimal // point too when the fraction is 0. It returns the index where the // output bytes begin and the value v/10**prec. func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) { // Omit trailing zeros up to and including decimal point. w := len(buf) print := false for i := 0; i < prec; i++ { digit := v % 10 print = print || digit != 0 if print { w-- buf[w] = byte(digit) + '0' } v /= 10 } if print { w-- buf[w] = '.' } return w, v } // fmtInt formats v into the tail of buf. // It returns the index where the output begins. func fmtInt(buf []byte, v uint64) int { w := len(buf) if v == 0 { w-- buf[w] = '0' } else { for v > 0 { w-- buf[w] = byte(v%10) + '0' v /= 10 } } return w } // Nanoseconds returns the duration as an integer nanosecond count. func (d Duration) Nanoseconds() int64 { return int64(d) } // These methods return float64 because the dominant // use case is for printing a floating point number like 1.5s, and // a truncation to integer would make them not useful in those cases. // Splitting the integer and fraction ourselves guarantees that // converting the returned float64 to an integer rounds the same // way that a pure integer conversion would have, even in cases // where, say, float64(d.Nanoseconds())/1e9 would have rounded // differently. // Seconds returns the duration as a floating point number of seconds. func (d Duration) Seconds() float64 { sec := d / Second nsec := d % Second return float64(sec) + float64(nsec)*1e-9 } // Minutes returns the duration as a floating point number of minutes. func (d Duration) Minutes() float64 { min := d / Minute nsec := d % Minute return float64(min) + float64(nsec)*(1e-9/60) } // Hours returns the duration as a floating point number of hours. func (d Duration) Hours() float64 { hour := d / Hour nsec := d % Hour return float64(hour) + float64(nsec)*(1e-9/60/60) } // Add returns the time t+d. func (t Time) Add(d Duration) Time { t.sec += int64(d / 1e9) nsec := int32(t.nsec) + int32(d%1e9) if nsec >= 1e9 { t.sec++ nsec -= 1e9 } else if nsec < 0 { t.sec-- nsec += 1e9 } t.nsec = nsec return t } // Sub returns the duration t-u. If the result exceeds the maximum (or minimum) // value that can be stored in a Duration, the maximum (or minimum) duration // will be returned. // To compute t-d for a duration d, use t.Add(-d). func (t Time) Sub(u Time) Duration { d := Duration(t.sec-u.sec)*Second + Duration(int32(t.nsec)-int32(u.nsec)) // Check for overflow or underflow. switch { case u.Add(d).Equal(t): return d // d is correct case t.Before(u): return minDuration // t - u is negative out of range default: return maxDuration // t - u is positive out of range } } // Since returns the time elapsed since t. // It is shorthand for time.Now().Sub(t). func Since(t Time) Duration { return Now().Sub(t) } // AddDate returns the time corresponding to adding the // given number of years, months, and days to t. // For example, AddDate(-1, 2, 3) applied to January 1, 2011 // returns March 4, 2010. // // AddDate normalizes its result in the same way that Date does, // so, for example, adding one month to October 31 yields // December 1, the normalized form for November 31. func (t Time) AddDate(years int, months int, days int) Time { year, month, day := t.Date() hour, min, sec := t.Clock() return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc) } const ( secondsPerMinute = 60 secondsPerHour = 60 * 60 secondsPerDay = 24 * secondsPerHour secondsPerWeek = 7 * secondsPerDay daysPer400Years = 365*400 + 97 daysPer100Years = 365*100 + 24 daysPer4Years = 365*4 + 1 ) // date computes the year, day of year, and when full=true, // the month and day in which t occurs. func (t Time) date(full bool) (year int, month Month, day int, yday int) { return absDate(t.abs(), full) } // absDate is like date but operates on an absolute time. func absDate(abs uint64, full bool) (year int, month Month, day int, yday int) { // Split into time and day. d := abs / secondsPerDay // Account for 400 year cycles. n := d / daysPer400Years y := 400 * n d -= daysPer400Years * n // Cut off 100-year cycles. // The last cycle has one extra leap year, so on the last day // of that year, day / daysPer100Years will be 4 instead of 3. // Cut it back down to 3 by subtracting n>>2. n = d / daysPer100Years n -= n >> 2 y += 100 * n d -= daysPer100Years * n // Cut off 4-year cycles. // The last cycle has a missing leap year, which does not // affect the computation. n = d / daysPer4Years y += 4 * n d -= daysPer4Years * n // Cut off years within a 4-year cycle. // The last year is a leap year, so on the last day of that year, // day / 365 will be 4 instead of 3. Cut it back down to 3 // by subtracting n>>2. n = d / 365 n -= n >> 2 y += n d -= 365 * n year = int(int64(y) + absoluteZeroYear) yday = int(d) if !full { return } day = yday if isLeap(year) { // Leap year switch { case day > 31+29-1: // After leap day; pretend it wasn't there. day-- case day == 31+29-1: // Leap day. month = February day = 29 return } } // Estimate month on assumption that every month has 31 days. // The estimate may be too low by at most one month, so adjust. month = Month(day / 31) end := int(daysBefore[month+1]) var begin int if day >= end { month++ begin = end } else { begin = int(daysBefore[month]) } month++ // because January is 1 day = day - begin + 1 return } // daysBefore[m] counts the number of days in a non-leap year // before month m begins. There is an entry for m=12, counting // the number of days before January of next year (365). var daysBefore = [...]int32{ 0, 31, 31 + 28, 31 + 28 + 31, 31 + 28 + 31 + 30, 31 + 28 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31, } func daysIn(m Month, year int) int { if m == February && isLeap(year) { return 29 } return int(daysBefore[m] - daysBefore[m-1]) } // Provided by package runtime. func now() (sec int64, nsec int32) // Now returns the current local time. func Now() Time { sec, nsec := now() return Time{sec + unixToInternal, nsec, Local} } // UTC returns t with the location set to UTC. func (t Time) UTC() Time { t.loc = UTC return t } // Local returns t with the location set to local time. func (t Time) Local() Time { t.loc = Local return t } // In returns t with the location information set to loc. // // In panics if loc is nil. func (t Time) In(loc *Location) Time { if loc == nil { panic("time: missing Location in call to Time.In") } t.loc = loc return t } // Location returns the time zone information associated with t. func (t Time) Location() *Location { l := t.loc if l == nil { l = UTC } return l } // Zone computes the time zone in effect at time t, returning the abbreviated // name of the zone (such as "CET") and its offset in seconds east of UTC. func (t Time) Zone() (name string, offset int) { name, offset, _, _, _ = t.loc.lookup(t.sec + internalToUnix) return } // Unix returns t as a Unix time, the number of seconds elapsed // since January 1, 1970 UTC. func (t Time) Unix() int64 { return t.sec + internalToUnix } // UnixNano returns t as a Unix time, the number of nanoseconds elapsed // since January 1, 1970 UTC. The result is undefined if the Unix time // in nanoseconds cannot be represented by an int64. Note that this // means the result of calling UnixNano on the zero Time is undefined. func (t Time) UnixNano() int64 { return (t.sec+internalToUnix)*1e9 + int64(t.nsec) } const timeBinaryVersion byte = 1 // MarshalBinary implements the encoding.BinaryMarshaler interface. func (t Time) MarshalBinary() ([]byte, error) { var offsetMin int16 // minutes east of UTC. -1 is UTC. if t.Location() == &utcLoc { offsetMin = -1 } else { _, offset := t.Zone() if offset%60 != 0 { return nil, errors.New("Time.MarshalBinary: zone offset has fractional minute") } offset /= 60 if offset < -32768 || offset == -1 || offset > 32767 { return nil, errors.New("Time.MarshalBinary: unexpected zone offset") } offsetMin = int16(offset) } enc := []byte{ timeBinaryVersion, // byte 0 : version byte(t.sec >> 56), // bytes 1-8: seconds byte(t.sec >> 48), byte(t.sec >> 40), byte(t.sec >> 32), byte(t.sec >> 24), byte(t.sec >> 16), byte(t.sec >> 8), byte(t.sec), byte(t.nsec >> 24), // bytes 9-12: nanoseconds byte(t.nsec >> 16), byte(t.nsec >> 8), byte(t.nsec), byte(offsetMin >> 8), // bytes 13-14: zone offset in minutes byte(offsetMin), } return enc, nil } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. func (t *Time) UnmarshalBinary(data []byte) error { buf := data if len(buf) == 0 { return errors.New("Time.UnmarshalBinary: no data") } if buf[0] != timeBinaryVersion { return errors.New("Time.UnmarshalBinary: unsupported version") } if len(buf) != /*version*/ 1+ /*sec*/ 8+ /*nsec*/ 4+ /*zone offset*/ 2 { return errors.New("Time.UnmarshalBinary: invalid length") } buf = buf[1:] t.sec = int64(buf[7]) | int64(buf[6])<<8 | int64(buf[5])<<16 | int64(buf[4])<<24 | int64(buf[3])<<32 | int64(buf[2])<<40 | int64(buf[1])<<48 | int64(buf[0])<<56 buf = buf[8:] t.nsec = int32(buf[3]) | int32(buf[2])<<8 | int32(buf[1])<<16 | int32(buf[0])<<24 buf = buf[4:] offset := int(int16(buf[1])|int16(buf[0])<<8) * 60 if offset == -1*60 { t.loc = &utcLoc } else if _, localoff, _, _, _ := Local.lookup(t.sec + internalToUnix); offset == localoff { t.loc = Local } else { t.loc = FixedZone("", offset) } return nil } // TODO(rsc): Remove GobEncoder, GobDecoder, MarshalJSON, UnmarshalJSON in Go 2. // The same semantics will be provided by the generic MarshalBinary, MarshalText, // UnmarshalBinary, UnmarshalText. // GobEncode implements the gob.GobEncoder interface. func (t Time) GobEncode() ([]byte, error) { return t.MarshalBinary() } // GobDecode implements the gob.GobDecoder interface. func (t *Time) GobDecode(data []byte) error { return t.UnmarshalBinary(data) } // MarshalJSON implements the json.Marshaler interface. // The time is a quoted string in RFC 3339 format, with sub-second precision added if present. func (t Time) MarshalJSON() ([]byte, error) { if y := t.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") } return []byte(t.Format(`"` + RFC3339Nano + `"`)), nil } // UnmarshalJSON implements the json.Unmarshaler interface. // The time is expected to be a quoted string in RFC 3339 format. func (t *Time) UnmarshalJSON(data []byte) (err error) { // Fractional seconds are handled implicitly by Parse. *t, err = Parse(`"`+RFC3339+`"`, string(data)) return } // MarshalText implements the encoding.TextMarshaler interface. // The time is formatted in RFC 3339 format, with sub-second precision added if present. func (t Time) MarshalText() ([]byte, error) { if y := t.Year(); y < 0 || y >= 10000 { return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") } return []byte(t.Format(RFC3339Nano)), nil } // UnmarshalText implements the encoding.TextUnmarshaler interface. // The time is expected to be in RFC 3339 format. func (t *Time) UnmarshalText(data []byte) (err error) { // Fractional seconds are handled implicitly by Parse. *t, err = Parse(RFC3339, string(data)) return } // Unix returns the local Time corresponding to the given Unix time, // sec seconds and nsec nanoseconds since January 1, 1970 UTC. // It is valid to pass nsec outside the range [0, 999999999]. func Unix(sec int64, nsec int64) Time { if nsec < 0 || nsec >= 1e9 { n := nsec / 1e9 sec += n nsec -= n * 1e9 if nsec < 0 { nsec += 1e9 sec-- } } return Time{sec + unixToInternal, int32(nsec), Local} } func isLeap(year int) bool { return year%4 == 0 && (year%100 != 0 || year%400 == 0) } // norm returns nhi, nlo such that // hi * base + lo == nhi * base + nlo // 0 <= nlo < base func norm(hi, lo, base int) (nhi, nlo int) { if lo < 0 { n := (-lo-1)/base + 1 hi -= n lo += n * base } if lo >= base { n := lo / base hi += n lo -= n * base } return hi, lo } // Date returns the Time corresponding to // yyyy-mm-dd hh:mm:ss + nsec nanoseconds // in the appropriate zone for that time in the given location. // // The month, day, hour, min, sec, and nsec values may be outside // their usual ranges and will be normalized during the conversion. // For example, October 32 converts to November 1. // // A daylight savings time transition skips or repeats times. // For example, in the United States, March 13, 2011 2:15am never occurred, // while November 6, 2011 1:15am occurred twice. In such cases, the // choice of time zone, and therefore the time, is not well-defined. // Date returns a time that is correct in one of the two zones involved // in the transition, but it does not guarantee which. // // Date panics if loc is nil. func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time { if loc == nil { panic("time: missing Location in call to Date") } // Normalize month, overflowing into year. m := int(month) - 1 year, m = norm(year, m, 12) month = Month(m) + 1 // Normalize nsec, sec, min, hour, overflowing into day. sec, nsec = norm(sec, nsec, 1e9) min, sec = norm(min, sec, 60) hour, min = norm(hour, min, 60) day, hour = norm(day, hour, 24) y := uint64(int64(year) - absoluteZeroYear) // Compute days since the absolute epoch. // Add in days from 400-year cycles. n := y / 400 y -= 400 * n d := daysPer400Years * n // Add in 100-year cycles. n = y / 100 y -= 100 * n d += daysPer100Years * n // Add in 4-year cycles. n = y / 4 y -= 4 * n d += daysPer4Years * n // Add in non-leap years. n = y d += 365 * n // Add in days before this month. d += uint64(daysBefore[month-1]) if isLeap(year) && month >= March { d++ // February 29 } // Add in days before today. d += uint64(day - 1) // Add in time elapsed today. abs := d * secondsPerDay abs += uint64(hour*secondsPerHour + min*secondsPerMinute + sec) unix := int64(abs) + (absoluteToInternal + internalToUnix) // Look for zone offset for t, so we can adjust to UTC. // The lookup function expects UTC, so we pass t in the // hope that it will not be too close to a zone transition, // and then adjust if it is. _, offset, _, start, end := loc.lookup(unix) if offset != 0 { switch utc := unix - int64(offset); { case utc < start: _, offset, _, _, _ = loc.lookup(start - 1) case utc >= end: _, offset, _, _, _ = loc.lookup(end) } unix -= int64(offset) } return Time{unix + unixToInternal, int32(nsec), loc} } // Truncate returns the result of rounding t down to a multiple of d (since the zero time). // If d <= 0, Truncate returns t unchanged. func (t Time) Truncate(d Duration) Time { if d <= 0 { return t } _, r := div(t, d) return t.Add(-r) } // Round returns the result of rounding t to the nearest multiple of d (since the zero time). // The rounding behavior for halfway values is to round up. // If d <= 0, Round returns t unchanged. func (t Time) Round(d Duration) Time { if d <= 0 { return t } _, r := div(t, d) if r+r < d { return t.Add(-r) } return t.Add(d - r) } // div divides t by d and returns the quotient parity and remainder. // We don't use the quotient parity anymore (round half up instead of round to even) // but it's still here in case we change our minds. func div(t Time, d Duration) (qmod2 int, r Duration) { neg := false nsec := int32(t.nsec) if t.sec < 0 { // Operate on absolute value. neg = true t.sec = -t.sec nsec = -nsec if nsec < 0 { nsec += 1e9 t.sec-- // t.sec >= 1 before the -- so safe } } switch { // Special case: 2d divides 1 second. case d < Second && Second%(d+d) == 0: qmod2 = int(nsec/int32(d)) & 1 r = Duration(nsec % int32(d)) // Special case: d is a multiple of 1 second. case d%Second == 0: d1 := int64(d / Second) qmod2 = int(t.sec/d1) & 1 r = Duration(t.sec%d1)*Second + Duration(nsec) // General case. // This could be faster if more cleverness were applied, // but it's really only here to avoid special case restrictions in the API. // No one will care about these cases. default: // Compute nanoseconds as 128-bit number. sec := uint64(t.sec) tmp := (sec >> 32) * 1e9 u1 := tmp >> 32 u0 := tmp << 32 tmp = uint64(sec&0xFFFFFFFF) * 1e9 u0x, u0 := u0, u0+tmp if u0 < u0x { u1++ } u0x, u0 = u0, u0+uint64(nsec) if u0 < u0x { u1++ } // Compute remainder by subtracting r<>63 != 1 { d1 <<= 1 } d0 := uint64(0) for { qmod2 = 0 if u1 > d1 || u1 == d1 && u0 >= d0 { // subtract qmod2 = 1 u0x, u0 = u0, u0-d0 if u0 > u0x { u1-- } u1 -= d1 } if d1 == 0 && d0 == uint64(d) { break } d0 >>= 1 d0 |= (d1 & 1) << 63 d1 >>= 1 } r = Duration(u0) } if neg && r != 0 { // If input was negative and not an exact multiple of d, we computed q, r such that // q*d + r = -t // But the right answers are given by -(q-1), d-r: // q*d + r = -t // -q*d - r = t // -(q-1)*d + (d - r) = t qmod2 ^= 1 r = d - r } return } ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/unsafe/unsafe.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package unsafe contains operations that step around the type safety of Go programs. Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines. */ package unsafe // ArbitraryType is here for the purposes of documentation only and is not actually // part of the unsafe package. It represents the type of an arbitrary Go expression. type ArbitraryType int // Pointer represents a pointer to an arbitrary type. There are four special operations // available for type Pointer that are not available for other types. // 1) A pointer value of any type can be converted to a Pointer. // 2) A Pointer can be converted to a pointer value of any type. // 3) A uintptr can be converted to a Pointer. // 4) A Pointer can be converted to a uintptr. // Pointer therefore allows a program to defeat the type system and read and write // arbitrary memory. It should be used with extreme care. type Pointer *ArbitraryType // Sizeof returns the size in bytes occupied by the value v. The size is that of the // "top level" of the value only. For instance, if v is a slice, it returns the size of // the slice descriptor, not the size of the memory referenced by the slice. func Sizeof(v ArbitraryType) uintptr // Offsetof returns the offset within the struct of the field represented by v, // which must be of the form structValue.field. In other words, it returns the // number of bytes between the start of the struct and the start of the field. func Offsetof(v ArbitraryType) uintptr // Alignof returns the alignment of the value v. It is the maximum value m such // that the address of a variable with the type of v will always be zero mod m. // If v is of the form structValue.field, it returns the alignment of field f within struct object obj. func Alignof(v ArbitraryType) uintptr ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/withmain/main_package.go ================================================ package main ================================================ FILE: testData/mockSdk-1.1.2/src/pkg/withmain/not_main_package.go ================================================ package withmain type SomeType struct { } ================================================ FILE: testData/parameterInfo/chainedCall.go ================================================ package main type ( ds1 struct { } ds2 struct { } ) func (d ds1) d1(param1 string, param2 int) ds2 { return ds2{} } func (d ds2) d2(param1 string, param2 int) int { return 1 } func main() { d := ds1{} d.d1("1", 2).d2() } ================================================ FILE: testData/parameterInfo/closure.go ================================================ package main func main() { go func(param1, param2 string) (return1, return2 string) { return param1, param2 }("1", ) } ================================================ FILE: testData/parameterInfo/fieldMethCall.go ================================================ package main type Outer struct { inner Inner } type Inner struct {} func (i* Inner) f(a, b int) {} func (o* Outer) Test() { o.inner.f() } ================================================ FILE: testData/parameterInfo/funcEmbedInner.go ================================================ package foo func bar(num int, text string) { } func blah(a, b, c, d int) int { return a + b } func test() { blah(1, 2, bar(3, ), 4) } ================================================ FILE: testData/parameterInfo/funcEmbedOuter.go ================================================ package foo func bar(num int, text string) { } func blah(a, b, c, d int) int { return a + b } func test() { blah(1, 2, bar(3, ), 4) } ================================================ FILE: testData/parameterInfo/funcParam.go ================================================ package foo func bar(num int, text string) { } func test() { bar(1, ) } ================================================ FILE: testData/parameterInfo/funcParamEllipsis.go ================================================ package foo func bar(num int, text string, more ...int) { } func test() { bar(1, "text", 2, 3, 4, ) } ================================================ FILE: testData/parameterInfo/funcParamMulti.go ================================================ package foo func bar(a, b, c int, d, e, f string) { } func test() { bar(1, 2, 3, "4", ) } ================================================ FILE: testData/parameterInfo/funcParamNone.go ================================================ package foo func bar() { } func test() { bar() } ================================================ FILE: testData/parameterInfo/funcTypes.go ================================================ package main func main() { v := ReturnsFunc("1")(10)("") } func ReturnsFunc(s string) func (int) func(string) string { return func (i int) func(string) string { return func (foo string) string { return "ola" } } } ================================================ FILE: testData/parameterInfo/functionTypeByRef.go ================================================ package main import ( "fmt" "reflect" ) type b func(intParam int) type a b func c() { aFunc := generateFunc() if f, ok := aFunc.(a); ok { fmt.Println(reflect.TypeOf(f)) f() } } func generateFunc() interface{} { return a(func (intParam int) { }) } func main() { c() } ================================================ FILE: testData/parameterInfo/methParam.go ================================================ package foo type Dummy struct { a int } func (d* Dummy) bar(num int, text string) { } func test() { d := new(Dummy) d.bar(1, ) } ================================================ FILE: testData/parameterInfo/methParamEllipsis.go ================================================ package foo type Dummy int func (d *Dummy) bar(num int, text string, more ...int) { } func test() { d := new(Dummy) d.bar(1, "text", 2, 3, 4, ) } ================================================ FILE: testData/parameterInfo/methParamNone.go ================================================ package foo type Dummy int func (d *Dummy) bar() { } func test() { d := new(Dummy) d.bar() } ================================================ FILE: testData/parameterInfo/unnamedAndNamedParameters.go ================================================ package foo type Registry interface { Register(a string, interface{}) } func (r Registry) bar() { r.Register() } ================================================ FILE: testData/parameterInfo/unnamedParameters.go ================================================ package foo type Registry interface { Register(string, interface{}) } func (r Registry) bar() { r.Register() } ================================================ FILE: testData/parser/ArrayTypes.go ================================================ package pem func Encode() error { if err := Write([]byte(1)); err != nil { } if len > 0 { } } ================================================ FILE: testData/parser/ArrayTypes.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('pem') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('Encode') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') PsiElement(>)('>') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/ArrayTypesInRanges.go ================================================ package main type File struct { } func main() { for _ = range []File{} { } } ================================================ FILE: testData/parser/ArrayTypesInRanges.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('File') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE REFERENCE_EXPRESSION PsiElement(identifier)('_') PsiElement(=)('=') PsiElement(range)('range') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('File') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/BlockRecover.go ================================================ package main func main() { test( asd asd) test() asd) test() } func test() { } ================================================ FILE: testData/parser/BlockRecover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('test') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('asd') PsiErrorElement:')', ',' or '...' expected, got 'asd' SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('asd') PsiErrorElement:',', ';', <-, , or '}' expected, got ')' PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('test') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('asd') PsiErrorElement:',', ';', <-, , or '}' expected, got ')' PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('test') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('test') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') ================================================ FILE: testData/parser/Cars.go ================================================ package main import "fmt" type Car struct { wheelCount int } func (car Car) numberOfWheels() int { return car.wheelCount } type Ferrari struct { Car } func (f Ferrari) sayHiToSchumacher() { fmt.Println("Hi Schumacher!") } type AstonMartin struct { Car } func (a AstonMartin) sayHiToBond() { fmt.Println("Hi Bond, James Bond!") } func main() { f := Ferrari{Car{4}} fmt.Println("A Ferrari has this many wheels: ", f.numberOfWheels()) //has car behavior f.sayHiToSchumacher() //has Ferrari behavior a := AstonMartin{Car{4}} fmt.Println("An Aston Martin has this many wheels: ", a.numberOfWheels()) //has car behavior a.sayHiToBond() //has AstonMartin behavior } ================================================ FILE: testData/parser/Cars.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Car') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('wheelCount') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('car') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Car') PsiElement())(')') PsiElement(identifier)('numberOfWheels') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('car') PsiElement(.)('.') PsiElement(identifier)('wheelCount') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Ferrari') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION ANONYMOUS_FIELD_DEFINITION TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Car') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('f') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Ferrari') PsiElement())(')') PsiElement(identifier)('sayHiToSchumacher') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hi Schumacher!"') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('AstonMartin') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION ANONYMOUS_FIELD_DEFINITION TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Car') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('a') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('AstonMartin') PsiElement())(')') PsiElement(identifier)('sayHiToBond') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hi Bond, James Bond!"') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('f') PsiElement(:=)(':=') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Ferrari') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Car') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL PsiElement(int)('4') PsiElement(})('}') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"A Ferrari has this many wheels: "') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('f') PsiElement(.)('.') PsiElement(identifier)('numberOfWheels') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('//has car behavior') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('f') PsiElement(.)('.') PsiElement(identifier)('sayHiToSchumacher') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('//has Ferrari behavior') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('AstonMartin') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Car') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL PsiElement(int)('4') PsiElement(})('}') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"An Aston Martin has this many wheels: "') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(.)('.') PsiElement(identifier)('numberOfWheels') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('//has car behavior') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(.)('.') PsiElement(identifier)('sayHiToBond') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('//has AstonMartin behavior') PsiElement(})('}') ================================================ FILE: testData/parser/ChanRecover.go ================================================ package n func f() { // test case from issue 13273 <-chan int((chan int)(nil)) <-chan int(nil) <-chan chan int(nil) <-chan chan chan int(nil) <-chan chan chan chan int(nil) <-chan chan chan chan chan int(nil) <-chan <-chan int(nil) <-chan <-chan <-chan int(nil) <-chan <-chan <-chan <-chan int(nil) <-chan <-chan <-chan <-chan <-chan int(nil) <-chan (<-chan int)(nil) <-chan (<-chan (<-chan int))(nil) <-chan (<-chan (<-chan (<-chan int)))(nil) <-chan (<-chan (<-chan (<-chan (<-chan int))))(nil) <-(<-chan int)(nil) <-(<-chan chan int)(nil) <-(<-chan chan chan int)(nil) <-(<-chan chan chan chan int)(nil) <-(<-chan chan chan chan chan int)(nil) <-(<-chan <-chan int)(nil) <-(<-chan <-chan <-chan int)(nil) <-(<-chan <-chan <-chan <-chan int)(nil) <-(<-chan <-chan <-chan <-chan <-chan int)(nil) <-(<-chan (<-chan int))(nil) <-(<-chan (<-chan (<-chan int)))(nil) <-(<-chan (<-chan (<-chan (<-chan int))))(nil) <-(<-chan (<-chan (<-chan (<-chan (<-chan int)))))(nil) type _ <-<-chan int // ERROR "unexpected <-, expecting chan" <-chan int // ERROR "unexpected <-, expecting chan|expecting {" (new parser: same error as for type decl) <-<-chan int // ERROR "unexpected <-, expecting chan|expecting {" (new parser: same error as for type decl) type _ <-chan <-int // ERROR "unexpected int, expecting chan|expecting chan" <-chan<-int // ERROR "unexpected int, expecting chan|expecting {" (new parser: same error as for type decl) } ================================================ FILE: testData/parser/ChanRecover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('n') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('f') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// test case from issue 13273') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') PsiElement(<-)('<-') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('_') CHANNEL_TYPE PsiElement(<-)('<-') PsiErrorElement:chan expected, got '<-' CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiComment(GO_LINE_COMMENT)('// ERROR "unexpected <-, expecting chan"') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') PsiErrorElement:'!', '!=', '%', '&', '&^', '(', '*', '+', '++', '-', '--', '/', <, <-, <<, <=, , , , '==', '>', '>=', '>>', '[', '^', chan, func, identifier, interface, map, struct or '|' expected, got 'chan' PsiElement(chan)('chan') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiComment(GO_LINE_COMMENT)('// ERROR "unexpected <-, expecting chan|expecting {" (new parser: same error as for type decl)') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') UNARY_EXPR PsiElement(<-)('<-') PsiErrorElement:'!', '!=', '%', '&', '&^', '(', '*', '+', '++', '-', '--', '/', <, <-, <<, <=, , , , '==', '>', '>=', '>>', '[', '^', chan, func, identifier, interface, map, struct or '|' expected, got 'chan' PsiElement(chan)('chan') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiComment(GO_LINE_COMMENT)('// ERROR "unexpected <-, expecting chan|expecting {" (new parser: same error as for type decl)') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('_') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') CHANNEL_TYPE PsiElement(<-)('<-') PsiErrorElement:chan expected, got 'int' TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiComment(GO_LINE_COMMENT)('// ERROR "unexpected int, expecting chan|expecting chan"') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') PsiErrorElement:'!', '!=', '%', '&', '&^', '(', '*', '+', '++', '-', '--', '/', <, <-, <<, <=, , , , '==', '>', '>=', '>>', '[', '^', chan, func, identifier, interface, map, struct or '|' expected, got 'chan' PsiElement(chan)('chan') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiComment(GO_LINE_COMMENT)('// ERROR "unexpected int, expecting chan|expecting {" (new parser: same error as for type decl)') PsiElement(})('}') ================================================ FILE: testData/parser/ElementRecover.go ================================================ package foo type connection interface{} func (conn *connection) Delete(ctx *context.Context) (err errors.Error) { connection := &entity.Connection{ connection.AccountID = ctx.Bag["accountID"].(int64), connection.AccountID = ctx.Bag["accountID"].(int64) } if err = conn.storage.Delete(connection); err != nil { return } server.WriteResponse(ctx, "", http.StatusNoContent, 10) return } func (conn *connection) Create(ctx *context.Context) (err errors.Error) { } ================================================ FILE: testData/parser/ElementRecover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('foo') IMPORT_LIST TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('connection') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('conn') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('connection') PsiElement())(')') PsiElement(identifier)('Delete') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('ctx') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('context') PsiElement(.)('.') PsiElement(identifier)('Context') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('Error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('connection') PsiElement(:=)(':=') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('entity') PsiElement(.)('.') PsiElement(identifier)('Connection') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('connection') PsiElement(.)('.') PsiElement(identifier)('AccountID') PsiErrorElement:'!=', '%', '&', '&^', '(', '*', '+', '-', '/', ':', <, <<, <=, '==', '>', '>=', '>>', '^', '{' or '|' expected, got '=' PsiElement(=)('=') PsiElement(DUMMY_BLOCK) PsiElement(identifier)('ctx') PsiElement(.)('.') PsiElement(identifier)('Bag') PsiElement([)('[') PsiElement(string)('"accountID"') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') PsiElement(identifier)('int64') PsiElement())(')') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('connection') PsiElement(.)('.') PsiElement(identifier)('AccountID') PsiErrorElement:'!=', '%', '&', '&^', '(', '*', '+', '-', '/', ':', <, <<, <=, '==', '>', '>=', '>>', '^', '{' or '|' expected, got '=' PsiElement(=)('=') PsiElement(DUMMY_BLOCK) PsiElement(identifier)('ctx') PsiElement(.)('.') PsiElement(identifier)('Bag') PsiElement([)('[') PsiElement(string)('"accountID"') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') PsiElement(identifier)('int64') PsiElement())(')') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('conn') PsiElement(.)('.') PsiElement(identifier)('storage') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Delete') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('connection') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('server') PsiElement(.)('.') PsiElement(identifier)('WriteResponse') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ctx') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('http') PsiElement(.)('.') PsiElement(identifier)('StatusNoContent') PsiElement(,)(',') LITERAL PsiElement(int)('10') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('conn') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('connection') PsiElement())(')') PsiElement(identifier)('Create') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('ctx') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('context') PsiElement(.)('.') PsiElement(identifier)('Context') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('Error') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') ================================================ FILE: testData/parser/Error.go ================================================ // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // The Error interface identifies a run time error. type Error interface { error // RuntimeError is a no-op function but // serves to distinguish types that are runtime // errors from ordinary errors: a type is a // runtime error if it has a RuntimeError method. RuntimeError() } // A TypeAssertionError explains a failed type assertion. type TypeAssertionError struct { interfaceString string concreteString string assertedString string missingMethod string // one method needed by Interface, missing from Concrete } func (*TypeAssertionError) RuntimeError() {} func (e *TypeAssertionError) Error() string { inter := e.interfaceString if inter == "" { inter = "interface" } if e.concreteString == "" { return "interface conversion: " + inter + " is nil, not " + e.assertedString } if e.missingMethod == "" { return "interface conversion: " + inter + " is " + e.concreteString + ", not " + e.assertedString } return "interface conversion: " + e.concreteString + " is not " + e.assertedString + ": missing method " + e.missingMethod } // For calling from C. func newTypeAssertionError(ps1, ps2, ps3 *string, pmeth *string, ret *interface{}) { var s1, s2, s3, meth string if ps1 != nil { s1 = *ps1 } if ps2 != nil { s2 = *ps2 } if ps3 != nil { s3 = *ps3 } if pmeth != nil { meth = *pmeth } *ret = &TypeAssertionError{s1, s2, s3, meth} } // An errorString represents a runtime error described by a single string. type errorString string func (e errorString) RuntimeError() {} func (e errorString) Error() string { aaa return "runtime error: " + string(e) } // For calling from C. func newErrorString(s string, ret *interface{}) { *ret = errorString(s) } type stringer interface { String() string } func typestring(interface{}) string // For calling from C. // Prints an argument passed to panic. // There's room for arbitrary complexity here, but we keep it // simple and handle just a few important cases: int, string, and Stringer. func printany(i interface{}) { switch v := i.(type) { case nil: print("nil") case stringer: print(v.String()) case error: print(v.Error()) case int: print(v) case string: print(v) default: print("(", typestring(i), ") ", i) } } // called from generated code func panicwrap(pkg, typ, meth string) { panic("value method " + pkg + "." + typ + "." + meth + " called using nil *" + typ + " pointer") } // New returns an initialized Fetcher. func New(h Handler) *Fetcher { return &Fetcher{ Handler: h, CrawlDelay: DefaultCrawlDelay, HttpClient: http.DefaultClient, UserAgent: DefaultUserAgent, WorkerIdleTTL: DefaultWorkerIdleTTL, dbg: make(chan *DebugInfo, 1), } } ================================================ FILE: testData/parser/Error.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// Copyright 2010 The Go Authors. All rights reserved.') PsiComment(GO_LINE_COMMENT)('// Use of this source code is governed by a BSD-style') PsiComment(GO_LINE_COMMENT)('// license that can be found in the LICENSE file.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('runtime') IMPORT_LIST PsiComment(GO_LINE_COMMENT)('// The Error interface identifies a run time error.') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Error') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') METHOD_SPEC TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiComment(GO_LINE_COMMENT)('// RuntimeError is a no-op function but') PsiComment(GO_LINE_COMMENT)('// serves to distinguish types that are runtime') PsiComment(GO_LINE_COMMENT)('// errors from ordinary errors: a type is a') PsiComment(GO_LINE_COMMENT)('// runtime error if it has a RuntimeError method.') METHOD_SPEC PsiElement(identifier)('RuntimeError') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// A TypeAssertionError explains a failed type assertion.') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('TypeAssertionError') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('interfaceString') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('concreteString') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('assertedString') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('missingMethod') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiComment(GO_LINE_COMMENT)('// one method needed by Interface, missing from Concrete') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TypeAssertionError') PsiElement())(')') PsiElement(identifier)('RuntimeError') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('e') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TypeAssertionError') PsiElement())(')') PsiElement(identifier)('Error') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('inter') PsiElement(:=)(':=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('interfaceString') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('inter') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('inter') ASSIGN_OP PsiElement(=)('=') STRING_LITERAL PsiElement(string)('"interface"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('concreteString') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR STRING_LITERAL PsiElement(string)('"interface conversion: "') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('inter') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('" is nil, not "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('assertedString') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('missingMethod') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR STRING_LITERAL PsiElement(string)('"interface conversion: "') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('inter') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('" is "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('concreteString') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('", not "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('assertedString') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR STRING_LITERAL PsiElement(string)('"interface conversion: "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('concreteString') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('" is not "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('assertedString') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('": missing method "') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('missingMethod') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// For calling from C.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('newTypeAssertionError') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('ps1') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('ps2') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('ps3') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('pmeth') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('ret') POINTER_TYPE PsiElement(*)('*') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('s1') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('s2') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('s3') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('meth') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('ps1') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('s1') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ps1') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('ps2') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('s2') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ps2') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('ps3') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('s3') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ps3') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('pmeth') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('meth') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('pmeth') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ret') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TypeAssertionError') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('s1') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('s2') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('s3') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('meth') PsiElement(})('}') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// An errorString represents a runtime error described by a single string.') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('errorString') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('e') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('errorString') PsiElement())(')') PsiElement(identifier)('RuntimeError') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('e') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('errorString') PsiElement())(')') PsiElement(identifier)('Error') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('aaa') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR STRING_LITERAL PsiElement(string)('"runtime error: "') PsiElement(+)('+') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('string') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// For calling from C.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('newErrorString') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('ret') POINTER_TYPE PsiElement(*)('*') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ret') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('errorString') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('stringer') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') METHOD_SPEC PsiElement(identifier)('String') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('typestring') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiComment(GO_LINE_COMMENT)('// For calling from C.') PsiComment(GO_LINE_COMMENT)('// Prints an argument passed to panic.') PsiComment(GO_LINE_COMMENT)('// There's room for arbitrary complexity here, but we keep it') PsiComment(GO_LINE_COMMENT)('// simple and handle just a few important cases: int, string, and Stringer.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('printany') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('i') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') BLOCK PsiElement({)('{') TYPE_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') TYPE_SWITCH_GUARD VAR_DEFINITION PsiElement(identifier)('v') PsiElement(:=)(':=') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(.)('.') TYPE_GUARD PsiElement(()('(') PsiElement(type)('type') PsiElement())(')') PsiElement({)('{') TYPE_CASE_CLAUSE PsiElement(case)('case') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"nil"') PsiElement())(')') TYPE_CASE_CLAUSE PsiElement(case)('case') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stringer') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement(.)('.') PsiElement(identifier)('String') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') TYPE_CASE_CLAUSE PsiElement(case)('case') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement(.)('.') PsiElement(identifier)('Error') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') TYPE_CASE_CLAUSE PsiElement(case)('case') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement())(')') TYPE_CASE_CLAUSE PsiElement(case)('case') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement())(')') TYPE_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('print') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"("') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('typestring') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('") "') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// called from generated code') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('panicwrap') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('pkg') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('typ') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('meth') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR STRING_LITERAL PsiElement(string)('"value method "') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('pkg') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('"."') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('typ') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('"."') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('meth') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('" called using nil *"') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('typ') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('" pointer"') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// New returns an initialized Fetcher.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('New') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('h') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Handler') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Fetcher') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Fetcher') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Handler') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('CrawlDelay') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('DefaultCrawlDelay') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('HttpClient') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('http') PsiElement(.)('.') PsiElement(identifier)('DefaultClient') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('UserAgent') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('DefaultUserAgent') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('WorkerIdleTTL') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('DefaultWorkerIdleTTL') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('dbg') PsiElement(:)(':') VALUE BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('DebugInfo') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement(,)(',') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/ExpressionPerformance.go ================================================ package performance import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestFoo(t *testing.T) { Convey("All starts with 1", t, func() { So(Foo(), ShouldEqual, 1) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 2) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 3) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 4) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 5) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 6) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 7) Convey("Then it increases", func() { So(Foo(), ShouldEqual, 8) Convey("Then it stops", func() { So(Foo(), ShouldEqual, func() { } ) }) }) }) }) }) }) }) }) }) } ================================================ FILE: testData/parser/ExpressionPerformance.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('performance') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') PsiElement(()('(') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"testing"') IMPORT_SPEC PsiElement(.)('.') IMPORT_STRING STRING_LITERAL PsiElement(string)('"github.com/smartystreets/goconvey/convey"') PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('TestFoo') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('t') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('testing') PsiElement(.)('.') PsiElement(identifier)('T') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"All starts with 1"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('2') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('3') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('4') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('5') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('6') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it increases"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') LITERAL PsiElement(int)('8') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Convey') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Then it stops"') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('So') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Foo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('ShouldEqual') PsiElement(,)(',') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/If.go ================================================ package main import "fmt" type A struct { } func main() { var err error if false { panic(err) } if err !=nil {panic(err)} fmt.Println("Hello, playground") x := make(map[string]int) x["foo"] = 1 if _, ok := x["foo"]; !ok {fmt.Println("Missing key 'foo'")} type A struct {} if &A{} {panic("foo")} // error, it's ok } ================================================ FILE: testData/parser/If.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('A') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('false') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hello, playground"') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('x') PsiElement(:=)(':=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement([)('[') STRING_LITERAL PsiElement(string)('"foo"') PsiElement(])(']') ASSIGN_OP PsiElement(=)('=') LITERAL PsiElement(int)('1') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('_') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('ok') PsiElement(:=)(':=') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement([)('[') STRING_LITERAL PsiElement(string)('"foo"') PsiElement(])(']') PsiElement(;)(';') UNARY_EXPR PsiElement(!)('!') REFERENCE_EXPRESSION PsiElement(identifier)('ok') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Missing key 'foo'"') PsiElement())(')') PsiElement(})('}') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('A') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('A') BLOCK PsiElement({)('{') PsiElement(})('}') PsiErrorElement:';', , else or '}' expected, got '{' STATEMENT BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"foo"') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// error, it's ok') PsiElement(})('}') ================================================ FILE: testData/parser/IfComposite.go ================================================ package main func main() { if allowedErrors[osPkg{"", ""}] { } } type osPkg struct { goos, pkg string } var allowedErrors = map[osPkg]bool{ osPkg{"windows", "log/syslog"}: true, osPkg{"plan9", "log/syslog"}: true, } ================================================ FILE: testData/parser/IfComposite.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('allowedErrors') PsiElement([)('[') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('osPkg') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(})('}') PsiElement(])(']') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('osPkg') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('goos') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('pkg') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('allowedErrors') PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('osPkg') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('osPkg') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"windows"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"log/syslog"') PsiElement(})('}') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT KEY COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('osPkg') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"plan9"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"log/syslog"') PsiElement(})('}') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') PsiElement(})('}') ================================================ FILE: testData/parser/IfWithNew.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // HTTP server. See RFC 2616. package http func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) { for { w, err := c.readRequest() } for atomic.LoadUint32(&x) != expected { } for ; ; c <- *a[S{}.i] { if t != nil { break } } if req.RequestURI == "*" && req.Method == "OPTIONS" { handler = globalOptionsHandler{} } for { handler = globalOptionsHandler{} } if err := bar(func() int {return 42}); err != nil { panic(err) } type M2 struct { name string; want int } for n, tt := range []M2{ {"Alice", 1}, {"Bob", 2}, {"Chris", 3}, } { fmt.Print(n, tt) } } func ValidName(name string) (string, error) { if kind, ok := map[string]string{ "basic": "Basic", "active": "Active", }[strings.ToLower(name)]; ok { return kind, nil } else { return "", fmt.Errorf("Invalid name: %s", name) } } ================================================ FILE: testData/parser/IfWithNew.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// Copyright 2009 The Go Authors. All rights reserved.') PsiComment(GO_LINE_COMMENT)('// Use of this source code is governed by a BSD-style') PsiComment(GO_LINE_COMMENT)('// license that can be found in the LICENSE file.') PsiComment(GO_LINE_COMMENT)('// HTTP server. See RFC 2616.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('http') IMPORT_LIST METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('sh') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('serverHandler') PsiElement())(')') PsiElement(identifier)('ServeHTTP') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('rw') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('ResponseWriter') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('req') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Request') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('w') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(.)('.') PsiElement(identifier)('readRequest') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('atomic') PsiElement(.)('.') PsiElement(identifier)('LoadUint32') ARGUMENT_LIST PsiElement(()('(') UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement())(')') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('expected') BLOCK PsiElement({)('{') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE PsiElement(;)(';') PsiElement(;)(';') SEND_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(<-)('<-') UNARY_EXPR PsiElement(*)('*') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement([)('[') SELECTOR_EXPR COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('S') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') PsiElement(})('}') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST AND_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('req') PsiElement(.)('.') PsiElement(identifier)('RequestURI') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('"*"') PsiElement(&&)('&&') CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('req') PsiElement(.)('.') PsiElement(identifier)('Method') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('"OPTIONS"') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('handler') ASSIGN_OP PsiElement(=)('=') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('globalOptionsHandler') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('handler') ASSIGN_OP PsiElement(=)('=') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('globalOptionsHandler') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('bar') ARGUMENT_LIST PsiElement(()('(') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') LITERAL PsiElement(int)('42') PsiElement(})('}') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('M2') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('name') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(;)(';') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('want') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('n') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('tt') PsiElement(:=)(':=') PsiElement(range)('range') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('M2') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Alice"') PsiElement(,)(',') ELEMENT VALUE LITERAL PsiElement(int)('1') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Bob"') PsiElement(,)(',') ELEMENT VALUE LITERAL PsiElement(int)('2') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Chris"') PsiElement(,)(',') ELEMENT VALUE LITERAL PsiElement(int)('3') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Print') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('tt') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ValidName') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('name') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PsiElement(()('(') TYPE_LIST TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('kind') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('ok') PsiElement(:=)(':=') INDEX_OR_SLICE_EXPR COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY STRING_LITERAL PsiElement(string)('"basic"') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"Basic"') PsiElement(,)(',') ELEMENT KEY STRING_LITERAL PsiElement(string)('"active"') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"Active"') PsiElement(,)(',') PsiElement(})('}') PsiElement([)('[') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strings') PsiElement(.)('.') PsiElement(identifier)('ToLower') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement())(')') PsiElement(])(']') PsiElement(;)(';') REFERENCE_EXPRESSION PsiElement(identifier)('ok') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('kind') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Errorf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Invalid name: %s"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/IncDec.go ================================================ package main func main() { var a = 1 var b = 1 a, b++ a, b-- a++ b++ } ================================================ FILE: testData/parser/IncDec.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('a') PsiElement(=)('=') LITERAL PsiElement(int)('1') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('b') PsiElement(=)('=') LITERAL PsiElement(int)('1') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiErrorElement:',', ';', <-, , or '}' expected, got '++' PsiElement(++)('++') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiErrorElement:',', ';', <-, , or '}' expected, got '--' PsiElement(--)('--') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(++)('++') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(++)('++') PsiElement(})('}') ================================================ FILE: testData/parser/IncompleteRanges.go ================================================ package ff func main() { for a = ran for b := ran for ran for i := 1;; } ================================================ FILE: testData/parser/IncompleteRanges.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('ff') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(=)('=') PsiErrorElement:range expected, got 'ran' REFERENCE_EXPRESSION PsiElement(identifier)('ran') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('b') PsiElement(:=)(':=') PsiErrorElement:',', '=' or range expected, got 'ran' REFERENCE_EXPRESSION PsiElement(identifier)('ran') FOR_STATEMENT PsiElement(for)('for') PsiErrorElement:'!', '&', '(', '*', '+', '-', ';', <-, , , '[', '^', chan, func, identifier, interface, map, struct, '{' or '}' expected, got 'ran' SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('ran') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') LITERAL PsiElement(int)('1') PsiElement(;)(';') PsiElement(;)(';') PsiErrorElement: or '{' expected, got '}' PsiElement(})('}') ================================================ FILE: testData/parser/IncompleteTypeDeclaration.go ================================================ package ff type ( a b c ) func main() {} ================================================ FILE: testData/parser/IncompleteTypeDeclaration.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('ff') IMPORT_LIST TYPE_DECLARATION PsiElement(type)('type') PsiElement(()('(') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('a') PsiErrorElement: expected, got '' TYPE_SPEC SPEC_TYPE PsiElement(identifier)('b') PsiErrorElement: expected, got '' TYPE_SPEC SPEC_TYPE PsiElement(identifier)('c') PsiErrorElement: expected, got '' PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') ================================================ FILE: testData/parser/IncompleteVarDeclaration.go ================================================ package ff var ( a b c = ) func main() {} type foo struct { bar string } var ( baz = []*foo{ { }, } func foo1() { } ================================================ FILE: testData/parser/IncompleteVarDeclaration.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('ff') IMPORT_LIST VAR_DECLARATION PsiElement(var)('var') PsiElement(()('(') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('a') PsiErrorElement:',', or '=' expected, got '' VAR_SPEC VAR_DEFINITION PsiElement(identifier)('b') PsiErrorElement:',', or '=' expected, got '' VAR_SPEC VAR_DEFINITION PsiElement(identifier)('c') PsiElement(=)('=') PsiErrorElement: expected, got ')' PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('foo') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('bar') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') PsiElement(()('(') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('baz') PsiElement(=)('=') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('foo') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') PsiErrorElement:')' or identifier expected, got 'func' FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('foo1') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') ================================================ FILE: testData/parser/Labels.go ================================================ // errorcheck // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Verify that erroneous labels are caught by the compiler. // This set is caught by pass 2. That's why this file is label1.go. // Does not compile. package main var x int func f() { L1: for { if x == 0 { break L1 } if x == 1 { continue L1 } goto L1 } L2: select { default: if x == 0 { break L2 } if x == 1 { continue L2 // ERROR "invalid continue label .*L2" } goto L2 } L3: switch { case x > 10: if x == 11 { break L3 } if x == 12 { continue L3 // ERROR "invalid continue label .*L3" } goto L3 } L4: if true { if x == 13 { break L4 // ERROR "invalid break label .*L4" } if x == 14 { continue L4 // ERROR "invalid continue label .*L4" } if x == 15 { goto L4 } } L5: f() if x == 16 { break L5 // ERROR "invalid break label .*L5" } if x == 17 { continue L5 // ERROR "invalid continue label .*L5" } if x == 18 { goto L5 } for { if x == 19 { break L1 // ERROR "invalid break label .*L1" } if x == 20 { continue L1 // ERROR "invalid continue label .*L1" } if x == 21 { goto L1 } } } ================================================ FILE: testData/parser/Labels.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// errorcheck') PsiComment(GO_LINE_COMMENT)('// Copyright 2011 The Go Authors. All rights reserved.') PsiComment(GO_LINE_COMMENT)('// Use of this source code is governed by a BSD-style') PsiComment(GO_LINE_COMMENT)('// license that can be found in the LICENSE file.') PsiComment(GO_LINE_COMMENT)('// Verify that erroneous labels are caught by the compiler.') PsiComment(GO_LINE_COMMENT)('// This set is caught by pass 2. That's why this file is label1.go.') PsiComment(GO_LINE_COMMENT)('// Does not compile.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('x') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('f') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('L1') PsiElement(:)(':') FOR_STATEMENT PsiElement(for)('for') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L1') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('1') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L1') PsiElement(})('}') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L1') PsiElement(})('}') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('L2') PsiElement(:)(':') SELECT_STATEMENT PsiElement(select)('select') PsiElement({)('{') COMM_CLAUSE COMM_CASE PsiElement(default)('default') PsiElement(:)(':') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L2') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('1') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L2') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid continue label .*L2"') PsiElement(})('}') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L2') PsiElement(})('}') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('L3') PsiElement(:)(':') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(>)('>') LITERAL PsiElement(int)('10') PsiElement(:)(':') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('11') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L3') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('12') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L3') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid continue label .*L3"') PsiElement(})('}') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L3') PsiElement(})('}') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('L4') PsiElement(:)(':') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('true') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('13') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L4') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid break label .*L4"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('14') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L4') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid continue label .*L4"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('15') BLOCK PsiElement({)('{') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L4') PsiElement(})('}') PsiElement(})('}') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('L5') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('16') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L5') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid break label .*L5"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('17') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L5') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid continue label .*L5"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('18') BLOCK PsiElement({)('{') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L5') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('19') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') LABEL_REF PsiElement(identifier)('L1') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid break label .*L1"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('20') BLOCK PsiElement({)('{') CONTINUE_STATEMENT PsiElement(continue)('continue') LABEL_REF PsiElement(identifier)('L1') PsiComment(GO_LINE_COMMENT)('// ERROR "invalid continue label .*L1"') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('21') BLOCK PsiElement({)('{') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('L1') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/LiteralValues.go ================================================ // DO NOT EDIT. THIS IS FILE IS GENERATED AUTOMAGICALLY. ANY CHANGE WILL BE LOST. package cli import ( "bytes" "encoding/json" "errors" "fmt" "io" "net" "net/textproto" "strings" "sync/atomic" "text/template" ) type session struct { *textproto.Conn netConn net.Conn lineBuffer bytes.Buffer requestId uint32 sessionId uint32 outType int closed bool } type θ_parse_node struct { name string ident bool bindings []int action func(*session, []string) error doc string next []θ_parse_node } func (s *session) θ_echo(p []string) (err error) { ret := echo(p[0]) err = s.θ_writeResponse(ret, nil) if err != nil { return err } else { return s.θ_writeOk() } } func (s *session) θ_get_server_time(p []string) (err error) { ret := get_server_time() err = s.θ_writeResponse(ret, nil) if err != nil { return err } else { return s.θ_writeOk() } } func (s *session) θ_get_server_time(p []string) (err error) { ret := get_server_time() err = s.θ_writeResponse(ret, nil) if err != nil { return err } else { return s.θ_writeOk() } } func (s *session) θ_debug_ide(p []string) (err error) { p0, err := s.parse_number(p[0]) if err != nil { return s.θ_writeError(err) } ret := debug_ide(p0) err = s.θ_writeResponse(ret, nil) if err != nil { return err } else { return s.θ_writeOk() } } var θ_parse_tree = θ_parse_node{"", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"debug", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"idea", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"patience", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"for", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"tree", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"with", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"nested", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"level", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"more", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"than", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"", false, []int{0}, (*session).θ_debug_ide, "here goes an unnecessary long command", []θ_parse_node{}}}}}}}}}}}}}}}}}}}}}}, θ_parse_node{"echo", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"", false, []int{0}, (*session).θ_echo, "Returns its parameter", []θ_parse_node{}}}}, θ_parse_node{"get", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"output", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"type", true, []int{}, (*session).θ_get_output_type, "returns current output type", []θ_parse_node{}}}}, θ_parse_node{"server", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"time", true, []int{}, (*session).θ_get_server_time, "Returns server time", []θ_parse_node{}}}}}}, θ_parse_node{"quit", true, []int{}, (*session).θ_quit, "closes CLI connection", []θ_parse_node{}}, θ_parse_node{"set", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"output", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"type", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"to", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"", false, []int{0}, (*session).θ_set_output_type, "sets current output type (either json or text)", []θ_parse_node{}}}}}}}}}}, θ_parse_node{"show", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"server", true, []int{}, nil, "", []θ_parse_node{θ_parse_node{"time", true, []int{}, (*session).θ_get_server_time, "Returns server time", []θ_parse_node{}}}}}}}} type stru struct { Field string Field1 map[string]string } type str struct { Fiel *stru } func de() *stru { a := &stru{ Field: "demo", Field1: map[string]string{"f1": "val"}, } a.Field = "dem" a.Field1 = map[string]string{"f2": "val"} return a } func dem() { b := de() b.Field = "de" b.Field1 = map[string]string{"f3": "fal"} a := *str{ Fiel: &stru{ Field: fmt.Sprint("demo%d", 1), Field1: map[string]string{"a", "n"}, }, } for i := 0; i<4; i++ { a.Fiel = &stru{ Field: fmt.Sprintf("demo %d", i), // parser fails here Field1: map[string]string{ "a", "n", }, } } _ = b _ = a } ================================================ FILE: testData/parser/LiteralValues.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// DO NOT EDIT. THIS IS FILE IS GENERATED AUTOMAGICALLY. ANY CHANGE WILL BE LOST.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('cli') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') PsiElement(()('(') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"bytes"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"encoding/json"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"errors"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"io"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"net"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"net/textproto"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"strings"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"sync/atomic"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"text/template"') PsiElement())(')') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('session') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION ANONYMOUS_FIELD_DEFINITION POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('textproto') PsiElement(.)('.') PsiElement(identifier)('Conn') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('netConn') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('net') PsiElement(.)('.') PsiElement(identifier)('Conn') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('lineBuffer') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bytes') PsiElement(.)('.') PsiElement(identifier)('Buffer') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('requestId') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint32') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('sessionId') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint32') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('outType') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('closed') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('θ_parse_node') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('name') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('ident') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('bindings') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('action') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement(,)(',') PARAMETER_DECLARATION ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('doc') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('next') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('s') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(identifier)('θ_echo') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('p') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('ret') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('echo') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeResponse') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ret') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeOk') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('s') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(identifier)('θ_get_server_time') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('p') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('ret') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('get_server_time') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeResponse') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ret') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeOk') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('s') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(identifier)('θ_get_server_time') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('p') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('ret') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('get_server_time') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeResponse') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ret') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeOk') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('s') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(identifier)('θ_debug_ide') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('p') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('p0') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('parse_number') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeError') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('ret') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('debug_ide') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('p0') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeResponse') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ret') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('θ_writeOk') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('θ_parse_tree') PsiElement(=)('=') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"debug"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"idea"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"patience"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"for"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"tree"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"with"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"nested"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"level"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"more"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"than"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('false') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL PsiElement(int)('0') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_debug_ide') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"here goes an unnecessary long command"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"echo"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('false') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL PsiElement(int)('0') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_echo') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Returns its parameter"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"get"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"output"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"type"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_get_output_type') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"returns current output type"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"server"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"time"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_get_server_time') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Returns server time"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"quit"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_quit') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"closes CLI connection"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"set"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"output"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"type"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"to"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('false') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE LITERAL PsiElement(int)('0') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_set_output_type') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"sets current output type (either json or text)"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"show"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"server"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"time"') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') ELEMENT VALUE SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('session') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('θ_get_server_time') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Returns server time"') PsiElement(,)(',') ELEMENT VALUE COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('θ_parse_node') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('stru') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Field') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Field1') MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('str') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Fiel') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stru') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('de') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stru') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stru') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"demo"') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field1') PsiElement(:)(':') VALUE COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY STRING_LITERAL PsiElement(string)('"f1"') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"val"') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(.)('.') PsiElement(identifier)('Field') ASSIGN_OP PsiElement(=)('=') STRING_LITERAL PsiElement(string)('"dem"') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(.)('.') PsiElement(identifier)('Field1') ASSIGN_OP PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY STRING_LITERAL PsiElement(string)('"f2"') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"val"') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('dem') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('b') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('de') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(.)('.') PsiElement(identifier)('Field') ASSIGN_OP PsiElement(=)('=') STRING_LITERAL PsiElement(string)('"de"') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(.)('.') PsiElement(identifier)('Field1') ASSIGN_OP PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY STRING_LITERAL PsiElement(string)('"f3"') PsiElement(:)(':') VALUE STRING_LITERAL PsiElement(string)('"fal"') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') UNARY_EXPR PsiElement(*)('*') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('str') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Fiel') PsiElement(:)(':') VALUE UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stru') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field') PsiElement(:)(':') VALUE CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Sprint') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"demo%d"') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field1') PsiElement(:)(':') VALUE COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"a"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"n"') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') LITERAL PsiElement(int)('0') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<)('<') LITERAL PsiElement(int)('4') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(++)('++') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(.)('.') PsiElement(identifier)('Fiel') ASSIGN_OP PsiElement(=)('=') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('stru') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field') PsiElement(:)(':') VALUE CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Sprintf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"demo %d"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(,)(',') PsiComment(GO_LINE_COMMENT)('// parser fails here') ELEMENT KEY FIELD_NAME PsiElement(identifier)('Field1') PsiElement(:)(':') VALUE COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"a"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"n"') PsiElement(,)(',') PsiElement(})('}') PsiElement(,)(',') PsiElement(})('}') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('b') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(})('}') ================================================ FILE: testData/parser/LiteralValuesElse.go ================================================ package main import ( "fmt" ) func main() { s := struct{ Username, Password string }{ "User", "Password", } if s != struct{ Username, Password string }{} { fmt.Println("yes") } else { fmt.Println("yes") } } ================================================ FILE: testData/parser/LiteralValuesElse.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') PsiElement(()('(') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('s') PsiElement(:=)(':=') COMPOSITE_LIT STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Username') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('Password') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"User"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Password"') PsiElement(,)(',') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(!=)('!=') COMPOSITE_LIT STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Username') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('Password') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"yes"') PsiElement())(')') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"yes"') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/MapLiteralRecover.go ================================================ package main func main() { _ := []string a := []string{} println(a) } ================================================ FILE: testData/parser/MapLiteralRecover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('_') PsiElement(:=)(':=') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiErrorElement:'(', '.' or '{' expected, got '' SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('println') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/MethodExpr.go ================================================ package test type T struct { a int } func (tv T) Mv(a int) int { return 0 } // value receiver func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver var t T func bar() { t.Mv(7) T.Mv(t, 7) (T).Mv(t, 7) f1 := T.Mv; f1(t, 7) f2 := (T).Mv; f2(t, 7) } ================================================ FILE: testData/parser/MethodExpr.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('test') IMPORT_LIST TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('a') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tv') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(identifier)('Mv') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') LITERAL PsiElement(int)('0') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// value receiver') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tp') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(identifier)('Mp') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('f') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float32') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float32') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') LITERAL PsiElement(int)('1') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// pointer receiver') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('t') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('bar') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(.)('.') PsiElement(identifier)('Mv') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('7') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement(.)('.') PsiElement(identifier)('Mv') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Mv') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('f1') PsiElement(:=)(':=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement(.)('.') PsiElement(identifier)('Mv') PsiElement(;)(';') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f1') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('f2') PsiElement(:=)(':=') SELECTOR_EXPR PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Mv') PsiElement(;)(';') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f2') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/MethodWithoutReceiverIdentifier.go ================================================ package main func (ConstraintViolationError) Error() string { return "x509: invalid signature: parent certificate cannot sign this kind of certificate" } func (ds *dasa,) yooolo(dsa dasa) { *ds = dsa } ================================================ FILE: testData/parser/MethodWithoutReceiverIdentifier.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('ConstraintViolationError') PsiElement())(')') PsiElement(identifier)('Error') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') STRING_LITERAL PsiElement(string)('"x509: invalid signature: parent certificate cannot sign this kind of certificate"') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('ds') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('dasa') PsiElement(,)(',') PsiElement())(')') PsiElement(identifier)('yooolo') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('dsa') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('dasa') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('ds') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('dsa') PsiElement(})('}') ================================================ FILE: testData/parser/PlusPlusRecover.go ================================================ package main func main() { i := 0 i //error &i //error /i //error /=i //error ^i //error i //error >>i //error ...i //error !i //error !=i //error %i //error &&i //error &=i //error &^i //error &^=i //error +=i //error --i //error ++i //error Println() } ================================================ FILE: testData/parser/PlusPlusRecover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') LITERAL PsiElement(int)('0') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'/' unexpected PsiElement(/)('/') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'/=' unexpected PsiElement(/=)('/=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(^)('^') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'<' unexpected PsiElement(<)('<') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'<<' unexpected PsiElement(<<)('<<') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'=' unexpected PsiElement(=)('=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'==' unexpected PsiElement(==)('==') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'>' unexpected PsiElement(>)('>') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'>>' unexpected PsiElement(>>)('>>') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'...' unexpected PsiElement(...)('...') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(!)('!') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'!=' unexpected PsiElement(!=)('!=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'%' unexpected PsiElement(%)('%') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'&&' unexpected PsiElement(&&)('&&') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'&=' unexpected PsiElement(&=)('&=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'&^' unexpected PsiElement(&^)('&^') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'&^=' unexpected PsiElement(&^=)('&^=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'+=' unexpected PsiElement(+=)('+=') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'--' unexpected PsiElement(--)('--') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') PsiErrorElement:'++' unexpected PsiElement(++)('++') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiComment(GO_LINE_COMMENT)('//error') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/Primer.go ================================================ package main import "fmt" func printf(str string, args ...interface{}) (int, error) { _, err := fmt.Printf(str, args...) return len(args), err } func main() { count := 1 closure := func(msg string) { printf("%d %s\n", count, msg) count++ } closure("A Message") closure("Another Message") } func main2() { loops := 1 // while loop: for loops > 0 { fmt.Printf("\nNumber of loops?\n") fmt.Scanf("%d", &loops) // for loop for i := 0 ; i < loops ; i++ { fmt.Printf("%d ", i) } } // Infinite loop for { // Explicitly terminated break } } const ( Red = (1<)('>') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"\nNumber of loops?\n"') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Scanf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d"') PsiElement(,)(',') UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('loops') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// for loop') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') LITERAL PsiElement(int)('0') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<)('<') REFERENCE_EXPRESSION PsiElement(identifier)('loops') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(++)('++') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d "') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Infinite loop') FOR_STATEMENT PsiElement(for)('for') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// Explicitly terminated') BREAK_STATEMENT PsiElement(break)('break') PsiElement(})('}') PsiElement(})('}') CONST_DECLARATION PsiElement(const)('const') PsiElement(()('(') CONST_SPEC CONST_DEFINITION PsiElement(identifier)('Red') PsiElement(=)('=') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR LITERAL PsiElement(int)('1') PsiElement(<<)('<<') REFERENCE_EXPRESSION PsiElement(identifier)('iota') PsiElement())(')') CONST_SPEC CONST_DEFINITION PsiElement(identifier)('Green') PsiElement(=)('=') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR LITERAL PsiElement(int)('1') PsiElement(<<)('<<') REFERENCE_EXPRESSION PsiElement(identifier)('iota') PsiElement())(')') CONST_SPEC CONST_DEFINITION PsiElement(identifier)('Blue') PsiElement(,)(',') CONST_DEFINITION PsiElement(identifier)('ColorMask') PsiElement(=)('=') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR LITERAL PsiElement(int)('1') PsiElement(<<)('<<') REFERENCE_EXPRESSION PsiElement(identifier)('iota') PsiElement())(')') PsiElement(,)(',') ADD_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR LITERAL PsiElement(int)('1') PsiElement(<<)('<<') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('iota') PsiElement(+)('+') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement())(')') PsiElement(-)('-') LITERAL PsiElement(int)('1') PsiElement())(')') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Example') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Val') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('count') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('integer') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('i') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('integer') PsiElement())(')') PsiElement(identifier)('log') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d\n"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(;)(';') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('e') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Example') PsiElement())(')') PsiElement(identifier)('Log') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') INC_DEC_STATEMENT REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('count') PsiElement(++)('++') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d %s\n"') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('count') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('e') PsiElement(.)('.') PsiElement(identifier)('Val') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('cartesianPoint') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('x') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('y') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('polarPoint') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('r') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('θ') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('p') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('cartesianPoint') PsiElement())(')') PsiElement(identifier)('X') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('x') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('p') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('cartesianPoint') PsiElement())(')') PsiElement(identifier)('Y') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('y') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('p') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('polarPoint') PsiElement())(')') PsiElement(identifier)('X') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('r') PsiElement(*)('*') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('math') PsiElement(.)('.') PsiElement(identifier)('Cos') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('θ') PsiElement())(')') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('p') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('polarPoint') PsiElement())(')') PsiElement(identifier)('Y') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('r') PsiElement(*)('*') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('math') PsiElement(.)('.') PsiElement(identifier)('Sin') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement(.)('.') PsiElement(identifier)('θ') PsiElement())(')') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('self') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('cartesianPoint') PsiElement())(')') PsiElement(identifier)('Print') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"(%f, %f)\n"') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('self') PsiElement(.)('.') PsiElement(identifier)('x') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('self') PsiElement(.)('.') PsiElement(identifier)('y') PsiElement())(')') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('self') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('polarPoint') PsiElement())(')') PsiElement(identifier)('Print') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"(%f, %f ◦ )\n"') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('self') PsiElement(.)('.') PsiElement(identifier)('r') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('self') PsiElement(.)('.') PsiElement(identifier)('θ') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Point') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') METHOD_SPEC TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Printer') METHOD_SPEC PsiElement(identifier)('X') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') METHOD_SPEC PsiElement(identifier)('Y') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Printer') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') METHOD_SPEC PsiElement(identifier)('Print') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/Ranges.go ================================================ package ff func main() { for range x { } for _ := range x { } for k, v := range x { } } ================================================ FILE: testData/parser/Ranges.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('ff') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE PsiElement(range)('range') REFERENCE_EXPRESSION PsiElement(identifier)('x') BLOCK PsiElement({)('{') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('_') PsiElement(:=)(':=') PsiElement(range)('range') REFERENCE_EXPRESSION PsiElement(identifier)('x') BLOCK PsiElement({)('{') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('k') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('v') PsiElement(:=)(':=') PsiElement(range)('range') REFERENCE_EXPRESSION PsiElement(identifier)('x') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/Recover.go ================================================ package main func main() { } aa type T struct {} bb var cc interface{} ccc const aa int=1 func main() { type aa interface { } b := 0 var a = b.(type) _ = a fmt.Println(b) } ================================================ FILE: testData/parser/Recover.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') PsiErrorElement:'aa' unexpected PsiElement(identifier)('aa') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') PsiElement(})('}') PsiErrorElement:'bb' unexpected PsiElement(identifier)('bb') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('cc') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiErrorElement:'ccc' unexpected PsiElement(identifier)('ccc') CONST_DECLARATION PsiElement(const)('const') CONST_SPEC CONST_DEFINITION PsiElement(identifier)('aa') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(=)('=') LITERAL PsiElement(int)('1') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('aa') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('b') PsiElement(:=)(':=') LITERAL PsiElement(int)('0') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('a') PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(.)('.') PsiErrorElement:'(' or identifier expected, got '(' SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST PARENTHESES_EXPR PsiElement(()('(') PsiErrorElement:'!=', '%', '&', '&^', '(', ')', '*', '+', '++', '-', '--', '/', <, <-, <<, <=, , '==', '>', '>=', '>>', '[', '^', chan, func, interface, map, struct or '|' expected, got 'type' STATEMENT TYPE_DECLARATION PsiElement(type)('type') PsiErrorElement:'(' or identifier expected, got ')' PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('a') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/Recover2.go ================================================ package http func labelsCheck() { goto Label1; Label1: 1; goto Label2} func serve() { foo( if 1 {} } func foo() { bar(,) doo() } func main() { switch expr { case } } func _() { []string } func User(createBase base.AuthFunc) base.Ajaxer { log.Println("Restful user request.") authCtrl := createBase("controller/account/user") switch authCtrl.Req.Method { case "PUT": return &edit{AuthCtrl: authCtrl} "DELETE": return &delete{AuthCtrl: authCtrl} default: return &read{AuthCtrl: authCtrl} } } func User(createBase base.AuthFunc) base.Ajaxer { log.Println("Restful user request.") authCtrl := createBase("controller/account/user") switch authCtrl.Req.Method { "PUT": return &edit{AuthCtrl: authCtrl} "DELETE": return &delete{AuthCtrl: authCtrl} default: return &read{AuthCtrl: authCtrl} } } ================================================ FILE: testData/parser/Recover2.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('http') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('labelsCheck') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('Label1') PsiElement(;)(';') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('Label1') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST LITERAL PsiElement(int)('1') PsiElement(;)(';') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('Label2') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('serve') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('foo') ARGUMENT_LIST PsiElement(()('(') PsiErrorElement:'!=', '%', '&', '&^', '(', ')', '*', '+', '++', '-', '--', '/', <, <<, <=, , , '==', '>', '>=', '>>', '^' or '|' expected, got 'if' IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST LITERAL PsiElement(int)('1') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('foo') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('bar') ARGUMENT_LIST PsiElement(()('(') PsiErrorElement:'!=', '%', '&', '&^', '(', ')', '*', '+', '++', '-', '--', '/', <, <<, <=, , , '==', '>', '>=', '>>', '^' or '|' expected, got ',' PsiElement(,)(',') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('doo') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('expr') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(case)('case') PsiErrorElement: expected, got '}' PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('_') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiErrorElement:'!=', '%', '&', '&^', '(', '*', '+', '++', '-', '--', '.', '/', <, <<, <=, '==', '>', '>=', '>>', '^', '{' or '|' expected, got '' PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('User') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('createBase') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('base') PsiElement(.)('.') PsiElement(identifier)('AuthFunc') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('base') PsiElement(.)('.') PsiElement(identifier)('Ajaxer') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('log') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Restful user request."') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('authCtrl') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('createBase') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"controller/account/user"') PsiElement())(')') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(.)('.') PsiElement(identifier)('Req') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Method') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(case)('case') STRING_LITERAL PsiElement(string)('"PUT"') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('edit') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST STRING_LITERAL PsiElement(string)('"DELETE"') PsiErrorElement:',', ';', <-, , or '}' expected, got ':' PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('delete') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('read') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('User') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('createBase') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('base') PsiElement(.)('.') PsiElement(identifier)('AuthFunc') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('base') PsiElement(.)('.') PsiElement(identifier)('Ajaxer') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('log') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Restful user request."') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('authCtrl') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('createBase') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"controller/account/user"') PsiElement())(')') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(.)('.') PsiElement(identifier)('Req') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Method') PsiElement({)('{') EXPR_CASE_CLAUSE PsiErrorElement:case or default expected, got '"PUT"' SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST STRING_LITERAL PsiElement(string)('"PUT"') PsiErrorElement:',', ';', <-, , or '}' expected, got ':' PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('edit') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST STRING_LITERAL PsiElement(string)('"DELETE"') PsiErrorElement:',', ';', <-, , or '}' expected, got ':' PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('delete') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('read') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('AuthCtrl') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('authCtrl') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/Recover3.go ================================================ package main fooo func func example() { } foo func ex ================================================ FILE: testData/parser/Recover3.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST PsiErrorElement:const, func, import, type or var expected, got 'fooo' PsiElement(identifier)('fooo') METHOD_DECLARATION PsiElement(func)('func') PsiErrorElement:'(' or identifier expected, got 'func' FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('example') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') PsiErrorElement:'foo' unexpected PsiElement(identifier)('foo') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ex') PsiErrorElement:'(' expected, unexpected end of file ================================================ FILE: testData/parser/Simple.go ================================================ package foo func NewCipher(key []byte) (cipher.Block , error) { return c, nil } func simpleF() int { return 2 } func complexF1() (re float64, im float64) { return -7.0, -4.0 } func test() { switch tag { default: s3() case 0, 1, 2, 3: s1() case 4, 5, 6, 7: s2() } switch x := f(); { // missing switch expression means "true" case x < 0: return -x default: return x } switch x := f(); 1==1 { // missing switch expression means "true" case x < 0: return -x default: return x } switch { case x < y: f1() case x < z: f2() case x == 4: f3() } } func emptyFor() { for s.accept(decimalDigits) { } } func emptyIf() { if err := q.Send(&Cmd{U: parsed, M: method}); err != nil { } } func emptyForRange() { for key, value := range collection { } } func emptyClauses() { verb := "1"[0] switch verb { case 'p': default: } } func (h extraHeader) Write(w io.Writer) { for i, v := range []string{h.contentType, h.contentLength, h.connection, h.date, h.transferEncoding} { if v != "" { w.Write(extraHeaderKeys[i]) w.Write(colonSpace) io.WriteString(w, v) w.Write(crlf) } } } func main() { if 1 != 1 { } select { case ce := <-ch: return ce.cn, ce.err case <-time.After(c.netTimeout()): // Too slow. Fall through. } } var days = [...]string{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", } var htmlReplacer = strings.NewReplacer( "&", "&", "<", "<", ">", ">", // """ is shorter than """. `"`, """, // "'" is shorter than "'" and apos was not in HTML until HTML5. "'", "'", ) func tets() { v = v.assignTo("reflect.Value.Call", targ, (*interface{})(addr)) type test interface {} t := new(test) v := (interface{})(t) } func (*ctx) Errorf(string, ...interface{}) {} var alreadyAddedErrors = map[pb.TaskQueueServiceError_ErrorCode]bool{ pb.TaskQueueServiceError_TASK_ALREADY_EXISTS: true, } var alreadyAddedErrors2 = map[pb.TaskQueueServiceError_ErrorCode]bool{ pb.TaskQueueServiceError_TASK_ALREADY_EXISTS: true, pb.TaskQueueServiceError_TOMBSTONED_TASK: true, } var a = []byte(b.Type + "-----\n") var b = map[string]int{ "", } func foo() { func () { }() } func hello( id string, ) error { return nil } func hello( id string, ) error { return nil } func sourceReader(files <-chan *File) { for _, page := range []*File{} { if page.Contents == "" { break } } } func sourceReader1() { for _, page := range []*File{} { } } func sourceReader1() { for _, page := range *File{} { // error as expected } } func main() { a := []byte{} b := append( []byte("demo"), a..., // example fails here ) _ = b } func main() { for a:= 1; a<10; a++ { goto err } err: } func main() { if err := foo(demo{}); err!= nil { panic(err) } if err := (demo{}); err!= nil { panic(err) } for b, i := M{}, 10; i < 10; i++ { // error fmt.Println(v) } for b, i := (M{}), 10; i < 10; i++ { fmt.Println(v) } } type name struct { foo string `xml:""` } func TestFor() { type name1234 interface { } var v []int call(func() { for range v { // v is not resolved here } }) } func TestIf() { var v string call(func() { if v == "" { } if "" == v { // v is not resolved here } }) } func call(f func()) { f() } type SensorFactory struct { Sensors map[string]string } func InitSensorFactory() *SensorFactory { factory := new (SensorFactory) factory.Sensors = make(map[string]string) return factory } ================================================ FILE: testData/parser/Simple.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('foo') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('NewCipher') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('key') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement())(')') RESULT PsiElement(()('(') TYPE_LIST TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('cipher') PsiElement(.)('.') PsiElement(identifier)('Block') PsiElement(,)(',') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('simpleF') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') LITERAL PsiElement(int)('2') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('complexF1') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('re') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('im') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement())(')') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(-)('-') LITERAL PsiElement(float)('7.0') PsiElement(,)(',') UNARY_EXPR PsiElement(-)('-') LITERAL PsiElement(float)('4.0') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('test') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('tag') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s3') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') EXPR_CASE_CLAUSE PsiElement(case)('case') LITERAL PsiElement(int)('0') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement(,)(',') LITERAL PsiElement(int)('2') PsiElement(,)(',') LITERAL PsiElement(int)('3') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s1') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') EXPR_CASE_CLAUSE PsiElement(case)('case') LITERAL PsiElement(int)('4') PsiElement(,)(',') LITERAL PsiElement(int)('5') PsiElement(,)(',') LITERAL PsiElement(int)('6') PsiElement(,)(',') LITERAL PsiElement(int)('7') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s2') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('x') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(;)(';') PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// missing switch expression means "true"') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(<)('<') LITERAL PsiElement(int)('0') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(-)('-') REFERENCE_EXPRESSION PsiElement(identifier)('x') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(})('}') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('x') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR LITERAL PsiElement(int)('1') PsiElement(==)('==') LITERAL PsiElement(int)('1') PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// missing switch expression means "true"') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(<)('<') LITERAL PsiElement(int)('0') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(-)('-') REFERENCE_EXPRESSION PsiElement(identifier)('x') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(})('}') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(<)('<') REFERENCE_EXPRESSION PsiElement(identifier)('y') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f1') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(<)('<') REFERENCE_EXPRESSION PsiElement(identifier)('z') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f2') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') EXPR_CASE_CLAUSE PsiElement(case)('case') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(==)('==') LITERAL PsiElement(int)('4') PsiElement(:)(':') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f3') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('emptyFor') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('accept') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('decimalDigits') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('emptyIf') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('q') PsiElement(.)('.') PsiElement(identifier)('Send') ARGUMENT_LIST PsiElement(()('(') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Cmd') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('U') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('parsed') PsiElement(,)(',') ELEMENT KEY FIELD_NAME PsiElement(identifier)('M') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('method') PsiElement(})('}') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('emptyForRange') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('key') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('value') PsiElement(:=)(':=') PsiElement(range)('range') REFERENCE_EXPRESSION PsiElement(identifier)('collection') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('emptyClauses') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('verb') PsiElement(:=)(':=') INDEX_OR_SLICE_EXPR STRING_LITERAL PsiElement(string)('"1"') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') EXPR_SWITCH_STATEMENT SWITCH_START PsiElement(switch)('switch') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('verb') PsiElement({)('{') EXPR_CASE_CLAUSE PsiElement(case)('case') LITERAL PsiElement(char)(''p'') PsiElement(:)(':') EXPR_CASE_CLAUSE PsiElement(default)('default') PsiElement(:)(':') PsiElement(})('}') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('h') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('extraHeader') PsiElement())(')') PsiElement(identifier)('Write') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('w') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('io') PsiElement(.)('.') PsiElement(identifier)('Writer') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('i') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('v') PsiElement(:=)(':=') PsiElement(range)('range') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(.)('.') PsiElement(identifier)('contentType') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(.)('.') PsiElement(identifier)('contentLength') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(.)('.') PsiElement(identifier)('connection') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(.)('.') PsiElement(identifier)('date') PsiElement(,)(',') ELEMENT VALUE REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('h') PsiElement(.)('.') PsiElement(identifier)('transferEncoding') PsiElement(})('}') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement(!=)('!=') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('w') PsiElement(.)('.') PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('extraHeaderKeys') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('w') PsiElement(.)('.') PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('colonSpace') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('io') PsiElement(.)('.') PsiElement(identifier)('WriteString') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('w') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('w') PsiElement(.)('.') PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('crlf') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR LITERAL PsiElement(int)('1') PsiElement(!=)('!=') LITERAL PsiElement(int)('1') BLOCK PsiElement({)('{') PsiElement(})('}') SELECT_STATEMENT PsiElement(select)('select') PsiElement({)('{') COMM_CLAUSE COMM_CASE PsiElement(case)('case') RECV_STATEMENT VAR_DEFINITION PsiElement(identifier)('ce') PsiElement(:=)(':=') UNARY_EXPR PsiElement(<-)('<-') REFERENCE_EXPRESSION PsiElement(identifier)('ch') PsiElement(:)(':') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ce') PsiElement(.)('.') PsiElement(identifier)('cn') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ce') PsiElement(.)('.') PsiElement(identifier)('err') COMM_CLAUSE COMM_CASE PsiElement(case)('case') RECV_STATEMENT UNARY_EXPR PsiElement(<-)('<-') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('time') PsiElement(.)('.') PsiElement(identifier)('After') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(.)('.') PsiElement(identifier)('netTimeout') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiElement(:)(':') PsiComment(GO_LINE_COMMENT)('// Too slow. Fall through.') PsiElement(})('}') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('days') PsiElement(=)('=') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(...)('...') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Sunday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Monday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Tuesday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Wednesday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Thursday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Friday"') PsiElement(,)(',') ELEMENT VALUE STRING_LITERAL PsiElement(string)('"Saturday"') PsiElement(,)(',') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('htmlReplacer') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strings') PsiElement(.)('.') PsiElement(identifier)('NewReplacer') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"&"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"&"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"<"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"<"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('">"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('">"') PsiElement(,)(',') PsiComment(GO_LINE_COMMENT)('// """ is shorter than """.') STRING_LITERAL PsiElement(raw_string)('`"`') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"""') PsiElement(,)(',') PsiComment(GO_LINE_COMMENT)('// "'" is shorter than "'" and apos was not in HTML until HTML5.') STRING_LITERAL PsiElement(string)('"'"') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"'"') PsiElement(,)(',') PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('tets') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('v') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement(.)('.') PsiElement(identifier)('assignTo') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"reflect.Value.Call"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('targ') PsiElement(,)(',') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('addr') PsiElement())(')') PsiElement())(')') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('test') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('t') PsiElement(:=)(':=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('new') BUILTIN_ARGUMENT_LIST PsiElement(()('(') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('test') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('v') PsiElement(:=)(':=') CONVERSION_EXPR PAR_TYPE PsiElement(()('(') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement())(')') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('ctx') PsiElement())(')') PsiElement(identifier)('Errorf') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PARAMETER_DECLARATION PsiElement(...)('...') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('alreadyAddedErrors') PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('pb') PsiElement(.)('.') PsiElement(identifier)('TaskQueueServiceError_ErrorCode') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('pb') PsiElement(.)('.') PsiElement(identifier)('TaskQueueServiceError_TASK_ALREADY_EXISTS') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('alreadyAddedErrors2') PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('pb') PsiElement(.)('.') PsiElement(identifier)('TaskQueueServiceError_ErrorCode') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('pb') PsiElement(.)('.') PsiElement(identifier)('TaskQueueServiceError_TASK_ALREADY_EXISTS') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') ELEMENT KEY REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('pb') PsiElement(.)('.') PsiElement(identifier)('TaskQueueServiceError_TOMBSTONED_TASK') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(,)(',') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('a') PsiElement(=)('=') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') ADD_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(.)('.') PsiElement(identifier)('Type') PsiElement(+)('+') STRING_LITERAL PsiElement(string)('"-----\n"') PsiElement())(')') VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('b') PsiElement(=)('=') COMPOSITE_LIT MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') LITERAL_VALUE PsiElement({)('{') ELEMENT VALUE STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('foo') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(})('}') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('hello') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('id') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('hello') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('id') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('sourceReader') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('files') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('File') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('_') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('page') PsiElement(:=)(':=') PsiElement(range)('range') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('File') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('page') PsiElement(.)('.') PsiElement(identifier)('Contents') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') PsiElement(})('}') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('sourceReader1') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('_') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('page') PsiElement(:=)(':=') PsiElement(range)('range') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('File') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('sourceReader1') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('_') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('page') PsiElement(:=)(':=') PsiElement(range)('range') UNARY_EXPR PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('File') BLOCK PsiElement({)('{') PsiElement(})('}') PsiErrorElement:';', or '}' expected, got '{' STATEMENT BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// error as expected') PsiElement(})('}') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') COMPOSITE_LIT ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('b') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('append') ARGUMENT_LIST PsiElement(()('(') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') STRING_LITERAL PsiElement(string)('"demo"') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(...)('...') PsiElement(,)(',') PsiComment(GO_LINE_COMMENT)('// example fails here') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('a') PsiElement(:=)(':=') LITERAL PsiElement(int)('1') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(<)('<') LITERAL PsiElement(int)('10') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(++)('++') BLOCK PsiElement({)('{') GOTO_STATEMENT PsiElement(goto)('goto') LABEL_REF PsiElement(identifier)('err') PsiElement(})('}') LABELED_STATEMENT LABEL_DEFINITION PsiElement(identifier)('err') PsiElement(:)(':') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('foo') ARGUMENT_LIST PsiElement(()('(') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('demo') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') PARENTHESES_EXPR PsiElement(()('(') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('demo') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('panic') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement())(')') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE VAR_DEFINITION PsiElement(identifier)('b') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') PsiErrorElement:',', '=' or range expected, got 'M' REFERENCE_EXPRESSION PsiElement(identifier)('M') BLOCK PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST LITERAL PsiElement(int)('10') PsiElement(;)(';') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<)('<') LITERAL PsiElement(int)('10') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(++)('++') PsiErrorElement:';', or '}' expected, got '{' STATEMENT BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// error') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement())(')') PsiElement(})('}') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('b') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') PARENTHESES_EXPR PsiElement(()('(') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('M') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement())(')') PsiElement(,)(',') LITERAL PsiElement(int)('10') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<)('<') LITERAL PsiElement(int)('10') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(++)('++') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement())(')') PsiElement(})('}') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('name') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('foo') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') TAG STRING_LITERAL PsiElement(raw_string)('`xml:""`') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('TestFor') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('name1234') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('v') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('call') ARGUMENT_LIST PsiElement(()('(') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') FOR_STATEMENT PsiElement(for)('for') RANGE_CLAUSE PsiElement(range)('range') REFERENCE_EXPRESSION PsiElement(identifier)('v') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// v is not resolved here') PsiElement(})('}') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('TestIf') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('v') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('call') ARGUMENT_LIST PsiElement(()('(') FUNCTION_LIT PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('v') PsiElement(==)('==') STRING_LITERAL PsiElement(string)('""') BLOCK PsiElement({)('{') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR STRING_LITERAL PsiElement(string)('""') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('v') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// v is not resolved here') PsiElement(})('}') PsiElement(})('}') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('call') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('f') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('SensorFactory') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Sensors') MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('InitSensorFactory') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('SensorFactory') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('factory') PsiElement(:=)(':=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('new') BUILTIN_ARGUMENT_LIST PsiElement(()('(') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('SensorFactory') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('factory') PsiElement(.)('.') PsiElement(identifier)('Sensors') ASSIGN_OP PsiElement(=)('=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') MAP_TYPE PsiElement(map)('map') PsiElement([)('[') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('factory') PsiElement(})('}') ================================================ FILE: testData/parser/Str2Num.go ================================================ package main import "fmt" import "strconv" func main() { p := fmt.Printf ((fmt.Printf))("Hello\n", 1) (fmt.Printf)("Hello\n", 1) p("Hello\n", 1) j := interface{}(1) if (false) {p("", j); return } var i int f := ((fmt.Scanf)) f("%d", &i) str := strconv.FormatInt(int64(i), 10) hex, _ := strconv.ParseInt(str, 16, 64) fmt.Printf("%d\n", hex) } ================================================ FILE: testData/parser/Str2Num.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') IMPORT_DECLARATION PsiElement(import)('import') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"strconv"') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('p') PsiElement(:=)(':=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR PARENTHESES_EXPR PsiElement(()('(') PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') PsiElement())(')') PsiElement())(')') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hello\n"') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') PsiElement())(')') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hello\n"') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('p') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"Hello\n"') PsiElement(,)(',') LITERAL PsiElement(int)('1') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('j') PsiElement(:=)(':=') CONVERSION_EXPR INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement(()('(') LITERAL PsiElement(int)('1') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('false') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('p') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('""') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('j') PsiElement())(')') PsiElement(;)(';') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('i') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('f') PsiElement(:=)(':=') PARENTHESES_EXPR PsiElement(()('(') PARENTHESES_EXPR PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Scanf') PsiElement())(')') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('f') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d"') PsiElement(,)(',') UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('str') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strconv') PsiElement(.)('.') PsiElement(identifier)('FormatInt') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement())(')') PsiElement(,)(',') LITERAL PsiElement(int)('10') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('hex') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('_') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strconv') PsiElement(.)('.') PsiElement(identifier)('ParseInt') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('str') PsiElement(,)(',') LITERAL PsiElement(int)('16') PsiElement(,)(',') LITERAL PsiElement(int)('64') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Printf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d\n"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('hex') PsiElement())(')') PsiElement(})('}') ================================================ FILE: testData/parser/Torture.go ================================================ // compile // Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Various tests for expressions with high complexity. package main // Concatenate 16 4-bit integers into a 64-bit number. func concat(s *[16]byte) uint64 { r := (((((((((((((((uint64(s[0])<<4| uint64(s[1]))<<4| uint64(s[2]))<<4| uint64(s[3]))<<4| uint64(s[4]))<<4| uint64(s[5]))<<4| uint64(s[6]))<<4| uint64(s[7]))<<4| uint64(s[8]))<<4| uint64(s[9]))<<4| uint64(s[10]))<<4| uint64(s[11]))<<4| uint64(s[12]))<<4| uint64(s[13]))<<4| uint64(s[14]))<<4 | uint64(s[15])) return r } // Compute the determinant of a 4x4-matrix by the sum // over all index permutations. func determinant(m [4][4]float64) float64 { return m[0][0]*m[1][1]*m[2][2]*m[3][3] - m[0][0]*m[1][1]*m[2][3]*m[3][2] - m[0][0]*m[1][2]*m[2][1]*m[3][3] + m[0][0]*m[1][2]*m[2][3]*m[3][1] + m[0][0]*m[1][3]*m[2][1]*m[3][2] - m[0][0]*m[1][3]*m[2][2]*m[3][1] - m[0][1]*m[1][0]*m[2][2]*m[3][3] + m[0][1]*m[1][0]*m[2][3]*m[3][2] + m[0][1]*m[1][2]*m[2][0]*m[3][3] - m[0][1]*m[1][2]*m[2][3]*m[3][0] - m[0][1]*m[1][3]*m[2][0]*m[3][2] + m[0][1]*m[1][3]*m[2][2]*m[3][0] + m[0][2]*m[1][0]*m[2][1]*m[3][3] - m[0][2]*m[1][0]*m[2][3]*m[3][1] - m[0][2]*m[1][1]*m[2][0]*m[3][3] + m[0][2]*m[1][1]*m[2][3]*m[3][0] + m[0][2]*m[1][3]*m[2][0]*m[3][1] - m[0][2]*m[1][3]*m[2][1]*m[3][0] - m[0][3]*m[1][0]*m[2][1]*m[3][2] + m[0][3]*m[1][0]*m[2][2]*m[3][1] + m[0][3]*m[1][1]*m[2][0]*m[3][2] - m[0][3]*m[1][1]*m[2][2]*m[3][0] - m[0][3]*m[1][2]*m[2][0]*m[3][1] + m[0][3]*m[1][2]*m[2][1]*m[3][0] } // Compute the determinant of a 4x4-matrix by the sum // over all index permutations. func determinantInt(m [4][4]int) int { return m[0][0]*m[1][1]*m[2][2]*m[3][3] - m[0][0]*m[1][1]*m[2][3]*m[3][2] - m[0][0]*m[1][2]*m[2][1]*m[3][3] + m[0][0]*m[1][2]*m[2][3]*m[3][1] + m[0][0]*m[1][3]*m[2][1]*m[3][2] - m[0][0]*m[1][3]*m[2][2]*m[3][1] - m[0][1]*m[1][0]*m[2][2]*m[3][3] + m[0][1]*m[1][0]*m[2][3]*m[3][2] + m[0][1]*m[1][2]*m[2][0]*m[3][3] - m[0][1]*m[1][2]*m[2][3]*m[3][0] - m[0][1]*m[1][3]*m[2][0]*m[3][2] + m[0][1]*m[1][3]*m[2][2]*m[3][0] + m[0][2]*m[1][0]*m[2][1]*m[3][3] - m[0][2]*m[1][0]*m[2][3]*m[3][1] - m[0][2]*m[1][1]*m[2][0]*m[3][3] + m[0][2]*m[1][1]*m[2][3]*m[3][0] + m[0][2]*m[1][3]*m[2][0]*m[3][1] - m[0][2]*m[1][3]*m[2][1]*m[3][0] - m[0][3]*m[1][0]*m[2][1]*m[3][2] + m[0][3]*m[1][0]*m[2][2]*m[3][1] + m[0][3]*m[1][1]*m[2][0]*m[3][2] - m[0][3]*m[1][1]*m[2][2]*m[3][0] - m[0][3]*m[1][2]*m[2][0]*m[3][1] + m[0][3]*m[1][2]*m[2][1]*m[3][0] } // Compute the determinant of a 4x4-matrix by the sum // over all index permutations. func determinantByte(m [4][4]byte) byte { return m[0][0]*m[1][1]*m[2][2]*m[3][3] - m[0][0]*m[1][1]*m[2][3]*m[3][2] - m[0][0]*m[1][2]*m[2][1]*m[3][3] + m[0][0]*m[1][2]*m[2][3]*m[3][1] + m[0][0]*m[1][3]*m[2][1]*m[3][2] - m[0][0]*m[1][3]*m[2][2]*m[3][1] - m[0][1]*m[1][0]*m[2][2]*m[3][3] + m[0][1]*m[1][0]*m[2][3]*m[3][2] + m[0][1]*m[1][2]*m[2][0]*m[3][3] - m[0][1]*m[1][2]*m[2][3]*m[3][0] - m[0][1]*m[1][3]*m[2][0]*m[3][2] + m[0][1]*m[1][3]*m[2][2]*m[3][0] + m[0][2]*m[1][0]*m[2][1]*m[3][3] - m[0][2]*m[1][0]*m[2][3]*m[3][1] - m[0][2]*m[1][1]*m[2][0]*m[3][3] + m[0][2]*m[1][1]*m[2][3]*m[3][0] + m[0][2]*m[1][3]*m[2][0]*m[3][1] - m[0][2]*m[1][3]*m[2][1]*m[3][0] - m[0][3]*m[1][0]*m[2][1]*m[3][2] + m[0][3]*m[1][0]*m[2][2]*m[3][1] + m[0][3]*m[1][1]*m[2][0]*m[3][2] - m[0][3]*m[1][1]*m[2][2]*m[3][0] - m[0][3]*m[1][2]*m[2][0]*m[3][1] + m[0][3]*m[1][2]*m[2][1]*m[3][0] } type A []A // A sequence of constant indexings. func IndexChain1(s A) A { return s[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] } // A sequence of non-constant indexings. func IndexChain2(s A, i int) A { return s[i][i][i][i][i][i][i][i][i][i][i][i][i][i][i][i] } // Another sequence of indexings. func IndexChain3(s []int) int { return s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[s[0]]]]]]]]]]]]]]]]]]]]] } // A right-leaning tree of byte multiplications. func righttree(a, b, c, d uint8) uint8 { return a * (b * (c * (d * (a * (b * (c * (d * (a * (b * (c * (d * (a * (b * (c * (d * (a * (b * (c * (d * a * (b * (c * d))))))))))))))))))))) } // A left-leaning tree of byte multiplications. func lefttree(a, b, c, d uint8) uint8 { return ((((((((((((((((((a * b) * c) * d * a) * b) * c) * d * a) * b) * c) * d * a) * b) * c) * d * a) * b) * c) * d * a) * b) * c) * d) } type T struct { Next I } type I interface{} // A chains of type assertions. func ChainT(t *T) *T { return t. Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T). Next.(*T) } type U struct { Children []J } func (u *U) Child(n int) J { return u.Children[n] } type J interface { Child(n int) J } func ChainUAssert(u *U) *U { return u.Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U). Child(0).(*U) } func ChainUNoAssert(u *U) *U { return u.Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0). Child(0).(*U) } // Type assertions and slice indexing. See issue 4207. func ChainAssertIndex(u *U) J { return u. Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0].(*U). Children[0] } type UArr struct { Children [2]J } func (u *UArr) Child(n int) J { return u.Children[n] } func ChainAssertArrayIndex(u *UArr) J { return u. Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0].(*UArr). Children[0] } type UArrPtr struct { Children *[2]J } func (u *UArrPtr) Child(n int) J { return u.Children[n] } func ChainAssertArrayptrIndex(u *UArrPtr) J { return u. Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0].(*UArrPtr). Children[0] } // Chains of divisions. See issue 4201. func ChainDiv(a, b int) int { return a / b / a / b / a / b / a / b / a / b / a / b / a / b / a / b / a / b / a / b / a / b / a / b } func ChainDivRight(a, b int) int { return a / (b / (a / (b / (a / (b / (a / (b / (a / (b / (a / (b / (a / (b / (a / (b / (a / (b / (a / b)))))))))))))))))) } func ChainDivConst(a int) int { return a / 17 / 17 / 17 / 17 / 17 / 17 / 17 / 17 / 17 / 17 / 17 } func ChainMulBytes(a, b, c byte) byte { return a*(a*(a*(a*(a*(a*(a*(a*(a*b+c)+c)+c)+c)+c)+c)+c)+c) + c } func ChainCap() { select { case <-make(chan int, cap(make(chan int, cap(make(chan int, cap(make(chan int, cap(make(chan int))))))))): default: } } ================================================ FILE: testData/parser/Torture.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// compile') PsiComment(GO_LINE_COMMENT)('// Copyright 2012 The Go Authors. All rights reserved.') PsiComment(GO_LINE_COMMENT)('// Use of this source code is governed by a BSD-style') PsiComment(GO_LINE_COMMENT)('// license that can be found in the LICENSE file.') PsiComment(GO_LINE_COMMENT)('// Various tests for expressions with high complexity.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST PsiComment(GO_LINE_COMMENT)('// Concatenate 16 4-bit integers into a 64-bit number.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('concat') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') POINTER_TYPE PsiElement(*)('*') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('16') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint64') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('r') PsiElement(:=)(':=') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('5') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('6') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('7') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('8') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('9') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('10') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('11') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('12') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('13') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('14') PsiElement(])(']') PsiElement())(')') PsiElement())(')') PsiElement(<<)('<<') LITERAL PsiElement(int)('4') PsiElement(|)('|') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('uint64') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('15') PsiElement(])(']') PsiElement())(')') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('r') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Compute the determinant of a 4x4-matrix by the sum') PsiComment(GO_LINE_COMMENT)('// over all index permutations.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('determinant') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('m') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Compute the determinant of a 4x4-matrix by the sum') PsiComment(GO_LINE_COMMENT)('// over all index permutations.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('determinantInt') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('m') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Compute the determinant of a 4x4-matrix by the sum') PsiComment(GO_LINE_COMMENT)('// over all index permutations.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('determinantByte') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('m') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('4') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR ADD_EXPR MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(-)('-') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(+)('+') MUL_EXPR MUL_EXPR MUL_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(*)('*') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('m') PsiElement([)('[') LITERAL PsiElement(int)('3') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('A') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('A') PsiComment(GO_LINE_COMMENT)('// A sequence of constant indexings.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('IndexChain1') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('A') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('A') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// A sequence of non-constant indexings.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('IndexChain2') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('A') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('i') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('A') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Another sequence of indexings.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('IndexChain3') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// A right-leaning tree of byte multiplications.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('righttree') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('b') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('c') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('d') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint8') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint8') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// A left-leaning tree of byte multiplications.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('lefttree') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('b') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('c') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('d') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint8') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('uint8') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('d') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Next') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('I') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('I') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// A chains of type assertions.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainT') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('t') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(.)('.') PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Next') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T') PsiElement())(')') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('U') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Children') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(identifier)('Child') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('n') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(])(']') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('J') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') METHOD_SPEC PsiElement(identifier)('Child') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('n') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainUAssert') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainUNoAssert') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') TYPE_ASSERTION_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR SELECTOR_EXPR CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Child') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement())(')') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Type assertions and slice indexing. See issue 4207.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainAssertIndex') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('U') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('UArr') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Children') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(identifier)('Child') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('n') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(])(']') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainAssertArrayIndex') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('UArrPtr') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('Children') POINTER_TYPE PsiElement(*)('*') ARRAY_OR_SLICE_TYPE PsiElement([)('[') LITERAL PsiElement(int)('2') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(identifier)('Child') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('n') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(])(']') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainAssertArrayptrIndex') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('u') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('J') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR SELECTOR_EXPR TYPE_ASSERTION_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('u') PsiElement(.)('.') PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(.)('.') PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('UArrPtr') PsiElement())(')') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Children') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Chains of divisions. See issue 4201.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainDiv') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('b') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainDivRight') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('b') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(/)('/') PARENTHESES_EXPR PsiElement(()('(') MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainDivConst') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(/)('/') LITERAL PsiElement(int)('17') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainMulBytes') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('b') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('c') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('a') PsiElement(*)('*') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('ChainCap') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SELECT_STATEMENT PsiElement(select)('select') PsiElement({)('{') COMM_CLAUSE COMM_CASE PsiElement(case)('case') RECV_STATEMENT UNARY_EXPR PsiElement(<-)('<-') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('cap') ARGUMENT_LIST PsiElement(()('(') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('cap') ARGUMENT_LIST PsiElement(()('(') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('cap') ARGUMENT_LIST PsiElement(()('(') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('cap') ARGUMENT_LIST PsiElement(()('(') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement())(')') PsiElement(:)(':') COMM_CLAUSE COMM_CASE PsiElement(default)('default') PsiElement(:)(':') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/TypeComma.go ================================================ package main import "fmt" type TestType struct{} func (t TestType) func1() { fmt.Println("func1!!!") } func test2() ( TestType, error ) { return TestType{}, nil } func test() ( TestType, error, ) { return TestType{}, nil } func main() { t, _ := test() t.func1() // Unresolved reference here } ================================================ FILE: testData/parser/TypeComma.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('TestType') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') PsiElement(})('}') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('t') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TestType') PsiElement())(')') PsiElement(identifier)('func1') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Println') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"func1!!!"') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('test2') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT PsiElement(()('(') TYPE_LIST TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TestType') PsiElement(,)(',') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TestType') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('test') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT PsiElement(()('(') TYPE_LIST TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TestType') PsiElement(,)(',') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement(,)(',') PsiElement())(')') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('TestType') LITERAL_VALUE PsiElement({)('{') PsiElement(})('}') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('t') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('_') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('test') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('t') PsiElement(.)('.') PsiElement(identifier)('func1') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// Unresolved reference here') PsiElement(})('}') ================================================ FILE: testData/parser/TypeInBlock.go ================================================ package exec func Start() { if c.Process != nil { return 1 } type F func(*Cmd) () } func Start2() { if c.Process != nil { return 1 } } ================================================ FILE: testData/parser/TypeInBlock.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('exec') IMPORT_LIST FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('Start') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement(.)('.') PsiElement(identifier)('Process') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') LITERAL PsiElement(int)('1') PsiElement(})('}') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('F') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Cmd') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement(})('}') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('Start2') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') PsiElement(if)('if') PsiElement(identifier)('c') PsiElement(.)('.') PsiElement(identifier)('Process') PsiElement(!=)('!=') PsiElement(identifier)('nil') PsiElement({)('{') PsiElement(return)('return') PsiElement(int)('1') PsiElement(})('}') PsiElement(})('}') ================================================ FILE: testData/parser/Types.go ================================================ package main type ( T0 []string T1 []string T2 struct{ a, b int } T3 struct{ a, c int } T4 func(int, float64) *T0 T5 func(x int, y float64) *[]string ) func main() { type Point interface { } var p interface{} = nil var c chan int = nil var x func() = nil var y func()int = nil *Point(p) // same as *(Point(p)) *(Point(p)) (*Point)(p) // p is converted to *Point <-chan int(c) // same as <-(chan int(c)) (<-chan int)(c) // c is converted to <-chan int (func())(x) // x is converted to func() (func() int)(y) // x is converted to func() int func() int(y) // x is converted to func() int (unambiguous) //func()(x) // function signature func() x } ================================================ FILE: testData/parser/Types.txt ================================================ GO_FILE PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('main') IMPORT_LIST TYPE_DECLARATION PsiElement(type)('type') PsiElement(()('(') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T0') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T1') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T2') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('b') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T3') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('a') PsiElement(,)(',') FIELD_DEFINITION PsiElement(identifier)('c') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(})('}') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T4') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') PARAMETER_DECLARATION TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('T0') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('T5') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('x') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('y') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('float64') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('main') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') BLOCK PsiElement({)('{') STATEMENT TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Point') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('p') INTERFACE_TYPE PsiElement(interface)('interface') PsiElement({)('{') PsiElement(})('}') PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('c') CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('x') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('y') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(*)('*') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Point') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// same as *(Point(p))') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(*)('*') PARENTHESES_EXPR PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('Point') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement())(')') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONVERSION_EXPR PAR_TYPE PsiElement(()('(') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Point') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('p') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// p is converted to *Point') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST UNARY_EXPR PsiElement(<-)('<-') CONVERSION_EXPR CHANNEL_TYPE PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// same as <-(chan int(c))') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONVERSION_EXPR PAR_TYPE PsiElement(()('(') CHANNEL_TYPE PsiElement(<-)('<-') PsiElement(chan)('chan') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('c') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// c is converted to <-chan int') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONVERSION_EXPR PAR_TYPE PsiElement(()('(') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// x is converted to func()') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONVERSION_EXPR PAR_TYPE PsiElement(()('(') FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement())(')') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('y') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// x is converted to func() int') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONVERSION_EXPR FUNCTION_TYPE PsiElement(func)('func') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('y') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// x is converted to func() int (unambiguous)') PsiComment(GO_LINE_COMMENT)('//func()(x) // function signature func() x') PsiElement(})('}') ================================================ FILE: testData/parser/Writer.go ================================================ // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tar // TODO(dsymonds): // - catch more errors (no first header, etc.) import ( "bytes" "errors" "fmt" "io" "os" "path" "strconv" "strings" "time" ) var ( ErrWriteTooLong = errors.New("archive/tar: write too long") ErrFieldTooLong = errors.New("archive/tar: header field too long") ErrWriteAfterClose = errors.New("archive/tar: write after close") errNameTooLong = errors.New("archive/tar: name too long") ) // A Writer provides sequential writing of a tar archive in POSIX.1 format. // A tar archive consists of a sequence of files. // Call WriteHeader to begin a new file, and then call Write to supply that file's data, // writing at most hdr.Size bytes in total. type Writer struct { w io.Writer err error nb int64 // number of unwritten bytes for current file entry pad int64 // amount of padding to write after current file entry closed bool usedBinary bool // whether the binary numeric field extension was used } // NewWriter creates a new Writer writing to w. func NewWriter(w io.Writer) *Writer { return &Writer{w: w} } // Flush finishes writing the current file (optional). func (tw *Writer) Flush() error { if tw.nb > 0 { tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb) return tw.err } n := tw.nb + tw.pad for n > 0 && tw.err == nil { nr := n if nr > blockSize { nr = blockSize } var nw int nw, tw.err = tw.w.Write(zeroBlock[0:nr]) n -= int64(nw) } tw.nb = 0 tw.pad = 0 return tw.err } // Write s into b, terminating it with a NUL if there is room. func (tw *Writer) cString(b []byte, s string) { if len(s) > len(b) { if tw.err == nil { tw.err = ErrFieldTooLong } return } copy(b, s) if len(s) < len(b) { b[len(s)] = 0 } } // Encode x as an octal ASCII string and write it into b with leading zeros. func (tw *Writer) octal(b []byte, x int64) { s := strconv.FormatInt(x, 8) // leading zeros, but leave room for a NUL. for len(s)+1 < len(b) { s = "0" + s } tw.cString(b, s) } // Write x into b, either as octal or as binary (GNUtar/star extension). func (tw *Writer) numeric(b []byte, x int64) { // Try octal first. s := strconv.FormatInt(x, 8) if len(s) < len(b) { tw.octal(b, x) return } // Too big: use binary (big-endian). tw.usedBinary = true for i := len(b) - 1; x > 0 && i >= 0; i-- { b[i] = byte(x) x >>= 8 } b[0] |= 0x80 // highest bit indicates binary format } var ( minTime = time.Unix(0, 0) // There is room for 11 octal digits (33 bits) of mtime. maxTime = minTime.Add((1<<33 - 1) * time.Second) ) // WriteHeader writes hdr and prepares to accept the file's contents. // WriteHeader calls Flush if it is not the first header. // Calling after a Close will return ErrWriteAfterClose. func (tw *Writer) WriteHeader(hdr *Header) error { if tw.closed { return ErrWriteAfterClose } if tw.err == nil { tw.Flush() } if tw.err != nil { return tw.err } // Decide whether or not to use PAX extensions // TODO(shanemhansen): we might want to use PAX headers for // subsecond time resolution, but for now let's just capture // the long name/long symlink use case. suffix := hdr.Name prefix := "" if len(hdr.Name) > fileNameSize || len(hdr.Linkname) > fileNameSize { var err error prefix, suffix, err = tw.splitUSTARLongName(hdr.Name) // Either we were unable to pack the long name into ustar format // or the link name is too long; use PAX headers. if err == errNameTooLong || len(hdr.Linkname) > fileNameSize { if err := tw.writePAXHeader(hdr); err != nil { return err } } else if err != nil { return err } } tw.nb = int64(hdr.Size) tw.pad = -tw.nb & (blockSize - 1) // blockSize is a power of two header := make([]byte, blockSize) s := slicer(header) tw.cString(s.next(fileNameSize), suffix) // Handle out of range ModTime carefully. var modTime int64 if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) { modTime = hdr.ModTime.Unix() } tw.octal(s.next(8), hdr.Mode) // 100:108 tw.numeric(s.next(8), int64(hdr.Uid)) // 108:116 tw.numeric(s.next(8), int64(hdr.Gid)) // 116:124 tw.numeric(s.next(12), hdr.Size) // 124:136 tw.numeric(s.next(12), modTime) // 136:148 s.next(8) // chksum (148:156) s.next(1)[0] = hdr.Typeflag // 156:157 tw.cString(s.next(100), hdr.Linkname) // linkname (157:257) copy(s.next(8), []byte("ustar\x0000")) // 257:265 tw.cString(s.next(32), hdr.Uname) // 265:297 tw.cString(s.next(32), hdr.Gname) // 297:329 tw.numeric(s.next(8), hdr.Devmajor) // 329:337 tw.numeric(s.next(8), hdr.Devminor) // 337:345 tw.cString(s.next(155), prefix) // 345:500 // Use the GNU magic instead of POSIX magic if we used any GNU extensions. if tw.usedBinary { copy(header[257:265], []byte("ustar \x00")) } // Use the ustar magic if we used ustar long names. if len(prefix) > 0 { copy(header[257:265], []byte("ustar\000")) } // The chksum field is terminated by a NUL and a space. // This is different from the other octal fields. chksum, _ := checksum(header) tw.octal(header[148:155], chksum) header[155] = ' ' if tw.err != nil { // problem with header; probably integer too big for a field. return tw.err } _, tw.err = tw.w.Write(header) return tw.err } // writeUSTARLongName splits a USTAR long name hdr.Name. // name must be < 256 characters. errNameTooLong is returned // if hdr.Name can't be split. The splitting heuristic // is compatible with gnu tar. func (tw *Writer) splitUSTARLongName(name string) (prefix, suffix string, err error) { length := len(name) if length > fileNamePrefixSize+1 { length = fileNamePrefixSize + 1 } else if name[length-1] == '/' { length-- } i := strings.LastIndex(name[:length], "/") nlen := length - i - 1 if i <= 0 || nlen > fileNameSize || nlen == 0 { err = errNameTooLong return } prefix, suffix = name[:i], name[i+1:] return } // writePaxHeader writes an extended pax header to the // archive. func (tw *Writer) writePAXHeader(hdr *Header) error { // Prepare extended header ext := new(Header) ext.Typeflag = TypeXHeader // Setting ModTime is required for reader parsing to // succeed, and seems harmless enough. ext.ModTime = hdr.ModTime // The spec asks that we namespace our pseudo files // with the current pid. pid := os.Getpid() dir, file := path.Split(hdr.Name) ext.Name = path.Join(dir, fmt.Sprintf("PaxHeaders.%d", pid), file)[0:100] // Construct the body var buf bytes.Buffer if len(hdr.Name) > fileNameSize { fmt.Fprint(&buf, paxHeader("path="+hdr.Name)) } if len(hdr.Linkname) > fileNameSize { fmt.Fprint(&buf, paxHeader("linkpath="+hdr.Linkname)) } ext.Size = int64(len(buf.Bytes())) if err := tw.WriteHeader(ext); err != nil { return err } if _, err := tw.Write(buf.Bytes()); err != nil { return err } if err := tw.Flush(); err != nil { return err } return nil } // paxHeader formats a single pax record, prefixing it with the appropriate length func paxHeader(msg string) string { const padding = 2 // Extra padding for space and newline size := len(msg) + padding size += len(strconv.Itoa(size)) record := fmt.Sprintf("%d %s\n", size, msg) if len(record) != size { // Final adjustment if adding size increased // the number of digits in size size = len(record) record = fmt.Sprintf("%d %s\n", size, msg) } return record } // Write writes to the current entry in the tar archive. // Write returns the error ErrWriteTooLong if more than // hdr.Size bytes are written after WriteHeader. func (tw *Writer) Write(b []byte) (n int, err error) { if tw.closed { err = ErrWriteTooLong return } overwrite := false if int64(len(b)) > tw.nb { b = b[0:tw.nb] overwrite = true } n, err = tw.w.Write(b) tw.nb -= int64(n) if err == nil && overwrite { err = ErrWriteTooLong return } tw.err = err return } // Close closes the tar archive, flushing any unwritten // data to the underlying writer. func (tw *Writer) Close() error { if tw.err != nil || tw.closed { return tw.err } tw.Flush() tw.closed = true if tw.err != nil { return tw.err } // trailer: two zero blocks for i := 0; i < 2; i++ { _, tw.err = tw.w.Write(zeroBlock) if tw.err != nil { break } } return tw.err } ================================================ FILE: testData/parser/Writer.txt ================================================ GO_FILE PsiComment(GO_LINE_COMMENT)('// Copyright 2009 The Go Authors. All rights reserved.') PsiComment(GO_LINE_COMMENT)('// Use of this source code is governed by a BSD-style') PsiComment(GO_LINE_COMMENT)('// license that can be found in the LICENSE file.') PACKAGE_CLAUSE PsiElement(package)('package') PsiElement(identifier)('tar') PsiComment(GO_LINE_COMMENT)('// TODO(dsymonds):') PsiComment(GO_LINE_COMMENT)('// - catch more errors (no first header, etc.)') IMPORT_LIST IMPORT_DECLARATION PsiElement(import)('import') PsiElement(()('(') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"bytes"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"errors"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"fmt"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"io"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"os"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"path"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"strconv"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"strings"') IMPORT_SPEC IMPORT_STRING STRING_LITERAL PsiElement(string)('"time"') PsiElement())(')') VAR_DECLARATION PsiElement(var)('var') PsiElement(()('(') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('ErrWriteTooLong') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('New') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"archive/tar: write too long"') PsiElement())(')') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('ErrFieldTooLong') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('New') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"archive/tar: header field too long"') PsiElement())(')') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('ErrWriteAfterClose') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('New') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"archive/tar: write after close"') PsiElement())(')') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('errNameTooLong') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('errors') PsiElement(.)('.') PsiElement(identifier)('New') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"archive/tar: name too long"') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// A Writer provides sequential writing of a tar archive in POSIX.1 format.') PsiComment(GO_LINE_COMMENT)('// A tar archive consists of a sequence of files.') PsiComment(GO_LINE_COMMENT)('// Call WriteHeader to begin a new file, and then call Write to supply that file's data,') PsiComment(GO_LINE_COMMENT)('// writing at most hdr.Size bytes in total.') TYPE_DECLARATION PsiElement(type)('type') TYPE_SPEC SPEC_TYPE PsiElement(identifier)('Writer') STRUCT_TYPE PsiElement(struct)('struct') PsiElement({)('{') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('w') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('io') PsiElement(.)('.') PsiElement(identifier)('Writer') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('nb') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int64') PsiComment(GO_LINE_COMMENT)('// number of unwritten bytes for current file entry') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('pad') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int64') PsiComment(GO_LINE_COMMENT)('// amount of padding to write after current file entry') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('closed') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') FIELD_DECLARATION FIELD_DEFINITION PsiElement(identifier)('usedBinary') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bool') PsiComment(GO_LINE_COMMENT)('// whether the binary numeric field extension was used') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// NewWriter creates a new Writer writing to w.') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('NewWriter') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('w') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('io') PsiElement(.)('.') PsiElement(identifier)('Writer') PsiElement())(')') RESULT POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') UNARY_EXPR PsiElement(&)('&') COMPOSITE_LIT TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') LITERAL_VALUE PsiElement({)('{') ELEMENT KEY FIELD_NAME PsiElement(identifier)('w') PsiElement(:)(':') VALUE REFERENCE_EXPRESSION PsiElement(identifier)('w') PsiElement(})('}') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Flush finishes writing the current file (optional).') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('Flush') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') PsiElement(>)('>') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Errorf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"archive/tar: missed writing %d bytes"') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('n') PsiElement(:=)(':=') ADD_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('pad') FOR_STATEMENT PsiElement(for)('for') AND_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(>)('>') LITERAL PsiElement(int)('0') PsiElement(&&)('&&') CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('nr') PsiElement(:=)(':=') REFERENCE_EXPRESSION PsiElement(identifier)('n') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('nr') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('blockSize') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('nr') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('blockSize') PsiElement(})('}') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('nw') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('nw') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('w') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('zeroBlock') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(:)(':') REFERENCE_EXPRESSION PsiElement(identifier)('nr') PsiElement(])(']') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('n') ASSIGN_OP PsiElement(-=)('-=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('nw') PsiElement())(')') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') ASSIGN_OP PsiElement(=)('=') LITERAL PsiElement(int)('0') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('pad') ASSIGN_OP PsiElement(=)('=') LITERAL PsiElement(int)('0') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Write s into b, terminating it with a NUL if there is room.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('cString') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('b') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('s') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(>)('>') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('ErrFieldTooLong') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('copy') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(<)('<') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement([)('[') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(])(']') ASSIGN_OP PsiElement(=)('=') LITERAL PsiElement(int)('0') PsiElement(})('}') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Encode x as an octal ASCII string and write it into b with leading zeros.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('octal') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('b') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('x') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int64') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('s') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strconv') PsiElement(.)('.') PsiElement(identifier)('FormatInt') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(,)(',') LITERAL PsiElement(int)('8') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// leading zeros, but leave room for a NUL.') FOR_STATEMENT PsiElement(for)('for') CONDITIONAL_EXPR ADD_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(+)('+') LITERAL PsiElement(int)('1') PsiElement(<)('<') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('s') ASSIGN_OP PsiElement(=)('=') ADD_EXPR STRING_LITERAL PsiElement(string)('"0"') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Write x into b, either as octal or as binary (GNUtar/star extension).') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('numeric') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('b') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('x') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int64') PsiElement())(')') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// Try octal first.') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('s') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strconv') PsiElement(.)('.') PsiElement(identifier)('FormatInt') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(,)(',') LITERAL PsiElement(int)('8') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement())(')') PsiElement(<)('<') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('octal') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Too big: use binary (big-endian).') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('usedBinary') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('true') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') ADD_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement(-)('-') LITERAL PsiElement(int)('1') PsiElement(;)(';') AND_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement(>)('>') LITERAL PsiElement(int)('0') PsiElement(&&)('&&') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(>=)('>=') LITERAL PsiElement(int)('0') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(--)('--') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement([)('[') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('byte') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('x') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('x') ASSIGN_OP PsiElement(>>=)('>>=') LITERAL PsiElement(int)('8') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') ASSIGN_OP PsiElement(|=)('|=') LITERAL PsiElement(hex)('0x80') PsiComment(GO_LINE_COMMENT)('// highest bit indicates binary format') PsiElement(})('}') VAR_DECLARATION PsiElement(var)('var') PsiElement(()('(') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('minTime') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('time') PsiElement(.)('.') PsiElement(identifier)('Unix') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('0') PsiElement(,)(',') LITERAL PsiElement(int)('0') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// There is room for 11 octal digits (33 bits) of mtime.') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('maxTime') PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('minTime') PsiElement(.)('.') PsiElement(identifier)('Add') ARGUMENT_LIST PsiElement(()('(') MUL_EXPR PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR MUL_EXPR LITERAL PsiElement(int)('1') PsiElement(<<)('<<') LITERAL PsiElement(int)('33') PsiElement(-)('-') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement(*)('*') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('time') PsiElement(.)('.') PsiElement(identifier)('Second') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// WriteHeader writes hdr and prepares to accept the file's contents.') PsiComment(GO_LINE_COMMENT)('// WriteHeader calls Flush if it is not the first header.') PsiComment(GO_LINE_COMMENT)('// Calling after a Close will return ErrWriteAfterClose.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('WriteHeader') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('hdr') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Header') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('closed') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('ErrWriteAfterClose') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('Flush') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Decide whether or not to use PAX extensions') PsiComment(GO_LINE_COMMENT)('// TODO(shanemhansen): we might want to use PAX headers for') PsiComment(GO_LINE_COMMENT)('// subsecond time resolution, but for now let's just capture') PsiComment(GO_LINE_COMMENT)('// the long name/long symlink use case.') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('suffix') PsiElement(:=)(':=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('prefix') PsiElement(:=)(':=') STRING_LITERAL PsiElement(string)('""') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST OR_EXPR CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') PsiElement(||)('||') CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Linkname') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') BLOCK PsiElement({)('{') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('prefix') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('suffix') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('splitUSTARLongName') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// Either we were unable to pack the long name into ustar format') PsiComment(GO_LINE_COMMENT)('// or the link name is too long; use PAX headers.') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST OR_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('errNameTooLong') PsiElement(||)('||') CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Linkname') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('writePAXHeader') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Size') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('pad') ASSIGN_OP PsiElement(=)('=') MUL_EXPR UNARY_EXPR PsiElement(-)('-') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') PsiElement(&)('&') PARENTHESES_EXPR PsiElement(()('(') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('blockSize') PsiElement(-)('-') LITERAL PsiElement(int)('1') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// blockSize is a power of two') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('header') PsiElement(:=)(':=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('make') BUILTIN_ARGUMENT_LIST PsiElement(()('(') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('blockSize') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('s') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('slicer') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('suffix') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// Handle out of range ModTime carefully.') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('modTime') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int64') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST AND_EXPR UNARY_EXPR PsiElement(!)('!') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('ModTime') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Before') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('minTime') PsiElement())(')') PsiElement(&&)('&&') UNARY_EXPR PsiElement(!)('!') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('ModTime') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('After') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('maxTime') PsiElement())(')') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('modTime') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('ModTime') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Unix') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('octal') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Mode') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 100:108') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Uid') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 108:116') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Gid') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 116:124') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('12') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Size') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 124:136') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('12') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('modTime') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 136:148') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// chksum (148:156)') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('1') PsiElement())(')') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(])(']') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Typeflag') PsiComment(GO_LINE_COMMENT)('// 156:157') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('100') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Linkname') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// linkname (157:257)') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('copy') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') STRING_LITERAL PsiElement(string)('"ustar\x0000"') PsiElement())(')') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 257:265') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('32') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Uname') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 265:297') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('32') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Gname') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 297:329') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Devmajor') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 329:337') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('numeric') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('8') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Devminor') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 337:345') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('cString') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('s') PsiElement(.)('.') PsiElement(identifier)('next') ARGUMENT_LIST PsiElement(()('(') LITERAL PsiElement(int)('155') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('prefix') PsiElement())(')') PsiComment(GO_LINE_COMMENT)('// 345:500') PsiComment(GO_LINE_COMMENT)('// Use the GNU magic instead of POSIX magic if we used any GNU extensions.') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('usedBinary') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('copy') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement([)('[') LITERAL PsiElement(int)('257') PsiElement(:)(':') LITERAL PsiElement(int)('265') PsiElement(])(']') PsiElement(,)(',') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') STRING_LITERAL PsiElement(string)('"ustar \x00"') PsiElement())(')') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Use the ustar magic if we used ustar long names.') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('prefix') PsiElement())(')') PsiElement(>)('>') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('copy') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement([)('[') LITERAL PsiElement(int)('257') PsiElement(:)(':') LITERAL PsiElement(int)('265') PsiElement(])(']') PsiElement(,)(',') CONVERSION_EXPR ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement(()('(') STRING_LITERAL PsiElement(string)('"ustar\000"') PsiElement())(')') PsiElement())(')') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// The chksum field is terminated by a NUL and a space.') PsiComment(GO_LINE_COMMENT)('// This is different from the other octal fields.') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('chksum') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('_') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('checksum') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement())(')') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('octal') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement([)('[') LITERAL PsiElement(int)('148') PsiElement(:)(':') LITERAL PsiElement(int)('155') PsiElement(])(']') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('chksum') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement([)('[') LITERAL PsiElement(int)('155') PsiElement(])(']') ASSIGN_OP PsiElement(=)('=') LITERAL PsiElement(char)('' '') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// problem with header; probably integer too big for a field.') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('w') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('header') PsiElement())(')') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// writeUSTARLongName splits a USTAR long name hdr.Name.') PsiComment(GO_LINE_COMMENT)('// name must be < 256 characters. errNameTooLong is returned') PsiComment(GO_LINE_COMMENT)('// if hdr.Name can't be split. The splitting heuristic') PsiComment(GO_LINE_COMMENT)('// is compatible with gnu tar.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('splitUSTARLongName') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('name') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('prefix') PsiElement(,)(',') PARAM_DEFINITION PsiElement(identifier)('suffix') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('length') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('length') PsiElement(>)('>') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('fileNamePrefixSize') PsiElement(+)('+') LITERAL PsiElement(int)('1') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('length') ASSIGN_OP PsiElement(=)('=') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('fileNamePrefixSize') PsiElement(+)('+') LITERAL PsiElement(int)('1') PsiElement(})('}') ELSE_STATEMENT PsiElement(else)('else') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement([)('[') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('length') PsiElement(-)('-') LITERAL PsiElement(int)('1') PsiElement(])(']') PsiElement(==)('==') LITERAL PsiElement(char)(''/'') BLOCK PsiElement({)('{') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('length') PsiElement(--)('--') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strings') PsiElement(.)('.') PsiElement(identifier)('LastIndex') ARGUMENT_LIST PsiElement(()('(') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement([)('[') PsiElement(:)(':') REFERENCE_EXPRESSION PsiElement(identifier)('length') PsiElement(])(']') PsiElement(,)(',') STRING_LITERAL PsiElement(string)('"/"') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('nlen') PsiElement(:=)(':=') ADD_EXPR ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('length') PsiElement(-)('-') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(-)('-') LITERAL PsiElement(int)('1') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST OR_EXPR OR_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<=)('<=') LITERAL PsiElement(int)('0') PsiElement(||)('||') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('nlen') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') PsiElement(||)('||') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('nlen') PsiElement(==)('==') LITERAL PsiElement(int)('0') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('errNameTooLong') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('prefix') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('suffix') ASSIGN_OP PsiElement(=)('=') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement([)('[') PsiElement(:)(':') REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(])(']') PsiElement(,)(',') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('name') PsiElement([)('[') ADD_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(+)('+') LITERAL PsiElement(int)('1') PsiElement(:)(':') PsiElement(])(']') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// writePaxHeader writes an extended pax header to the') PsiComment(GO_LINE_COMMENT)('// archive.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('writePAXHeader') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('hdr') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Header') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// Prepare extended header') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('ext') PsiElement(:=)(':=') BUILTIN_CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('new') BUILTIN_ARGUMENT_LIST PsiElement(()('(') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Header') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ext') PsiElement(.)('.') PsiElement(identifier)('Typeflag') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('TypeXHeader') PsiComment(GO_LINE_COMMENT)('// Setting ModTime is required for reader parsing to') PsiComment(GO_LINE_COMMENT)('// succeed, and seems harmless enough.') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ext') PsiElement(.)('.') PsiElement(identifier)('ModTime') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('ModTime') PsiComment(GO_LINE_COMMENT)('// The spec asks that we namespace our pseudo files') PsiComment(GO_LINE_COMMENT)('// with the current pid.') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('pid') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('os') PsiElement(.)('.') PsiElement(identifier)('Getpid') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('dir') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('file') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('path') PsiElement(.)('.') PsiElement(identifier)('Split') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ext') PsiElement(.)('.') PsiElement(identifier)('Name') ASSIGN_OP PsiElement(=)('=') INDEX_OR_SLICE_EXPR CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('path') PsiElement(.)('.') PsiElement(identifier)('Join') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('dir') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Sprintf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"PaxHeaders.%d"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('pid') PsiElement())(')') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('file') PsiElement())(')') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(:)(':') LITERAL PsiElement(int)('100') PsiElement(])(']') PsiComment(GO_LINE_COMMENT)('// Construct the body') STATEMENT VAR_DECLARATION PsiElement(var)('var') VAR_SPEC VAR_DEFINITION PsiElement(identifier)('buf') TYPE TYPE_REFERENCE_EXPRESSION TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('bytes') PsiElement(.)('.') PsiElement(identifier)('Buffer') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Fprint') ARGUMENT_LIST PsiElement(()('(') UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('buf') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('paxHeader') ARGUMENT_LIST PsiElement(()('(') ADD_EXPR STRING_LITERAL PsiElement(string)('"path="') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Name') PsiElement())(')') PsiElement())(')') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Linkname') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION PsiElement(identifier)('fileNameSize') BLOCK PsiElement({)('{') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Fprint') ARGUMENT_LIST PsiElement(()('(') UNARY_EXPR PsiElement(&)('&') REFERENCE_EXPRESSION PsiElement(identifier)('buf') PsiElement(,)(',') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('paxHeader') ARGUMENT_LIST PsiElement(()('(') ADD_EXPR STRING_LITERAL PsiElement(string)('"linkpath="') PsiElement(+)('+') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('hdr') PsiElement(.)('.') PsiElement(identifier)('Linkname') PsiElement())(')') PsiElement())(')') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('ext') PsiElement(.)('.') PsiElement(identifier)('Size') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('buf') PsiElement(.)('.') PsiElement(identifier)('Bytes') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('WriteHeader') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('ext') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('_') PsiElement(,)(',') VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('buf') PsiElement(.)('.') PsiElement(identifier)('Bytes') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('err') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('Flush') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// paxHeader formats a single pax record, prefixing it with the appropriate length') FUNCTION_DECLARATION PsiElement(func)('func') PsiElement(identifier)('paxHeader') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('msg') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('string') BLOCK PsiElement({)('{') STATEMENT CONST_DECLARATION PsiElement(const)('const') CONST_SPEC CONST_DEFINITION PsiElement(identifier)('padding') PsiElement(=)('=') LITERAL PsiElement(int)('2') PsiComment(GO_LINE_COMMENT)('// Extra padding for space and newline') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('size') PsiElement(:=)(':=') ADD_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('msg') PsiElement())(')') PsiElement(+)('+') REFERENCE_EXPRESSION PsiElement(identifier)('padding') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('size') ASSIGN_OP PsiElement(+=)('+=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('strconv') PsiElement(.)('.') PsiElement(identifier)('Itoa') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('size') PsiElement())(')') PsiElement())(')') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('record') PsiElement(:=)(':=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Sprintf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d %s\n"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('size') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('msg') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('record') PsiElement())(')') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('size') BLOCK PsiElement({)('{') PsiComment(GO_LINE_COMMENT)('// Final adjustment if adding size increased') PsiComment(GO_LINE_COMMENT)('// the number of digits in size') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('size') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('record') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('record') ASSIGN_OP PsiElement(=)('=') CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('fmt') PsiElement(.)('.') PsiElement(identifier)('Sprintf') ARGUMENT_LIST PsiElement(()('(') STRING_LITERAL PsiElement(string)('"%d %s\n"') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('size') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('msg') PsiElement())(')') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION PsiElement(identifier)('record') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Write writes to the current entry in the tar archive.') PsiComment(GO_LINE_COMMENT)('// Write returns the error ErrWriteTooLong if more than') PsiComment(GO_LINE_COMMENT)('// hdr.Size bytes are written after WriteHeader.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('Write') SIGNATURE PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('b') ARRAY_OR_SLICE_TYPE PsiElement([)('[') PsiElement(])(']') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('byte') PsiElement())(')') RESULT PARAMETERS PsiElement(()('(') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('n') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('int') PsiElement(,)(',') PARAMETER_DECLARATION PARAM_DEFINITION PsiElement(identifier)('err') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') PsiElement())(')') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('closed') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('ErrWriteTooLong') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('overwrite') PsiElement(:=)(':=') REFERENCE_EXPRESSION PsiElement(identifier)('false') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('len') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') PsiElement())(')') PsiElement(>)('>') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('b') ASSIGN_OP PsiElement(=)('=') INDEX_OR_SLICE_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement([)('[') LITERAL PsiElement(int)('0') PsiElement(:)(':') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') PsiElement(])(']') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('overwrite') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('true') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement(,)(',') REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('w') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('b') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('nb') ASSIGN_OP PsiElement(-=)('-=') CALL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('int64') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('n') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST AND_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('err') PsiElement(==)('==') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(&&)('&&') REFERENCE_EXPRESSION PsiElement(identifier)('overwrite') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('ErrWriteTooLong') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('err') RETURN_STATEMENT PsiElement(return)('return') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// Close closes the tar archive, flushing any unwritten') PsiComment(GO_LINE_COMMENT)('// data to the underlying writer.') METHOD_DECLARATION PsiElement(func)('func') RECEIVER PsiElement(()('(') PsiElement(identifier)('tw') POINTER_TYPE PsiElement(*)('*') TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('Writer') PsiElement())(')') PsiElement(identifier)('Close') SIGNATURE PARAMETERS PsiElement(()('(') PsiElement())(')') RESULT TYPE TYPE_REFERENCE_EXPRESSION PsiElement(identifier)('error') BLOCK PsiElement({)('{') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST OR_EXPR CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') PsiElement(||)('||') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('closed') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CALL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('Flush') ARGUMENT_LIST PsiElement(()('(') PsiElement())(')') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('closed') ASSIGN_OP PsiElement(=)('=') REFERENCE_EXPRESSION PsiElement(identifier)('true') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') PsiComment(GO_LINE_COMMENT)('// trailer: two zero blocks') FOR_STATEMENT PsiElement(for)('for') FOR_CLAUSE SIMPLE_STATEMENT SHORT_VAR_DECLARATION VAR_DEFINITION PsiElement(identifier)('i') PsiElement(:=)(':=') LITERAL PsiElement(int)('0') PsiElement(;)(';') CONDITIONAL_EXPR REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(<)('<') LITERAL PsiElement(int)('2') PsiElement(;)(';') INC_DEC_STATEMENT REFERENCE_EXPRESSION PsiElement(identifier)('i') PsiElement(++)('++') BLOCK PsiElement({)('{') ASSIGNMENT_STATEMENT LEFT_HAND_EXPR_LIST REFERENCE_EXPRESSION PsiElement(identifier)('_') PsiElement(,)(',') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') ASSIGN_OP PsiElement(=)('=') CALL_EXPR SELECTOR_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('w') PsiElement(.)('.') REFERENCE_EXPRESSION PsiElement(identifier)('Write') ARGUMENT_LIST PsiElement(()('(') REFERENCE_EXPRESSION PsiElement(identifier)('zeroBlock') PsiElement())(')') IF_STATEMENT PsiElement(if)('if') SIMPLE_STATEMENT LEFT_HAND_EXPR_LIST CONDITIONAL_EXPR REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(!=)('!=') REFERENCE_EXPRESSION PsiElement(identifier)('nil') BLOCK PsiElement({)('{') BREAK_STATEMENT PsiElement(break)('break') PsiElement(})('}') PsiElement(})('}') RETURN_STATEMENT PsiElement(return)('return') REFERENCE_EXPRESSION REFERENCE_EXPRESSION PsiElement(identifier)('tw') PsiElement(.)('.') PsiElement(identifier)('err') PsiElement(})('}') ================================================ FILE: testData/performance/GoUnresolvedReference/expected.xml ================================================ ================================================ FILE: testData/performance/GoUnusedExportedFunction/expected.xml ================================================ cli.go 92 light_idea_test_case Unused exported function inspection Unused function <code>NewDockerCli</code> #loc local.go 78 light_idea_test_case Unused exported function inspection Unused function <code>NewRouter</code> #loc network.go 21 light_idea_test_case Unused exported function inspection Unused function <code>NewRouter</code> #loc form.go 57 light_idea_test_case Unused exported function inspection Unused function <code>ArchiveFormValues</code> #loc httputils.go 28 light_idea_test_case Unused exported function inspection Unused function <code>HijackConnection</code> #loc httputils.go 39 light_idea_test_case Unused exported function inspection Unused function <code>CloseStreams</code> #loc httputils.go 52 light_idea_test_case Unused exported function inspection Unused function <code>CheckForJSON</code> #loc httputils.go 82 light_idea_test_case Unused exported function inspection Unused function <code>ParseMultipartForm</code> #loc httputils.go 90 light_idea_test_case Unused exported function inspection Unused function <code>WriteError</code> #loc httputils.go 163 light_idea_test_case Unused exported function inspection Unused function <code>WriteJSON</code> #loc httputils.go 171 light_idea_test_case Unused exported function inspection Unused function <code>VersionFromContext</code> #loc server.go 53 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc cli.go 33 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc cli.go 148 light_idea_test_case Unused exported function inspection Unused function <code>Subcmd</code> #loc term.go 35 light_idea_test_case Unused exported function inspection Unused function <code>StdStreams</code> #loc term.go 40 light_idea_test_case Unused exported function inspection Unused function <code>GetFdInfo</code> #loc term.go 51 light_idea_test_case Unused exported function inspection Unused function <code>GetWinsize</code> #loc term.go 62 light_idea_test_case Unused exported function inspection Unused function <code>SetWinsize</code> #loc term.go 90 light_idea_test_case Unused exported function inspection Unused function <code>SaveState</code> #loc term.go 101 light_idea_test_case Unused exported function inspection Unused function <code>DisableEcho</code> #loc term.go 114 light_idea_test_case Unused exported function inspection Unused function <code>SetRawTerminal</code> #loc flag.go 437 light_idea_test_case Unused exported function inspection Unused function <code>Lookup</code> #loc flag.go 442 light_idea_test_case Unused exported function inspection Unused function <code>IsSet</code> #loc flag.go 619 light_idea_test_case Unused exported function inspection Unused function <code>NFlag</code> #loc flag.go 640 light_idea_test_case Unused exported function inspection Unused function <code>NArg</code> #loc flag.go 656 light_idea_test_case Unused exported function inspection Unused function <code>BoolVar</code> #loc flag.go 682 light_idea_test_case Unused exported function inspection Unused function <code>IntVar</code> #loc flag.go 708 light_idea_test_case Unused exported function inspection Unused function <code>Int64Var</code> #loc flag.go 734 light_idea_test_case Unused exported function inspection Unused function <code>UintVar</code> #loc flag.go 760 light_idea_test_case Unused exported function inspection Unused function <code>Uint64Var</code> #loc flag.go 786 light_idea_test_case Unused exported function inspection Unused function <code>Uint16Var</code> #loc flag.go 800 light_idea_test_case Unused exported function inspection Unused function <code>Uint16</code> #loc flag.go 812 light_idea_test_case Unused exported function inspection Unused function <code>StringVar</code> #loc flag.go 838 light_idea_test_case Unused exported function inspection Unused function <code>Float64Var</code> #loc flag.go 864 light_idea_test_case Unused exported function inspection Unused function <code>DurationVar</code> #loc flag.go 917 light_idea_test_case Unused exported function inspection Unused function <code>Var</code> #loc flag.go 1166 light_idea_test_case Unused exported function inspection Unused function <code>Parsed</code> #loc flag.go 1213 light_idea_test_case Unused exported function inspection Unused function <code>Merge</code> #loc pools.go 62 light_idea_test_case Unused exported function inspection Unused function <code>Copy</code> #loc stub_proxy.go 26 light_idea_test_case Unused exported function inspection Unused function <code>NewStubProxy</code> #loc reexec.go 13 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc reexec.go 23 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc command_unsupported.go 10 light_idea_test_case Unused exported function inspection Unused function <code>Command</code> #loc trap.go 22 light_idea_test_case Unused exported function inspection Unused function <code>Trap</code> #loc signal.go 15 light_idea_test_case Unused exported function inspection Unused function <code>CatchAll</code> #loc signal.go 24 light_idea_test_case Unused exported function inspection Unused function <code>StopCatch</code> #loc signal.go 31 light_idea_test_case Unused exported function inspection Unused function <code>ParseSignal</code> #loc mknod.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Mknod</code> #loc mknod.go 20 light_idea_test_case Unused exported function inspection Unused function <code>Mkdev</code> #loc umask.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Umask</code> #loc filesys.go 12 light_idea_test_case Unused exported function inspection Unused function <code>MkdirAll</code> #loc filesys.go 17 light_idea_test_case Unused exported function inspection Unused function <code>IsAbs</code> #loc xattrs_unsupported.go 6 light_idea_test_case Unused exported function inspection Unused function <code>Lgetxattr</code> #loc xattrs_unsupported.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Lsetxattr</code> #loc meminfo_unsupported.go 6 light_idea_test_case Unused exported function inspection Unused function <code>ReadMemInfo</code> #loc diff.go 257 light_idea_test_case Unused exported function inspection Unused function <code>ApplyUncompressedLayer</code> #loc archive.go 727 light_idea_test_case Unused exported function inspection Unused function <code>UntarUncompressed</code> #loc graphdb.go 63 light_idea_test_case Unused exported function inspection Unused function <code>IsNonUniqueNameError</code> #loc conn_sqlite3.go 9 light_idea_test_case Unused exported function inspection Unused function <code>NewSqliteConn</code> #loc idtools.go 40 light_idea_test_case Unused exported function inspection Unused function <code>MkdirAllAs</code> #loc idtools.go 46 light_idea_test_case Unused exported function inspection Unused function <code>MkdirAs</code> #loc idtools.go 52 light_idea_test_case Unused exported function inspection Unused function <code>GetRootUIDGID</code> #loc idtools.go 75 light_idea_test_case Unused exported function inspection Unused function <code>ToContainer</code> #loc idtools.go 107 light_idea_test_case Unused exported function inspection Unused function <code>CreateIDMappings</code> #loc usergroupadd_unsupported.go 15 light_idea_test_case Unused exported function inspection Unused function <code>AddNamespaceRangesUser</code> #loc fmt.go 17 light_idea_test_case Unused exported function inspection Unused function <code>FprintfIfTrue</code> #loc temp_unix.go 8 light_idea_test_case Unused exported function inspection Unused function <code>TempDir</code> #loc writeflusher.go 84 light_idea_test_case Unused exported function inspection Unused function <code>NewWriteFlusher</code> #loc kernel.go 50 light_idea_test_case Unused exported function inspection Unused function <code>GetKernelVersion</code> #loc parsers.go 125 light_idea_test_case Unused exported function inspection Unused function <code>PartParser</code> #loc plugins.go 165 light_idea_test_case Unused exported function inspection Unused function <code>Get</code> #loc plugins.go 180 light_idea_test_case Unused exported function inspection Unused function <code>Handle</code> #loc promise.go 5 light_idea_test_case Unused exported function inspection Unused function <code>Go</code> #loc tcp_socket.go 19 light_idea_test_case Unused exported function inspection Unused function <code>NewTCPSocket</code> #loc tcp_socket.go 35 light_idea_test_case Unused exported function inspection Unused function <code>ConfigureTCPTransport</code> #loc fs.go 141 light_idea_test_case Unused exported function inspection Unused function <code>EvalSymlinks</code> #loc urlutil.go 39 light_idea_test_case Unused exported function inspection Unused function <code>IsTransportURL</code> #loc stringid.go 65 light_idea_test_case Unused exported function inspection Unused function <code>GenerateNonCryptoID</code> #loc backends.go 24 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc backends.go 45 light_idea_test_case Unused exported function inspection Unused function <code>ParseAdvertise</code> #loc backends.go 102 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc config.go 90 light_idea_test_case Unused exported function inspection Unused function <code>Client</code> #loc config.go 113 light_idea_test_case Unused exported function inspection Unused function <code>Server</code> #loc buffered.go 33 light_idea_test_case Unused exported function inspection Unused function <code>NewBuffered</code> #loc utils.go 336 light_idea_test_case Unused exported function inspection Unused function <code>RunAtDifferentDate</code> #loc diff.go 17 light_idea_test_case Unused exported function inspection Unused function <code>ApplyUncompressedLayer</code> #loc archive.go 27 light_idea_test_case Unused exported function inspection Unused function <code>UntarUncompressed</code> #loc opts.go 354 light_idea_test_case Unused exported function inspection Unused function <code>ValidateHost</code> #loc image.go 77 light_idea_test_case Unused exported function inspection Unused function <code>ValidateID</code> #loc git.go 19 light_idea_test_case Unused exported function inspection Unused function <code>GitClone</code> #loc stubs.go 7 light_idea_test_case Unused exported function inspection Unused function <code>ExperimentalBuild</code> #loc utils.go 84 light_idea_test_case Unused exported function inspection Unused function <code>DockerInitPath</code> #loc utils.go 129 light_idea_test_case Unused exported function inspection Unused function <code>TestDirectory</code> #loc utils.go 202 light_idea_test_case Unused exported function inspection Unused function <code>ValidateContextDirectory</code> #loc utils.go 293 light_idea_test_case Unused exported function inspection Unused function <code>GetErrorMessage</code> #loc timeout.go 9 light_idea_test_case Unused exported function inspection Unused function <code>IsTimeout</code> #loc filter.go 16 light_idea_test_case Unused exported function inspection Unused function <code>NewFilter</code> #loc logger.go 64 light_idea_test_case Unused exported function inspection Unused function <code>NewLogWatcher</code> #loc factory.go 66 light_idea_test_case Unused exported function inspection Unused function <code>RegisterLogDriver</code> #loc factory.go 72 light_idea_test_case Unused exported function inspection Unused function <code>RegisterLogOptValidator</code> #loc factory.go 77 light_idea_test_case Unused exported function inspection Unused function <code>GetLogDriver</code> #loc factory.go 83 light_idea_test_case Unused exported function inspection Unused function <code>ValidateLogOpts</code> #loc daemon.go 605 light_idea_test_case Unused exported function inspection Unused function <code>NewDaemon</code> #loc default_template.go 13 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc driver_unsupported.go 12 light_idea_test_case Unused exported function inspection Unused function <code>NewDriver</code> #loc unsupported.go 12 light_idea_test_case Unused exported function inspection Unused function <code>NewDriver</code> #loc pipes.go 15 light_idea_test_case Unused exported function inspection Unused function <code>NewPipes</code> #loc utils.go 51 light_idea_test_case Unused exported function inspection Unused function <code>GetCapability</code> #loc utils.go 72 light_idea_test_case Unused exported function inspection Unused function <code>TweakCapabilities</code> #loc driver_unix.go 32 light_idea_test_case Unused exported function inspection Unused function <code>InitContainer</code> #loc driver_unix.go 64 light_idea_test_case Unused exported function inspection Unused function <code>SetupCgroups</code> #loc driver_unix.go 128 light_idea_test_case Unused exported function inspection Unused function <code>Stats</code> #loc termconsole.go 15 light_idea_test_case Unused exported function inspection Unused function <code>NewStdConsole</code> #loc driver.go 102 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc driver.go 133 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc graphtest.go 29 light_idea_test_case Unused exported function inspection Unused function <code>InitLoopbacks</code> #loc graphtest.go 174 light_idea_test_case Unused exported function inspection Unused function <code>DriverTestCreateEmpty</code> #loc graphtest.go 265 light_idea_test_case Unused exported function inspection Unused function <code>DriverTestCreateBase</code> #loc graphtest.go 278 light_idea_test_case Unused exported function inspection Unused function <code>DriverTestCreateSnap</code> #loc driver_unsupported.go 13 light_idea_test_case Unused exported function inspection Unused function <code>GetFSMagic</code> #loc builder.go 208 light_idea_test_case Unused exported function inspection Unused function <code>DetectContextFromRemoteURL</code> #loc kqueue.go 43 light_idea_test_case Unused exported function inspection Unused function <code>NewWatcher</code> #loc run.go 12 light_idea_test_case Unused exported function inspection Unused function <code>Start</code> #loc util.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Getsize</code> #loc ed25519.go 27 light_idea_test_case Unused exported function inspection Unused function <code>GenerateKey</code> #loc ed25519.go 54 light_idea_test_case Unused exported function inspection Unused function <code>Sign</code> #loc ed25519.go 97 light_idea_test_case Unused exported function inspection Unused function <code>Verify</code> #loc edwards25519.go 1234 light_idea_test_case Unused exported function inspection Unused function <code>GeDoubleScalarMultVartime</code> #loc edwards25519.go 1324 light_idea_test_case Unused exported function inspection Unused function <code>GeScalarMultBase</code> #loc edwards25519.go 1380 light_idea_test_case Unused exported function inspection Unused function <code>ScMulAdd</code> #loc edwards25519.go 1811 light_idea_test_case Unused exported function inspection Unused function <code>ScReduce</code> #loc error.go 49 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc error.go 103 light_idea_test_case Unused exported function inspection Unused function <code>NewRequestFailure</code> #loc copy.go 14 light_idea_test_case Unused exported function inspection Unused function <code>Copy</code> #loc copy.go 25 light_idea_test_case Unused exported function inspection Unused function <code>CopyOf</code> #loc prettify.go 12 light_idea_test_case Unused exported function inspection Unused function <code>Prettify</code> #loc path_value.go 146 light_idea_test_case Unused exported function inspection Unused function <code>ValuesAtPath</code> #loc path_value.go 159 light_idea_test_case Unused exported function inspection Unused function <code>ValuesAtAnyPath</code> #loc path_value.go 171 light_idea_test_case Unused exported function inspection Unused function <code>SetValueAtPath</code> #loc path_value.go 181 light_idea_test_case Unused exported function inspection Unused function <code>SetValueAtAnyPath</code> #loc types.go 8 light_idea_test_case Unused exported function inspection Unused function <code>ReadSeekCloser</code> #loc logger.go 14 light_idea_test_case Unused exported function inspection Unused function <code>LogLevel</code> #loc service.go 36 light_idea_test_case Unused exported function inspection Unused function <code>NewService</code> #loc convutil.go 6 light_idea_test_case Unused exported function inspection Unused function <code>String</code> #loc convutil.go 21 light_idea_test_case Unused exported function inspection Unused function <code>StringSlice</code> #loc convutil.go 31 light_idea_test_case Unused exported function inspection Unused function <code>StringValueSlice</code> #loc convutil.go 43 light_idea_test_case Unused exported function inspection Unused function <code>StringMap</code> #loc convutil.go 54 light_idea_test_case Unused exported function inspection Unused function <code>StringValueMap</code> #loc convutil.go 80 light_idea_test_case Unused exported function inspection Unused function <code>BoolSlice</code> #loc convutil.go 90 light_idea_test_case Unused exported function inspection Unused function <code>BoolValueSlice</code> #loc convutil.go 102 light_idea_test_case Unused exported function inspection Unused function <code>BoolMap</code> #loc convutil.go 113 light_idea_test_case Unused exported function inspection Unused function <code>BoolValueMap</code> #loc convutil.go 124 light_idea_test_case Unused exported function inspection Unused function <code>Int</code> #loc convutil.go 139 light_idea_test_case Unused exported function inspection Unused function <code>IntSlice</code> #loc convutil.go 149 light_idea_test_case Unused exported function inspection Unused function <code>IntValueSlice</code> #loc convutil.go 161 light_idea_test_case Unused exported function inspection Unused function <code>IntMap</code> #loc convutil.go 172 light_idea_test_case Unused exported function inspection Unused function <code>IntValueMap</code> #loc convutil.go 183 light_idea_test_case Unused exported function inspection Unused function <code>Int64</code> #loc convutil.go 189 light_idea_test_case Unused exported function inspection Unused function <code>Int64Value</code> #loc convutil.go 198 light_idea_test_case Unused exported function inspection Unused function <code>Int64Slice</code> #loc convutil.go 208 light_idea_test_case Unused exported function inspection Unused function <code>Int64ValueSlice</code> #loc convutil.go 220 light_idea_test_case Unused exported function inspection Unused function <code>Int64Map</code> #loc convutil.go 231 light_idea_test_case Unused exported function inspection Unused function <code>Int64ValueMap</code> #loc convutil.go 242 light_idea_test_case Unused exported function inspection Unused function <code>Float64</code> #loc convutil.go 248 light_idea_test_case Unused exported function inspection Unused function <code>Float64Value</code> #loc convutil.go 257 light_idea_test_case Unused exported function inspection Unused function <code>Float64Slice</code> #loc convutil.go 267 light_idea_test_case Unused exported function inspection Unused function <code>Float64ValueSlice</code> #loc convutil.go 279 light_idea_test_case Unused exported function inspection Unused function <code>Float64Map</code> #loc convutil.go 290 light_idea_test_case Unused exported function inspection Unused function <code>Float64ValueMap</code> #loc convutil.go 301 light_idea_test_case Unused exported function inspection Unused function <code>Time</code> #loc convutil.go 307 light_idea_test_case Unused exported function inspection Unused function <code>TimeValue</code> #loc convutil.go 316 light_idea_test_case Unused exported function inspection Unused function <code>TimeSlice</code> #loc convutil.go 326 light_idea_test_case Unused exported function inspection Unused function <code>TimeValueSlice</code> #loc convutil.go 338 light_idea_test_case Unused exported function inspection Unused function <code>TimeMap</code> #loc convutil.go 349 light_idea_test_case Unused exported function inspection Unused function <code>TimeValueMap</code> #loc env_provider.go 36 light_idea_test_case Unused exported function inspection Unused function <code>NewEnvCredentials</code> #loc chain_provider.go 52 light_idea_test_case Unused exported function inspection Unused function <code>NewChainCredentials</code> #loc ec2_role_provider.go 67 light_idea_test_case Unused exported function inspection Unused function <code>NewEC2RoleCredentials</code> #loc shared_credentials_provider.go 40 light_idea_test_case Unused exported function inspection Unused function <code>NewSharedCredentials</code> #loc service.go 54 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc v4.go 66 light_idea_test_case Unused exported function inspection Unused function <code>Sign</code> #loc build.go 16 light_idea_test_case Unused exported function inspection Unused function <code>BuildJSON</code> #loc unmarshal.go 15 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalJSON</code> #loc build.go 40 light_idea_test_case Unused exported function inspection Unused function <code>Build</code> #loc payload.go 6 light_idea_test_case Unused exported function inspection Unused function <code>PayloadMember</code> #loc payload.go 32 light_idea_test_case Unused exported function inspection Unused function <code>PayloadType</code> #loc unmarshal.go 18 light_idea_test_case Unused exported function inspection Unused function <code>Unmarshal</code> #loc jsonrpc.go 21 light_idea_test_case Unused exported function inspection Unused function <code>Build</code> #loc jsonrpc.go 49 light_idea_test_case Unused exported function inspection Unused function <code>Unmarshal</code> #loc jsonrpc.go 61 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalMeta</code> #loc jsonrpc.go 66 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalError</code> #loc endpoints.go 11 light_idea_test_case Unused exported function inspection Unused function <code>EndpointForRegion</code> #loc inmem.go 119 light_idea_test_case Unused exported function inspection Unused function <code>NewInmemSink</code> #loc start.go 36 light_idea_test_case Unused exported function inspection Unused function <code>DefaultConfig</code> #loc start.go 68 light_idea_test_case Unused exported function inspection Unused function <code>NewGlobal</code> #loc start.go 77 light_idea_test_case Unused exported function inspection Unused function <code>SetGauge</code> #loc start.go 81 light_idea_test_case Unused exported function inspection Unused function <code>EmitKey</code> #loc start.go 85 light_idea_test_case Unused exported function inspection Unused function <code>IncrCounter</code> #loc start.go 89 light_idea_test_case Unused exported function inspection Unused function <code>AddSample</code> #loc start.go 93 light_idea_test_case Unused exported function inspection Unused function <code>MeasureSince</code> #loc statsd.go 27 light_idea_test_case Unused exported function inspection Unused function <code>NewStatsdSink</code> #loc statsite.go 27 light_idea_test_case Unused exported function inspection Unused function <code>NewStatsiteSink</code> #loc inmem_signal.go 43 light_idea_test_case Unused exported function inspection Unused function <code>DefaultInmemSignal</code> #loc sqlite3.go 105 light_idea_test_case Unused exported function inspection Unused function <code>Version</code> #loc patricia.go 64 light_idea_test_case Unused exported function inspection Unused function <code>MaxPrefixPerNode</code> #loc patricia.go 70 light_idea_test_case Unused exported function inspection Unused function <code>MaxChildrenPerSparseNode</code> #loc db.go 97 light_idea_test_case Unused exported function inspection Unused function <code>Open</code> #loc id.go 31 light_idea_test_case Unused exported function inspection Unused function <code>IDFromString</code> #loc set.go 42 light_idea_test_case Unused exported function inspection Unused function <code>NewThreadsafeSet</code> #loc urlsmap.go 29 light_idea_test_case Unused exported function inspection Unused function <code>NewURLsMap</code> #loc path.go 15 light_idea_test_case Unused exported function inspection Unused function <code>CanonicalURLPath</code> #loc srv.go 31 light_idea_test_case Unused exported function inspection Unused function <code>NewSRVDiscover</code> #loc curl.go 29 light_idea_test_case Unused exported function inspection Unused function <code>EnablecURLDebug</code> #loc curl.go 33 light_idea_test_case Unused exported function inspection Unused function <code>DisablecURLDebug</code> #loc keys.go 89 light_idea_test_case Unused exported function inspection Unused function <code>NewKeysAPI</code> #loc client.go 168 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc auth_role.go 52 light_idea_test_case Unused exported function inspection Unused function <code>NewAuthRoleAPI</code> #loc auth_user.go 50 light_idea_test_case Unused exported function inspection Unused function <code>NewAuthAPI</code> #loc auth_user.go 113 light_idea_test_case Unused exported function inspection Unused function <code>NewAuthUserAPI</code> #loc dbus.go 88 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc dbus.go 95 light_idea_test_case Unused exported function inspection Unused function <code>NewUserConnection</code> #loc properties.go 57 light_idea_test_case Unused exported function inspection Unused function <code>PropExecStart</code> #loc properties.go 74 light_idea_test_case Unused exported function inspection Unused function <code>PropRemainAfterExit</code> #loc properties.go 83 light_idea_test_case Unused exported function inspection Unused function <code>PropDescription</code> #loc properties.go 99 light_idea_test_case Unused exported function inspection Unused function <code>PropRequires</code> #loc properties.go 105 light_idea_test_case Unused exported function inspection Unused function <code>PropRequiresOverridable</code> #loc properties.go 111 light_idea_test_case Unused exported function inspection Unused function <code>PropRequisite</code> #loc properties.go 117 light_idea_test_case Unused exported function inspection Unused function <code>PropRequisiteOverridable</code> #loc properties.go 123 light_idea_test_case Unused exported function inspection Unused function <code>PropWants</code> #loc properties.go 129 light_idea_test_case Unused exported function inspection Unused function <code>PropBindsTo</code> #loc properties.go 135 light_idea_test_case Unused exported function inspection Unused function <code>PropRequiredBy</code> #loc properties.go 141 light_idea_test_case Unused exported function inspection Unused function <code>PropRequiredByOverridable</code> #loc properties.go 147 light_idea_test_case Unused exported function inspection Unused function <code>PropWantedBy</code> #loc properties.go 153 light_idea_test_case Unused exported function inspection Unused function <code>PropBoundBy</code> #loc properties.go 159 light_idea_test_case Unused exported function inspection Unused function <code>PropConflicts</code> #loc properties.go 165 light_idea_test_case Unused exported function inspection Unused function <code>PropConflictedBy</code> #loc properties.go 171 light_idea_test_case Unused exported function inspection Unused function <code>PropBefore</code> #loc properties.go 177 light_idea_test_case Unused exported function inspection Unused function <code>PropAfter</code> #loc properties.go 183 light_idea_test_case Unused exported function inspection Unused function <code>PropOnFailure</code> #loc properties.go 189 light_idea_test_case Unused exported function inspection Unused function <code>PropTriggers</code> #loc properties.go 195 light_idea_test_case Unused exported function inspection Unused function <code>PropTriggeredBy</code> #loc properties.go 201 light_idea_test_case Unused exported function inspection Unused function <code>PropPropagatesReloadTo</code> #loc properties.go 207 light_idea_test_case Unused exported function inspection Unused function <code>PropRequiresMountsFor</code> #loc properties.go 213 light_idea_test_case Unused exported function inspection Unused function <code>PropSlice</code> #loc util.go 27 light_idea_test_case Unused exported function inspection Unused function <code>IsRunningSystemd</code> #loc sdnotify.go 13 light_idea_test_case Unused exported function inspection Unused function <code>SdNotify</code> #loc send.go 57 light_idea_test_case Unused exported function inspection Unused function <code>Enabled</code> #loc send.go 68 light_idea_test_case Unused exported function inspection Unused function <code>Send</code> #loc listeners.go 27 light_idea_test_case Unused exported function inspection Unused function <code>Listeners</code> #loc packetconns.go 27 light_idea_test_case Unused exported function inspection Unused function <code>PacketConns</code> #loc etcd.go 49 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc boltdb.go 54 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc consul.go 51 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc zookeeper.go 34 light_idea_test_case Unused exported function inspection Unused function <code>Register</code> #loc helpers.go 8 light_idea_test_case Unused exported function inspection Unused function <code>CreateEndpoints</code> #loc helpers.go 19 light_idea_test_case Unused exported function inspection Unused function <code>Normalize</code> #loc helpers.go 28 light_idea_test_case Unused exported function inspection Unused function <code>GetDirectory</code> #loc libkv.go 29 light_idea_test_case Unused exported function inspection Unused function <code>NewStore</code> #loc libkv.go 38 light_idea_test_case Unused exported function inspection Unused function <code>AddStore</code> #loc passphrase.go 54 light_idea_test_case Unused exported function inspection Unused function <code>PromptRetriever</code> #loc client.go 86 light_idea_test_case Unused exported function inspection Unused function <code>NewTarget</code> #loc client.go 103 light_idea_test_case Unused exported function inspection Unused function <code>NewNotaryRepository</code> #loc change.go 46 light_idea_test_case Unused exported function inspection Unused function <code>NewTufChange</code> #loc changelist.go 9 light_idea_test_case Unused exported function inspection Unused function <code>NewMemChangelist</code> #loc file_changelist.go 22 light_idea_test_case Unused exported function inspection Unused function <code>NewFileChangelist</code> #loc x509store.go 91 light_idea_test_case Unused exported function inspection Unused function <code>Verify</code> #loc x509utils.go 27 light_idea_test_case Unused exported function inspection Unused function <code>GetCertFromURL</code> #loc x509utils.go 92 light_idea_test_case Unused exported function inspection Unused function <code>FingerprintCert</code> #loc x509utils.go 195 light_idea_test_case Unused exported function inspection Unused function <code>GetLeafCerts</code> #loc x509utils.go 208 light_idea_test_case Unused exported function inspection Unused function <code>GetIntermediateCerts</code> #loc x509utils.go 303 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRSAKey</code> #loc x509utils.go 334 light_idea_test_case Unused exported function inspection Unused function <code>GenerateECDSAKey</code> #loc x509utils.go 353 light_idea_test_case Unused exported function inspection Unused function <code>GenerateED25519Key</code> #loc x509utils.go 448 light_idea_test_case Unused exported function inspection Unused function <code>CertsToKeys</code> #loc x509utils.go 473 light_idea_test_case Unused exported function inspection Unused function <code>NewCertificate</code> #loc keyfilestore.go 30 light_idea_test_case Unused exported function inspection Unused function <code>NewKeyFileStore</code> #loc keyfilestore.go 71 light_idea_test_case Unused exported function inspection Unused function <code>NewKeyMemoryStore</code> #loc x509memstore.go 18 light_idea_test_case Unused exported function inspection Unused function <code>NewX509MemStore</code> #loc x509memstore.go 30 light_idea_test_case Unused exported function inspection Unused function <code>NewX509FilteredMemStore</code> #loc x509filestore.go 22 light_idea_test_case Unused exported function inspection Unused function <code>NewX509FileStore</code> #loc x509filestore.go 29 light_idea_test_case Unused exported function inspection Unused function <code>NewX509FilteredFileStore</code> #loc crypto_service.go 31 light_idea_test_case Unused exported function inspection Unused function <code>NewCryptoService</code> #loc unlocked_crypto_service.go 25 light_idea_test_case Unused exported function inspection Unused function <code>NewUnlockedCryptoService</code> #loc keystoremanager.go 64 light_idea_test_case Unused exported function inspection Unused function <code>NewKeyStoreManager</code> #loc key.go 85 light_idea_test_case Unused exported function inspection Unused function <code>FromCryptoPrivateKey</code> #loc util.go 55 light_idea_test_case Unused exported function inspection Unused function <code>NewIdentityAuthTLSClientConfig</code> #loc ec_key.go 405 light_idea_test_case Unused exported function inspection Unused function <code>GenerateECP384PrivateKey</code> #loc ec_key.go 418 light_idea_test_case Unused exported function inspection Unused function <code>GenerateECP521PrivateKey</code> #loc rsa_key.go 400 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRSA2048PrivateKey</code> #loc rsa_key.go 410 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRSA3072PrivateKey</code> #loc rsa_key.go 420 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRSA4096PrivateKey</code> #loc jsonsign.go 325 light_idea_test_case Unused exported function inspection Unused function <code>ParseJWS</code> #loc jsonsign.go 441 light_idea_test_case Unused exported function inspection Unused function <code>NewJSONSignatureFromMap</code> #loc jsonsign.go 493 light_idea_test_case Unused exported function inspection Unused function <code>ParsePrettySignature</code> #loc key_manager.go 29 light_idea_test_case Unused exported function inspection Unused function <code>NewClientKeyManager</code> #loc key_manager.go 97 light_idea_test_case Unused exported function inspection Unused function <code>NewIdentityAuthTLSConfig</code> #loc key_manager.go 127 light_idea_test_case Unused exported function inspection Unused function <code>NewCertAuthTLSConfig</code> #loc certificates.go 165 light_idea_test_case Unused exported function inspection Unused function <code>LoadCertificatePool</code> #loc idm.go 19 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc sandbox_unsupported.go 14 light_idea_test_case Unused exported function inspection Unused function <code>NewSandbox</code> #loc sandbox_unsupported.go 20 light_idea_test_case Unused exported function inspection Unused function <code>GenerateKey</code> #loc namespace_unsupported.go 7 light_idea_test_case Unused exported function inspection Unused function <code>GC</code> #loc namespace_unsupported.go 10 light_idea_test_case Unused exported function inspection Unused function <code>GetSandboxForExternalKey</code> #loc allocator.go 39 light_idea_test_case Unused exported function inspection Unused function <code>NewAllocator</code> #loc remote.go 31 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc builtin.go 12 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc types.go 248 light_idea_test_case Unused exported function inspection Unused function <code>GetMacCopy</code> #loc types.go 278 light_idea_test_case Unused exported function inspection Unused function <code>GetIPNetCanonical</code> #loc types.go 288 light_idea_test_case Unused exported function inspection Unused function <code>CompareIPNet</code> #loc types.go 299 light_idea_test_case Unused exported function inspection Unused function <code>GetMinimalIP</code> #loc types.go 307 light_idea_test_case Unused exported function inspection Unused function <code>GetMinimalIPNet</code> #loc types.go 344 light_idea_test_case Unused exported function inspection Unused function <code>GetHostPartIP</code> #loc types.go 363 light_idea_test_case Unused exported function inspection Unused function <code>GetBroadcastIP</code> #loc types.go 380 light_idea_test_case Unused exported function inspection Unused function <code>ParseCIDR</code> #loc types.go 501 light_idea_test_case Unused exported function inspection Unused function <code>NotFoundErrorf</code> #loc types.go 506 light_idea_test_case Unused exported function inspection Unused function <code>ForbiddenErrorf</code> #loc types.go 511 light_idea_test_case Unused exported function inspection Unused function <code>NoServiceErrorf</code> #loc types.go 516 light_idea_test_case Unused exported function inspection Unused function <code>NotImplementedErrorf</code> #loc types.go 521 light_idea_test_case Unused exported function inspection Unused function <code>TimeoutErrorf</code> #loc types.go 526 light_idea_test_case Unused exported function inspection Unused function <code>InternalErrorf</code> #loc types.go 531 light_idea_test_case Unused exported function inspection Unused function <code>InternalMaskableErrorf</code> #loc types.go 536 light_idea_test_case Unused exported function inspection Unused function <code>RetryErrorf</code> #loc sequence.go 44 light_idea_test_case Unused exported function inspection Unused function <code>NewHandle</code> #loc config.go 51 light_idea_test_case Unused exported function inspection Unused function <code>ParseConfig</code> #loc config.go 69 light_idea_test_case Unused exported function inspection Unused function <code>OptionDefaultNetwork</code> #loc config.go 77 light_idea_test_case Unused exported function inspection Unused function <code>OptionDefaultDriver</code> #loc config.go 85 light_idea_test_case Unused exported function inspection Unused function <code>OptionDriverConfig</code> #loc config.go 92 light_idea_test_case Unused exported function inspection Unused function <code>OptionLabels</code> #loc config.go 103 light_idea_test_case Unused exported function inspection Unused function <code>OptionKVProvider</code> #loc config.go 114 light_idea_test_case Unused exported function inspection Unused function <code>OptionKVProviderURL</code> #loc config.go 125 light_idea_test_case Unused exported function inspection Unused function <code>OptionKVOpts</code> #loc config.go 159 light_idea_test_case Unused exported function inspection Unused function <code>OptionDiscoveryWatcher</code> #loc config.go 166 light_idea_test_case Unused exported function inspection Unused function <code>OptionDiscoveryAddress</code> #loc config.go 173 light_idea_test_case Unused exported function inspection Unused function <code>OptionDataDir</code> #loc config.go 189 light_idea_test_case Unused exported function inspection Unused function <code>IsValidName</code> #loc config.go 197 light_idea_test_case Unused exported function inspection Unused function <code>OptionLocalKVProvider</code> #loc config.go 208 light_idea_test_case Unused exported function inspection Unused function <code>OptionLocalKVProviderURL</code> #loc config.go 219 light_idea_test_case Unused exported function inspection Unused function <code>OptionLocalKVProviderConfig</code> #loc host.go 19 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc null.go 19 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc bridge.go 120 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc driver.go 30 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc overlay.go 46 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc overlay.go 63 light_idea_test_case Unused exported function inspection Unused function <code>Fini</code> #loc windows.go 15 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc options.go 48 light_idea_test_case Unused exported function inspection Unused function <code>NewGeneric</code> #loc options.go 58 light_idea_test_case Unused exported function inspection Unused function <code>GenerateFromModel</code> #loc etchosts.go 61 light_idea_test_case Unused exported function inspection Unused function <code>Drop</code> #loc etchosts.go 72 light_idea_test_case Unused exported function inspection Unused function <code>Build</code> #loc etchosts.go 106 light_idea_test_case Unused exported function inspection Unused function <code>Add</code> #loc etchosts.go 135 light_idea_test_case Unused exported function inspection Unused function <code>Delete</code> #loc etchosts.go 160 light_idea_test_case Unused exported function inspection Unused function <code>Update</code> #loc iptables.go 76 light_idea_test_case Unused exported function inspection Unused function <code>NewChain</code> #loc iptables.go 98 light_idea_test_case Unused exported function inspection Unused function <code>ProgramChain</code> #loc iptables.go 147 light_idea_test_case Unused exported function inspection Unused function <code>RemoveExistingChain</code> #loc firewalld.go 41 light_idea_test_case Unused exported function inspection Unused function <code>FirewalldInit</code> #loc firewalld.go 134 light_idea_test_case Unused exported function inspection Unused function <code>OnReloaded</code> #loc labels.go 82 light_idea_test_case Unused exported function inspection Unused function <code>Key</code> #loc labels.go 90 light_idea_test_case Unused exported function inspection Unused function <code>Value</code> #loc labels.go 98 light_idea_test_case Unused exported function inspection Unused function <code>KeyValue</code> #loc utils.go 30 light_idea_test_case Unused exported function inspection Unused function <code>CheckNameserverOverlaps</code> #loc utils.go 46 light_idea_test_case Unused exported function inspection Unused function <code>CheckRouteOverlaps</code> #loc utils.go 66 light_idea_test_case Unused exported function inspection Unused function <code>NetworkRange</code> #loc utils.go 86 light_idea_test_case Unused exported function inspection Unused function <code>GetIfaceAddr</code> #loc utils.go 135 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRandomMAC</code> #loc utils.go 141 light_idea_test_case Unused exported function inspection Unused function <code>GenerateMACFromIP</code> #loc utils.go 158 light_idea_test_case Unused exported function inspection Unused function <code>GenerateIfaceName</code> #loc datastore.go 158 light_idea_test_case Unused exported function inspection Unused function <code>DefaultScopes</code> #loc datastore.go 187 light_idea_test_case Unused exported function inspection Unused function <code>ParseKey</code> #loc datastore.go 238 light_idea_test_case Unused exported function inspection Unused function <code>NewDataStore</code> #loc mock_store.go 27 light_idea_test_case Unused exported function inspection Unused function <code>NewMockStore</code> #loc network.go 475 light_idea_test_case Unused exported function inspection Unused function <code>NetworkOptionPersist</code> #loc network.go 482 light_idea_test_case Unused exported function inspection Unused function <code>NetworkOptionIpam</code> #loc network.go 494 light_idea_test_case Unused exported function inspection Unused function <code>NetworkOptionDriverOpts</code> #loc network.go 518 light_idea_test_case Unused exported function inspection Unused function <code>NetworkOptionDeferIPv6Alloc</code> #loc mapper.go 45 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc resolvconf.go 15 light_idea_test_case Unused exported function inspection Unused function <code>IsLocalhost</code> #loc resolvconf.go 49 light_idea_test_case Unused exported function inspection Unused function <code>Get</code> #loc resolvconf.go 62 light_idea_test_case Unused exported function inspection Unused function <code>GetSpecific</code> #loc resolvconf.go 77 light_idea_test_case Unused exported function inspection Unused function <code>GetIfChanged</code> #loc resolvconf.go 100 light_idea_test_case Unused exported function inspection Unused function <code>GetLastModified</code> #loc resolvconf.go 114 light_idea_test_case Unused exported function inspection Unused function <code>FilterResolvDNS</code> #loc resolvconf.go 168 light_idea_test_case Unused exported function inspection Unused function <code>GetNameserversAsCIDR</code> #loc resolvconf.go 179 light_idea_test_case Unused exported function inspection Unused function <code>GetSearchDomains</code> #loc resolvconf.go 194 light_idea_test_case Unused exported function inspection Unused function <code>GetOptions</code> #loc resolvconf.go 209 light_idea_test_case Unused exported function inspection Unused function <code>Build</code> #loc sandbox.go 845 light_idea_test_case Unused exported function inspection Unused function <code>OptionHostname</code> #loc sandbox.go 853 light_idea_test_case Unused exported function inspection Unused function <code>OptionDomainname</code> #loc sandbox.go 861 light_idea_test_case Unused exported function inspection Unused function <code>OptionHostsPath</code> #loc sandbox.go 869 light_idea_test_case Unused exported function inspection Unused function <code>OptionOriginHostsPath</code> #loc sandbox.go 877 light_idea_test_case Unused exported function inspection Unused function <code>OptionExtraHost</code> #loc sandbox.go 885 light_idea_test_case Unused exported function inspection Unused function <code>OptionParentUpdate</code> #loc sandbox.go 893 light_idea_test_case Unused exported function inspection Unused function <code>OptionResolvConfPath</code> #loc sandbox.go 901 light_idea_test_case Unused exported function inspection Unused function <code>OptionOriginResolvConfPath</code> #loc sandbox.go 909 light_idea_test_case Unused exported function inspection Unused function <code>OptionDNS</code> #loc sandbox.go 917 light_idea_test_case Unused exported function inspection Unused function <code>OptionDNSSearch</code> #loc sandbox.go 925 light_idea_test_case Unused exported function inspection Unused function <code>OptionDNSOptions</code> #loc sandbox.go 933 light_idea_test_case Unused exported function inspection Unused function <code>OptionUseDefaultSandbox</code> #loc sandbox.go 941 light_idea_test_case Unused exported function inspection Unused function <code>OptionUseExternalKey</code> #loc sandbox.go 950 light_idea_test_case Unused exported function inspection Unused function <code>OptionGeneric</code> #loc endpoint.go 680 light_idea_test_case Unused exported function inspection Unused function <code>EndpointOptionGeneric</code> #loc endpoint.go 722 light_idea_test_case Unused exported function inspection Unused function <code>JoinOptionPriority</code> #loc controller.go 153 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc controller.go 630 light_idea_test_case Unused exported function inspection Unused function <code>SandboxKeyWalker</code> #loc hostdiscovery.go 33 light_idea_test_case Unused exported function inspection Unused function <code>NewHostDiscovery</code> #loc portallocator.go 87 light_idea_test_case Unused exported function inspection Unused function <code>Get</code> #loc uuid.go 40 light_idea_test_case Unused exported function inspection Unused function <code>Generate</code> #loc uuid.go 87 light_idea_test_case Unused exported function inspection Unused function <code>Parse</code> #loc set.go 35 light_idea_test_case Unused exported function inspection Unused function <code>NewSet</code> #loc set.go 138 light_idea_test_case Unused exported function inspection Unused function <code>ShortCodeTable</code> #loc digest.go 47 light_idea_test_case Unused exported function inspection Unused function <code>NewDigestFromHex</code> #loc digest.go 85 light_idea_test_case Unused exported function inspection Unused function <code>FromTarArchive</code> #loc digest.go 104 light_idea_test_case Unused exported function inspection Unused function <code>FromBytes</code> #loc verifiers.go 25 light_idea_test_case Unused exported function inspection Unused function <code>NewDigestVerifier</code> #loc verifiers.go 75 light_idea_test_case Unused exported function inspection Unused function <code>NewLengthVerifier</code> #loc http.go 55 light_idea_test_case Unused exported function inspection Unused function <code>RemoteIP</code> #loc http.go 71 light_idea_test_case Unused exported function inspection Unused function <code>WithRequest</code> #loc http.go 90 light_idea_test_case Unused exported function inspection Unused function <code>GetRequest</code> #loc http.go 99 light_idea_test_case Unused exported function inspection Unused function <code>GetRequestID</code> #loc http.go 105 light_idea_test_case Unused exported function inspection Unused function <code>WithResponseWriter</code> #loc http.go 117 light_idea_test_case Unused exported function inspection Unused function <code>GetResponseWriter</code> #loc http.go 137 light_idea_test_case Unused exported function inspection Unused function <code>WithVars</code> #loc http.go 147 light_idea_test_case Unused exported function inspection Unused function <code>GetRequestLogger</code> #loc http.go 163 light_idea_test_case Unused exported function inspection Unused function <code>GetResponseLogger</code> #loc trace.go 39 light_idea_test_case Unused exported function inspection Unused function <code>WithTrace</code> #loc logger.go 43 light_idea_test_case Unused exported function inspection Unused function <code>WithLogger</code> #loc logger.go 50 light_idea_test_case Unused exported function inspection Unused function <code>GetLoggerWithField</code> #loc logger.go 57 light_idea_test_case Unused exported function inspection Unused function <code>GetLoggerWithFields</code> #loc context.go 65 light_idea_test_case Unused exported function inspection Unused function <code>WithValues</code> #loc sign.go 13 light_idea_test_case Unused exported function inspection Unused function <code>Sign</code> #loc sign.go 42 light_idea_test_case Unused exported function inspection Unused function <code>SignWithChain</code> #loc verify.go 12 light_idea_test_case Unused exported function inspection Unused function <code>Verify</code> #loc verify.go 25 light_idea_test_case Unused exported function inspection Unused function <code>VerifyChains</code> #loc urls.go 35 light_idea_test_case Unused exported function inspection Unused function <code>NewURLBuilderFromString</code> #loc urls.go 46 light_idea_test_case Unused exported function inspection Unused function <code>NewURLBuilderFromRequest</code> #loc names.go 78 light_idea_test_case Unused exported function inspection Unused function <code>ValidateRepositoryName</code> #loc errors.go 157 light_idea_test_case Unused exported function inspection Unused function <code>ParseErrorCode</code> #loc handler.go 11 light_idea_test_case Unused exported function inspection Unused function <code>ServeJSON</code> #loc register.go 78 light_idea_test_case Unused exported function inspection Unused function <code>GetErrorAllDescriptors</code> #loc session.go 40 light_idea_test_case Unused exported function inspection Unused function <code>NewAuthorizer</code> #loc session.go 113 light_idea_test_case Unused exported function inspection Unused function <code>NewTokenHandler</code> #loc session.go 237 light_idea_test_case Unused exported function inspection Unused function <code>NewBasicHandler</code> #loc api_version.go 28 light_idea_test_case Unused exported function inspection Unused function <code>APIVersions</code> #loc authchallenge.go 45 light_idea_test_case Unused exported function inspection Unused function <code>NewSimpleChallengeManager</code> #loc transport.go 19 light_idea_test_case Unused exported function inspection Unused function <code>NewHeaderRequestModifier</code> #loc transport.go 33 light_idea_test_case Unused exported function inspection Unused function <code>NewTransport</code> #loc http_reader.go 24 light_idea_test_case Unused exported function inspection Unused function <code>NewHTTPReadSeeker</code> #loc repository.go 30 light_idea_test_case Unused exported function inspection Unused function <code>NewRegistry</code> #loc repository.go 100 light_idea_test_case Unused exported function inspection Unused function <code>NewRepository</code> #loc repository.go 255 light_idea_test_case Unused exported function inspection Unused function <code>AddEtagToTag</code> #loc memory.go 21 light_idea_test_case Unused exported function inspection Unused function <code>NewInMemoryBlobDescriptorCacheProvider</code> #loc cache.go 21 light_idea_test_case Unused exported function inspection Unused function <code>ValidateDescriptor</code> #loc suite.go 14 light_idea_test_case Unused exported function inspection Unused function <code>CheckBlobDescriptorCache</code> #loc cachedblobdescriptorstore.go 35 light_idea_test_case Unused exported function inspection Unused function <code>NewCachedBlobStatter</code> #loc cachedblobdescriptorstore.go 44 light_idea_test_case Unused exported function inspection Unused function <code>NewCachedBlobStatterWithMetrics</code> #loc fluent.go 44 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc sig.go 44 light_idea_test_case Unused exported function inspection Unused function <code>SignatureOfType</code> #loc sig.go 130 light_idea_test_case Unused exported function inspection Unused function <code>ParseSignatureMust</code> #loc conn.go 65 light_idea_test_case Unused exported function inspection Unused function <code>SessionBus</code> #loc conn.go 104 light_idea_test_case Unused exported function inspection Unused function <code>SystemBus</code> #loc conn.go 150 light_idea_test_case Unused exported function inspection Unused function <code>NewConn</code> #loc conn.go 514 light_idea_test_case Unused exported function inspection Unused function <code>NewError</code> #loc variant.go 26 light_idea_test_case Unused exported function inspection Unused function <code>ParseVariant</code> #loc lib.go 243 light_idea_test_case Unused exported function inspection Unused function <code>GetStats</code> #loc lib.go 294 light_idea_test_case Unused exported function inspection Unused function <code>Bool</code> #loc lib.go 307 light_idea_test_case Unused exported function inspection Unused function <code>Int</code> #loc lib.go 315 light_idea_test_case Unused exported function inspection Unused function <code>Int64</code> #loc lib.go 321 light_idea_test_case Unused exported function inspection Unused function <code>Float32</code> #loc lib.go 327 light_idea_test_case Unused exported function inspection Unused function <code>Float64</code> #loc lib.go 333 light_idea_test_case Unused exported function inspection Unused function <code>Uint32</code> #loc lib.go 339 light_idea_test_case Unused exported function inspection Unused function <code>Uint64</code> #loc lib.go 345 light_idea_test_case Unused exported function inspection Unused function <code>String</code> #loc lib.go 351 light_idea_test_case Unused exported function inspection Unused function <code>EnumName</code> #loc lib.go 365 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalJSONEnum</code> #loc lib.go 502 light_idea_test_case Unused exported function inspection Unused function <code>SetDefaults</code> #loc text.go 770 light_idea_test_case Unused exported function inspection Unused function <code>MarshalText</code> #loc text.go 775 light_idea_test_case Unused exported function inspection Unused function <code>MarshalTextString</code> #loc text.go 782 light_idea_test_case Unused exported function inspection Unused function <code>CompactText</code> #loc encode.go 261 light_idea_test_case Unused exported function inspection Unused function <code>Size</code> #loc extensions.go 95 light_idea_test_case Unused exported function inspection Unused function <code>SetRawExtension</code> #loc extensions.go 212 light_idea_test_case Unused exported function inspection Unused function <code>HasExtension</code> #loc extensions.go 219 light_idea_test_case Unused exported function inspection Unused function <code>ClearExtension</code> #loc extensions.go 297 light_idea_test_case Unused exported function inspection Unused function <code>GetExtensions</code> #loc extensions.go 344 light_idea_test_case Unused exported function inspection Unused function <code>RegisterExtension</code> #loc properties.go 737 light_idea_test_case Unused exported function inspection Unused function <code>RegisterEnum</code> #loc message_set.go 159 light_idea_test_case Unused exported function inspection Unused function <code>MarshalMessageSet</code> #loc message_set.go 188 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalMessageSet</code> #loc message_set.go 219 light_idea_test_case Unused exported function inspection Unused function <code>MarshalMessageSetJSON</code> #loc message_set.go 262 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalMessageSetJSON</code> #loc message_set.go 282 light_idea_test_case Unused exported function inspection Unused function <code>RegisterMessageSetType</code> #loc text_parser.go 746 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalText</code> #loc flw.go 23 light_idea_test_case Unused exported function inspection Unused function <code>FLWSrvr</code> #loc flw.go 129 light_idea_test_case Unused exported function inspection Unused function <code>FLWRuok</code> #loc flw.go 152 light_idea_test_case Unused exported function inspection Unused function <code>FLWCons</code> #loc lock.go 23 light_idea_test_case Unused exported function inspection Unused function <code>NewLock</code> #loc util.go 15 light_idea_test_case Unused exported function inspection Unused function <code>AuthACL</code> #loc util.go 22 light_idea_test_case Unused exported function inspection Unused function <code>WorldACL</code> #loc util.go 26 light_idea_test_case Unused exported function inspection Unused function <code>DigestACL</code> #loc tracer.go 135 light_idea_test_case Unused exported function inspection Unused function <code>StartTracer</code> #loc server_help.go 24 light_idea_test_case Unused exported function inspection Unused function <code>StartTestCluster</code> #loc enum_gen.go 88 light_idea_test_case Unused exported function inspection Unused function <code>List</code> #loc capability.go 65 light_idea_test_case Unused exported function inspection Unused function <code>NewPid</code> #loc capability.go 70 light_idea_test_case Unused exported function inspection Unused function <code>NewFile</code> #loc gen.go 120 light_idea_test_case Unused exported function inspection Unused function <code>Gen</code> #loc gen.go 1697 light_idea_test_case Unused exported function inspection Unused function <code>GenInternalGoFile</code> #loc noop.go 15 light_idea_test_case Unused exported function inspection Unused function <code>NoopHandle</code> #loc decode.go 928 light_idea_test_case Unused exported function inspection Unused function <code>NewDecoderBytes</code> #loc gen-helper.generated.go 25 light_idea_test_case Unused exported function inspection Unused function <code>GenHelperEncoder</code> #loc gen-helper.generated.go 31 light_idea_test_case Unused exported function inspection Unused function <code>GenHelperDecoder</code> #loc assemble.go 19 light_idea_test_case Unused exported function inspection Unused function <code>NewOutputTarStream</code> #loc disassemble.go 21 light_idea_test_case Unused exported function inspection Unused function <code>NewInputTarStream</code> #loc getter.go 37 light_idea_test_case Unused exported function inspection Unused function <code>NewPathFileGetter</code> #loc getter.go 83 light_idea_test_case Unused exported function inspection Unused function <code>NewBufferFileGetPutter</code> #loc getter.go 90 light_idea_test_case Unused exported function inspection Unused function <code>NewDiscardFilePutter</code> #loc packer.go 79 light_idea_test_case Unused exported function inspection Unused function <code>NewJSONUnpacker</code> #loc packer.go 129 light_idea_test_case Unused exported function inspection Unused function <code>NewJSONPacker</code> #loc common.go 204 light_idea_test_case Unused exported function inspection Unused function <code>FileInfoHeader</code> #loc reader.go 106 light_idea_test_case Unused exported function inspection Unused function <code>NewReader</code> #loc writer.go 47 light_idea_test_case Unused exported function inspection Unused function <code>NewWriter</code> #loc mux.go 246 light_idea_test_case Unused exported function inspection Unused function <code>Vars</code> #loc mux.go 254 light_idea_test_case Unused exported function inspection Unused function <code>CurrentRoute</code> #loc context.go 20 light_idea_test_case Unused exported function inspection Unused function <code>Set</code> #loc context.go 31 light_idea_test_case Unused exported function inspection Unused function <code>Get</code> #loc context.go 43 light_idea_test_case Unused exported function inspection Unused function <code>GetOk</code> #loc context.go 55 light_idea_test_case Unused exported function inspection Unused function <code>GetAll</code> #loc context.go 71 light_idea_test_case Unused exported function inspection Unused function <code>GetAllOk</code> #loc context.go 83 light_idea_test_case Unused exported function inspection Unused function <code>Delete</code> #loc context.go 116 light_idea_test_case Unused exported function inspection Unused function <code>Purge</code> #loc context.go 138 light_idea_test_case Unused exported function inspection Unused function <code>ClearHandler</code> #loc edit.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Locate</code> #loc edit.go 23 light_idea_test_case Unused exported function inspection Unused function <code>Replace</code> #loc edit.go 34 light_idea_test_case Unused exported function inspection Unused function <code>CopyReplace</code> #loc edit.go 44 light_idea_test_case Unused exported function inspection Unused function <code>Remove</code> #loc edit.go 55 light_idea_test_case Unused exported function inspection Unused function <code>HasKey</code> #loc json.go 53 light_idea_test_case Unused exported function inspection Unused function <code>CopyToJSON</code> #loc read.go 102 light_idea_test_case Unused exported function inspection Unused function <code>Decode</code> #loc read.go 124 light_idea_test_case Unused exported function inspection Unused function <code>NewReaderSize</code> #loc write.go 63 light_idea_test_case Unused exported function inspection Unused function <code>Require</code> #loc write.go 118 light_idea_test_case Unused exported function inspection Unused function <code>NewWriterSize</code> #loc write.go 133 light_idea_test_case Unused exported function inspection Unused function <code>Encode</code> #loc circular.go 17 light_idea_test_case Unused exported function inspection Unused function <code>NewEndlessReader</code> #loc extension.go 38 light_idea_test_case Unused exported function inspection Unused function <code>RegisterExtension</code> #loc read_bytes.go 46 light_idea_test_case Unused exported function inspection Unused function <code>IsNil</code> #loc read_bytes.go 424 light_idea_test_case Unused exported function inspection Unused function <code>ReadInt16Bytes</code> #loc read_bytes.go 438 light_idea_test_case Unused exported function inspection Unused function <code>ReadInt8Bytes</code> #loc read_bytes.go 452 light_idea_test_case Unused exported function inspection Unused function <code>ReadIntBytes</code> #loc read_bytes.go 542 light_idea_test_case Unused exported function inspection Unused function <code>ReadUint16Bytes</code> #loc read_bytes.go 570 light_idea_test_case Unused exported function inspection Unused function <code>ReadUintBytes</code> #loc read_bytes.go 580 light_idea_test_case Unused exported function inspection Unused function <code>ReadByteBytes</code> #loc read_bytes.go 665 light_idea_test_case Unused exported function inspection Unused function <code>ReadExactBytes</code> #loc write_bytes.go 150 light_idea_test_case Unused exported function inspection Unused function <code>AppendUint</code> #loc write_bytes.go 156 light_idea_test_case Unused exported function inspection Unused function <code>AppendByte</code> #loc number_unsafe.go 29 light_idea_test_case Unused exported function inspection Unused function <code>UnsafeBytes</code> #loc set.go 149 light_idea_test_case Unused exported function inspection Unused function <code>NewSetFromSlice</code> #loc set.go 162 light_idea_test_case Unused exported function inspection Unused function <code>NewThreadUnsafeSetFromSlice</code> #loc run.go 20 light_idea_test_case Unused exported function inspection Unused function <code>Suite</code> #loc run.go 50 light_idea_test_case Unused exported function inspection Unused function <code>TestingT</code> #loc checkers.go 31 light_idea_test_case Unused exported function inspection Unused function <code>Commentf</code> #loc checkers.go 76 light_idea_test_case Unused exported function inspection Unused function <code>Not</code> #loc reader.go 24 light_idea_test_case Unused exported function inspection Unused function <code>NewReader</code> #loc writer.go 102 light_idea_test_case Unused exported function inspection Unused function <code>NewWriter</code> #loc logrus.go 35 light_idea_test_case Unused exported function inspection Unused function <code>ParseLevel</code> #loc exported.go 12 light_idea_test_case Unused exported function inspection Unused function <code>StandardLogger</code> #loc exported.go 17 light_idea_test_case Unused exported function inspection Unused function <code>SetOutput</code> #loc exported.go 24 light_idea_test_case Unused exported function inspection Unused function <code>SetFormatter</code> #loc exported.go 31 light_idea_test_case Unused exported function inspection Unused function <code>SetLevel</code> #loc exported.go 38 light_idea_test_case Unused exported function inspection Unused function <code>GetLevel</code> #loc exported.go 45 light_idea_test_case Unused exported function inspection Unused function <code>AddHook</code> #loc exported.go 56 light_idea_test_case Unused exported function inspection Unused function <code>WithField</code> #loc exported.go 66 light_idea_test_case Unused exported function inspection Unused function <code>WithFields</code> #loc exported.go 71 light_idea_test_case Unused exported function inspection Unused function <code>Debug</code> #loc exported.go 76 light_idea_test_case Unused exported function inspection Unused function <code>Print</code> #loc exported.go 81 light_idea_test_case Unused exported function inspection Unused function <code>Info</code> #loc exported.go 86 light_idea_test_case Unused exported function inspection Unused function <code>Warn</code> #loc exported.go 91 light_idea_test_case Unused exported function inspection Unused function <code>Warning</code> #loc exported.go 96 light_idea_test_case Unused exported function inspection Unused function <code>Error</code> #loc exported.go 101 light_idea_test_case Unused exported function inspection Unused function <code>Panic</code> #loc exported.go 106 light_idea_test_case Unused exported function inspection Unused function <code>Fatal</code> #loc exported.go 111 light_idea_test_case Unused exported function inspection Unused function <code>Debugf</code> #loc exported.go 116 light_idea_test_case Unused exported function inspection Unused function <code>Printf</code> #loc exported.go 121 light_idea_test_case Unused exported function inspection Unused function <code>Infof</code> #loc exported.go 126 light_idea_test_case Unused exported function inspection Unused function <code>Warnf</code> #loc exported.go 131 light_idea_test_case Unused exported function inspection Unused function <code>Warningf</code> #loc exported.go 136 light_idea_test_case Unused exported function inspection Unused function <code>Errorf</code> #loc exported.go 141 light_idea_test_case Unused exported function inspection Unused function <code>Panicf</code> #loc exported.go 146 light_idea_test_case Unused exported function inspection Unused function <code>Fatalf</code> #loc exported.go 151 light_idea_test_case Unused exported function inspection Unused function <code>Debugln</code> #loc exported.go 156 light_idea_test_case Unused exported function inspection Unused function <code>Println</code> #loc exported.go 161 light_idea_test_case Unused exported function inspection Unused function <code>Infoln</code> #loc exported.go 166 light_idea_test_case Unused exported function inspection Unused function <code>Warnln</code> #loc exported.go 171 light_idea_test_case Unused exported function inspection Unused function <code>Warningln</code> #loc exported.go 176 light_idea_test_case Unused exported function inspection Unused function <code>Errorln</code> #loc exported.go 181 light_idea_test_case Unused exported function inspection Unused function <code>Panicln</code> #loc exported.go 186 light_idea_test_case Unused exported function inspection Unused function <code>Fatalln</code> #loc ini.go 112 light_idea_test_case Unused exported function inspection Unused function <code>Load</code> #loc ini.go 119 light_idea_test_case Unused exported function inspection Unused function <code>LoadFile</code> #loc keys.go 43 light_idea_test_case Unused exported function inspection Unused function <code>NewPrivateKey</code> #loc keys.go 88 light_idea_test_case Unused exported function inspection Unused function <code>PublicKeyFromPrivate</code> #loc root.go 26 light_idea_test_case Unused exported function inspection Unused function <code>NewRoot</code> #loc root.go 77 light_idea_test_case Unused exported function inspection Unused function <code>RootFromSigned</code> #loc roles.go 25 light_idea_test_case Unused exported function inspection Unused function <code>SetValidRoles</code> #loc roles.go 34 light_idea_test_case Unused exported function inspection Unused function <code>RoleName</code> #loc roles.go 94 light_idea_test_case Unused exported function inspection Unused function <code>NewRole</code> #loc types.go 54 light_idea_test_case Unused exported function inspection Unused function <code>SetTUFTypes</code> #loc types.go 60 light_idea_test_case Unused exported function inspection Unused function <code>ValidTUFType</code> #loc types.go 165 light_idea_test_case Unused exported function inspection Unused function <code>SetDefaultExpiryTimes</code> #loc targets.go 22 light_idea_test_case Unused exported function inspection Unused function <code>NewTargets</code> #loc targets.go 104 light_idea_test_case Unused exported function inspection Unused function <code>TargetsFromSigned</code> #loc snapshot.go 24 light_idea_test_case Unused exported function inspection Unused function <code>NewSnapshot</code> #loc snapshot.go 85 light_idea_test_case Unused exported function inspection Unused function <code>SnapshotFromSigned</code> #loc timestamp.go 23 light_idea_test_case Unused exported function inspection Unused function <code>NewTimestamp</code> #loc timestamp.go 63 light_idea_test_case Unused exported function inspection Unused function <code>TimestampFromSigned</code> #loc db.go 24 light_idea_test_case Unused exported function inspection Unused function <code>NewDB</code> #loc dbstore.go 29 light_idea_test_case Unused exported function inspection Unused function <code>DBStore</code> #loc filestore.go 11 light_idea_test_case Unused exported function inspection Unused function <code>NewFilesystemStore</code> #loc httpstore.go 55 light_idea_test_case Unused exported function inspection Unused function <code>NewHTTPStore</code> #loc memorystore.go 13 light_idea_test_case Unused exported function inspection Unused function <code>NewMemoryStore</code> #loc util.go 52 light_idea_test_case Unused exported function inspection Unused function <code>FileMetaEqual</code> #loc util.go 71 light_idea_test_case Unused exported function inspection Unused function <code>NormalizeTarget</code> #loc util.go 75 light_idea_test_case Unused exported function inspection Unused function <code>HashedPaths</code> #loc utils.go 18 light_idea_test_case Unused exported function inspection Unused function <code>Download</code> #loc utils.go 26 light_idea_test_case Unused exported function inspection Unused function <code>Upload</code> #loc utils.go 34 light_idea_test_case Unused exported function inspection Unused function <code>ValidateTarget</code> #loc utils.go 50 light_idea_test_case Unused exported function inspection Unused function <code>StrSliceContains</code> #loc utils.go 59 light_idea_test_case Unused exported function inspection Unused function <code>StrSliceContainsI</code> #loc utils.go 70 light_idea_test_case Unused exported function inspection Unused function <code>FileExists</code> #loc utils.go 83 light_idea_test_case Unused exported function inspection Unused function <code>DoHash</code> #loc client.go 32 light_idea_test_case Unused exported function inspection Unused function <code>NewClient</code> #loc errors.go 71 light_idea_test_case Unused exported function inspection Unused function <code>IsNotFound</code> #loc errors.go 94 light_idea_test_case Unused exported function inspection Unused function <code>IsLatestSnapshot</code> #loc sign.go 13 light_idea_test_case Unused exported function inspection Unused function <code>Sign</code> #loc verify.go 25 light_idea_test_case Unused exported function inspection Unused function <code>VerifyRoot</code> #loc verify.go 152 light_idea_test_case Unused exported function inspection Unused function <code>Unmarshal</code> #loc verify.go 163 light_idea_test_case Unused exported function inspection Unused function <code>UnmarshalTrusted</code> #loc ed25519.go 16 light_idea_test_case Unused exported function inspection Unused function <code>NewEd25519</code> #loc verifiers.go 37 light_idea_test_case Unused exported function inspection Unused function <code>RegisterVerifier</code> #loc tuf.go 64 light_idea_test_case Unused exported function inspection Unused function <code>NewTufRepo</code> #loc serf.go 223 light_idea_test_case Unused exported function inspection Unused function <code>Create</code> #loc config.go 210 light_idea_test_case Unused exported function inspection Unused function <code>DefaultConfig</code> #loc api.go 184 light_idea_test_case Unused exported function inspection Unused function <code>NewClient</code> #loc decode.go 570 light_idea_test_case Unused exported function inspection Unused function <code>NewDecoderBytes</code> #loc encode.go 631 light_idea_test_case Unused exported function inspection Unused function <code>NewEncoderBytes</code> #loc config.go 178 light_idea_test_case Unused exported function inspection Unused function <code>DefaultWANConfig</code> #loc config.go 193 light_idea_test_case Unused exported function inspection Unused function <code>DefaultLocalConfig</code> #loc memberlist.go 133 light_idea_test_case Unused exported function inspection Unused function <code>Create</code> #loc decode.go 67 light_idea_test_case Unused exported function inspection Unused function <code>Unmarshal</code> #loc encode.go 138 light_idea_test_case Unused exported function inspection Unused function <code>MarshalIndent</code> #loc encode.go 153 light_idea_test_case Unused exported function inspection Unused function <code>MarshalCanonical</code> #loc encode.go 172 light_idea_test_case Unused exported function inspection Unused function <code>HTMLEscape</code> #loc indent.go 11 light_idea_test_case Unused exported function inspection Unused function <code>Compact</code> #loc stream.go 26 light_idea_test_case Unused exported function inspection Unused function <code>NewDecoder</code> #loc stream.go 147 light_idea_test_case Unused exported function inspection Unused function <code>NewEncoder</code> #loc guid.go 10 light_idea_test_case Unused exported function inspection Unused function <code>NewGUID</code> #loc copylayer.go 15 light_idea_test_case Unused exported function inspection Unused function <code>CopyLayer</code> #loc createlayer.go 13 light_idea_test_case Unused exported function inspection Unused function <code>CreateLayer</code> #loc exportlayer.go 16 light_idea_test_case Unused exported function inspection Unused function <code>ExportLayer</code> #loc importlayer.go 15 light_idea_test_case Unused exported function inspection Unused function <code>ImportLayer</code> #loc layerexists.go 13 light_idea_test_case Unused exported function inspection Unused function <code>LayerExists</code> #loc waitprocess.go 13 light_idea_test_case Unused exported function inspection Unused function <code>WaitForProcessInComputeSystem</code> #loc destroylayer.go 13 light_idea_test_case Unused exported function inspection Unused function <code>DestroyLayer</code> #loc preparelayer.go 16 light_idea_test_case Unused exported function inspection Unused function <code>PrepareLayer</code> #loc activatelayer.go 15 light_idea_test_case Unused exported function inspection Unused function <code>ActivateLayer</code> #loc createprocess.go 70 light_idea_test_case Unused exported function inspection Unused function <code>CreateProcessInComputeSystem</code> #loc resizeconsole.go 13 light_idea_test_case Unused exported function inspection Unused function <code>ResizeConsoleInComputeSystem</code> #loc unpreparelayer.go 13 light_idea_test_case Unused exported function inspection Unused function <code>UnprepareLayer</code> #loc deactivatelayer.go 12 light_idea_test_case Unused exported function inspection Unused function <code>DeactivateLayer</code> #loc terminateprocess.go 12 light_idea_test_case Unused exported function inspection Unused function <code>TerminateProcessInComputeSystem</code> #loc getlayermountpath.go 15 light_idea_test_case Unused exported function inspection Unused function <code>GetLayerMountPath</code> #loc createsandboxlayer.go 15 light_idea_test_case Unused exported function inspection Unused function <code>CreateSandboxLayer</code> #loc startcomputesystem.go 13 light_idea_test_case Unused exported function inspection Unused function <code>StartComputeSystem</code> #loc createcomputesystem.go 14 light_idea_test_case Unused exported function inspection Unused function <code>CreateComputeSystem</code> #loc getsharedbaseimages.go 14 light_idea_test_case Unused exported function inspection Unused function <code>GetSharedBaseImages</code> #loc shutdowncomputesystem.go 13 light_idea_test_case Unused exported function inspection Unused function <code>ShutdownComputeSystem</code> #loc terminatecomputesystem.go 12 light_idea_test_case Unused exported function inspection Unused function <code>TerminateComputeSystem</code> #loc zfs.go 99 light_idea_test_case Unused exported function inspection Unused function <code>SetLogger</code> #loc zfs.go 126 light_idea_test_case Unused exported function inspection Unused function <code>Filesystems</code> #loc zfs.go 133 light_idea_test_case Unused exported function inspection Unused function <code>Volumes</code> #loc zfs.go 178 light_idea_test_case Unused exported function inspection Unused function <code>ReceiveSnapshot</code> #loc zfs.go 203 light_idea_test_case Unused exported function inspection Unused function <code>CreateVolume</code> #loc zfs.go 279 light_idea_test_case Unused exported function inspection Unused function <code>CreateFilesystem</code> #loc zpool.go 65 light_idea_test_case Unused exported function inspection Unused function <code>CreateZpool</code> #loc zpool.go 88 light_idea_test_case Unused exported function inspection Unused function <code>ListZpools</code> #loc reader.go 48 light_idea_test_case Unused exported function inspection Unused function <code>NewReader</code> #loc writer.go 22 light_idea_test_case Unused exported function inspection Unused function <code>NewWriter</code> #loc writer.go 35 light_idea_test_case Unused exported function inspection Unused function <code>NewWriterSize</code> #loc decode.go 22 light_idea_test_case Unused exported function inspection Unused function <code>Unmarshal</code> #loc decode.go 47 light_idea_test_case Unused exported function inspection Unused function <code>PrimitiveDecode</code> #loc decode.go 119 light_idea_test_case Unused exported function inspection Unused function <code>DecodeFile</code> #loc decode.go 129 light_idea_test_case Unused exported function inspection Unused function <code>DecodeReader</code> #loc encode.go 56 light_idea_test_case Unused exported function inspection Unused function <code>NewEncoder</code> #loc netns.go 65 light_idea_test_case Unused exported function inspection Unused function <code>None</code> #loc netns_unspecified.go 13 light_idea_test_case Unused exported function inspection Unused function <code>Set</code> #loc netns_unspecified.go 17 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc netns_unspecified.go 21 light_idea_test_case Unused exported function inspection Unused function <code>Get</code> #loc netns_unspecified.go 25 light_idea_test_case Unused exported function inspection Unused function <code>GetFromName</code> #loc netns_unspecified.go 29 light_idea_test_case Unused exported function inspection Unused function <code>GetFromPid</code> #loc netns_unspecified.go 33 light_idea_test_case Unused exported function inspection Unused function <code>GetFromDocker</code> #loc addr.go 23 light_idea_test_case Unused exported function inspection Unused function <code>ParseAddr</code> #loc link.go 32 light_idea_test_case Unused exported function inspection Unused function <code>NewLinkAttrs</code> #loc netlink.go 37 light_idea_test_case Unused exported function inspection Unused function <code>NewIPNet</code> #loc netlink_unspecified.go 13 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetUp</code> #loc netlink_unspecified.go 17 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetDown</code> #loc netlink_unspecified.go 21 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetMTU</code> #loc netlink_unspecified.go 25 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetMaster</code> #loc netlink_unspecified.go 29 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetNsPid</code> #loc netlink_unspecified.go 33 light_idea_test_case Unused exported function inspection Unused function <code>LinkSetNsFd</code> #loc netlink_unspecified.go 37 light_idea_test_case Unused exported function inspection Unused function <code>LinkAdd</code> #loc netlink_unspecified.go 41 light_idea_test_case Unused exported function inspection Unused function <code>LinkDel</code> #loc netlink_unspecified.go 45 light_idea_test_case Unused exported function inspection Unused function <code>SetHairpin</code> #loc netlink_unspecified.go 49 light_idea_test_case Unused exported function inspection Unused function <code>SetGuard</code> #loc netlink_unspecified.go 53 light_idea_test_case Unused exported function inspection Unused function <code>SetFastLeave</code> #loc netlink_unspecified.go 57 light_idea_test_case Unused exported function inspection Unused function <code>SetLearning</code> #loc netlink_unspecified.go 61 light_idea_test_case Unused exported function inspection Unused function <code>SetRootBlock</code> #loc netlink_unspecified.go 65 light_idea_test_case Unused exported function inspection Unused function <code>SetFlood</code> #loc netlink_unspecified.go 69 light_idea_test_case Unused exported function inspection Unused function <code>LinkList</code> #loc netlink_unspecified.go 73 light_idea_test_case Unused exported function inspection Unused function <code>AddrAdd</code> #loc netlink_unspecified.go 77 light_idea_test_case Unused exported function inspection Unused function <code>AddrDel</code> #loc netlink_unspecified.go 81 light_idea_test_case Unused exported function inspection Unused function <code>AddrList</code> #loc netlink_unspecified.go 85 light_idea_test_case Unused exported function inspection Unused function <code>RouteAdd</code> #loc netlink_unspecified.go 89 light_idea_test_case Unused exported function inspection Unused function <code>RouteDel</code> #loc netlink_unspecified.go 93 light_idea_test_case Unused exported function inspection Unused function <code>RouteList</code> #loc netlink_unspecified.go 97 light_idea_test_case Unused exported function inspection Unused function <code>XfrmPolicyAdd</code> #loc netlink_unspecified.go 101 light_idea_test_case Unused exported function inspection Unused function <code>XfrmPolicyDel</code> #loc netlink_unspecified.go 105 light_idea_test_case Unused exported function inspection Unused function <code>XfrmPolicyList</code> #loc netlink_unspecified.go 109 light_idea_test_case Unused exported function inspection Unused function <code>XfrmStateAdd</code> #loc netlink_unspecified.go 113 light_idea_test_case Unused exported function inspection Unused function <code>XfrmStateDel</code> #loc netlink_unspecified.go 117 light_idea_test_case Unused exported function inspection Unused function <code>XfrmStateList</code> #loc netlink_unspecified.go 121 light_idea_test_case Unused exported function inspection Unused function <code>NeighAdd</code> #loc netlink_unspecified.go 125 light_idea_test_case Unused exported function inspection Unused function <code>NeighSet</code> #loc netlink_unspecified.go 129 light_idea_test_case Unused exported function inspection Unused function <code>NeighAppend</code> #loc netlink_unspecified.go 133 light_idea_test_case Unused exported function inspection Unused function <code>NeighDel</code> #loc netlink_unspecified.go 137 light_idea_test_case Unused exported function inspection Unused function <code>NeighList</code> #loc netlink_unspecified.go 141 light_idea_test_case Unused exported function inspection Unused function <code>NeighDeserialize</code> #loc user.go 72 light_idea_test_case Unused exported function inspection Unused function <code>ParsePasswdFile</code> #loc user.go 85 light_idea_test_case Unused exported function inspection Unused function <code>ParsePasswdFileFilter</code> #loc user.go 133 light_idea_test_case Unused exported function inspection Unused function <code>ParseGroupFile</code> #loc user.go 146 light_idea_test_case Unused exported function inspection Unused function <code>ParseGroupFileFilter</code> #loc user.go 204 light_idea_test_case Unused exported function inspection Unused function <code>GetExecUserPath</code> #loc user.go 412 light_idea_test_case Unused exported function inspection Unused function <code>GetAdditionalGroupsPath</code> #loc lookup.go 40 light_idea_test_case Unused exported function inspection Unused function <code>CurrentUser</code> #loc lookup.go 47 light_idea_test_case Unused exported function inspection Unused function <code>LookupUser</code> #loc lookup.go 88 light_idea_test_case Unused exported function inspection Unused function <code>CurrentGroup</code> #loc lookup.go 95 light_idea_test_case Unused exported function inspection Unused function <code>LookupGroup</code> #loc lookup_unix.go 16 light_idea_test_case Unused exported function inspection Unused function <code>GetPasswdPath</code> #loc lookup_unix.go 24 light_idea_test_case Unused exported function inspection Unused function <code>GetGroupPath</code> #loc label.go 8 light_idea_test_case Unused exported function inspection Unused function <code>InitLabels</code> #loc label.go 12 light_idea_test_case Unused exported function inspection Unused function <code>GenLabels</code> #loc label.go 16 light_idea_test_case Unused exported function inspection Unused function <code>FormatMountLabel</code> #loc label.go 20 light_idea_test_case Unused exported function inspection Unused function <code>SetProcessLabel</code> #loc label.go 24 light_idea_test_case Unused exported function inspection Unused function <code>SetFileLabel</code> #loc label.go 28 light_idea_test_case Unused exported function inspection Unused function <code>SetFileCreateLabel</code> #loc label.go 32 light_idea_test_case Unused exported function inspection Unused function <code>Relabel</code> #loc label.go 36 light_idea_test_case Unused exported function inspection Unused function <code>GetPidLabel</code> #loc label.go 40 light_idea_test_case Unused exported function inspection Unused function <code>Init</code> #loc label.go 43 light_idea_test_case Unused exported function inspection Unused function <code>ReserveLabel</code> #loc label.go 47 light_idea_test_case Unused exported function inspection Unused function <code>UnreserveLabel</code> #loc label.go 53 light_idea_test_case Unused exported function inspection Unused function <code>DupSecOpt</code> #loc label.go 59 light_idea_test_case Unused exported function inspection Unused function <code>DisableSecOpt</code> #loc label.go 64 light_idea_test_case Unused exported function inspection Unused function <code>Validate</code> #loc label.go 69 light_idea_test_case Unused exported function inspection Unused function <code>RelabelNeeded</code> #loc label.go 74 light_idea_test_case Unused exported function inspection Unused function <code>IsShared</code> #loc utils.go 17 light_idea_test_case Unused exported function inspection Unused function <code>GenerateRandomName</code> #loc utils.go 30 light_idea_test_case Unused exported function inspection Unused function <code>ResolveRootfs</code> #loc utils.go 40 light_idea_test_case Unused exported function inspection Unused function <code>ExitStatus</code> #loc utils_unix.go 11 light_idea_test_case Unused exported function inspection Unused function <code>CloseExecFrom</code> #loc proc.go 12 light_idea_test_case Unused exported function inspection Unused function <code>GetProcessStartTime</code> #loc apply_nosystemd.go 17 light_idea_test_case Unused exported function inspection Unused function <code>UseSystemd</code> #loc apply_nosystemd.go 49 light_idea_test_case Unused exported function inspection Unused function <code>Freeze</code> #loc config.go 15 light_idea_test_case Unused exported function inspection Unused function <code>New</code> #loc config.go 204 light_idea_test_case Unused exported function inspection Unused function <code>NewFunctionHook</code> #loc config.go 226 light_idea_test_case Unused exported function inspection Unused function <code>NewCommandHook</code> #loc blkio_device.go 23 light_idea_test_case Unused exported function inspection Unused function <code>NewWeightDevice</code> #loc blkio_device.go 50 light_idea_test_case Unused exported function inspection Unused function <code>NewThrottleDevice</code> #loc config.go 13 light_idea_test_case Unused exported function inspection Unused function <code>ConvertStringToOperator</code> #loc config.go 40 light_idea_test_case Unused exported function inspection Unused function <code>ConvertStringToAction</code> #loc seccomp_unsupported.go 14 light_idea_test_case Unused exported function inspection Unused function <code>InitSeccomp</code> #loc apparmor_disabled.go 5 light_idea_test_case Unused exported function inspection Unused function <code>IsEnabled</code> #loc apparmor_disabled.go 9 light_idea_test_case Unused exported function inspection Unused function <code>ApplyProfile</code> #loc capture.go 8 light_idea_test_case Unused exported function inspection Unused function <code>Capture</code> #loc context.go 187 light_idea_test_case Unused exported function inspection Unused function <code>Background</code> #loc context.go 196 light_idea_test_case Unused exported function inspection Unused function <code>TODO</code> #loc context.go 418 light_idea_test_case Unused exported function inspection Unused function <code>WithTimeout</code> #loc context.go 427 light_idea_test_case Unused exported function inspection Unused function <code>WithValue</code> #loc client.go 56 light_idea_test_case Unused exported function inspection Unused function <code>Dial</code> #loc extpoint.go 64 light_idea_test_case Unused exported function inspection Unused function <code>Unregister</code> #loc volume.go 54 light_idea_test_case Unused exported function inspection Unused function <code>ValidMountMode</code> #loc volume.go 59 light_idea_test_case Unused exported function inspection Unused function <code>ReadWrite</code> #loc git.go 11 light_idea_test_case Unused exported function inspection Unused function <code>MakeGitContext</code> #loc remote.go 31 light_idea_test_case Unused exported function inspection Unused function <code>MakeRemoteContext</code> #loc builder.go 259 light_idea_test_case Unused exported function inspection Unused function <code>Commit</code> #loc config.go 370 light_idea_test_case Unused exported function inspection Unused function <code>ParseIndexInfo</code> #loc service.go 20 light_idea_test_case Unused exported function inspection Unused function <code>NewService</code> #loc reference.go 55 light_idea_test_case Unused exported function inspection Unused function <code>ParseReference</code> #loc reference.go 66 light_idea_test_case Unused exported function inspection Unused function <code>DigestReference</code> #loc hostconfig_unix.go 70 light_idea_test_case Unused exported function inspection Unused function <code>IsPreDefinedNetwork</code> #loc ================================================ FILE: testData/performance/GoUnusedFunction/expected.xml ================================================ cwlogsiface_mock_test.go 52 light_idea_test_case Unused function inspection Unused function <code>test</code> #loc ioctl_bsd.go 25 light_idea_test_case Unused function inspection Unused function <code>_IO</code> #loc ioctl_bsd.go 29 light_idea_test_case Unused function inspection Unused function <code>_IOR</code> #loc ioctl_bsd.go 37 light_idea_test_case Unused function inspection Unused function <code>_IOWR</code> #loc utilities.go 17 light_idea_test_case Unused function inspection Unused function <code>convertBytesToInteger</code> #loc parser_test_helpers.go 28 light_idea_test_case Unused function inspection Unused function <code>anyToXHelper</code> #loc parser_test_helpers.go 41 light_idea_test_case Unused function inspection Unused function <code>parseParamsHelper</code> #loc parser_test_helpers.go 65 light_idea_test_case Unused function inspection Unused function <code>cursorSingleParamHelper</code> #loc parser_test_helpers.go 74 light_idea_test_case Unused function inspection Unused function <code>cursorTwoParamHelper</code> #loc parser_test_helpers.go 83 light_idea_test_case Unused function inspection Unused function <code>eraseHelper</code> #loc parser_test_helpers.go 93 light_idea_test_case Unused function inspection Unused function <code>scrollHelper</code> #loc parser_test_helpers.go 101 light_idea_test_case Unused function inspection Unused function <code>clearOnStateChangeHelper</code> #loc parser_test_helpers.go 109 light_idea_test_case Unused function inspection Unused function <code>c0Helper</code> #loc db.go 678 light_idea_test_case Unused function inspection Unused function <code>warn</code> #loc db.go 682 light_idea_test_case Unused function inspection Unused function <code>warnf</code> #loc db.go 686 light_idea_test_case Unused function inspection Unused function <code>printstack</code> #loc resolvconf.go 23 light_idea_test_case Unused function inspection Unused function <code>readResolvConf</code> #loc resolvconf.go 49 light_idea_test_case Unused function inspection Unused function <code>getNameserversAsCIDR</code> #loc mock_proxy.go 5 light_idea_test_case Unused function inspection Unused function <code>newMockProxyCommand</code> #loc sandbox.go 1017 light_idea_test_case Unused function inspection Unused function <code>createFile</code> #loc urls.go 226 light_idea_test_case Unused function inspection Unused function <code>appendValues</code> #loc suite.go 143 light_idea_test_case Unused function inspection Unused function <code>checkBlobDescriptorClear</code> #loc conn.go 586 light_idea_test_case Unused function inspection Unused function <code>dereferenceAll</code> #loc properties.go 707 light_idea_test_case Unused function inspection Unused function <code>propByIndex</code> #loc time.go 173 light_idea_test_case Unused function inspection Unused function <code>timeLocUTCName</code> #loc fast-path.generated.go 1626 light_idea_test_case Unused function inspection Unused function <code>fastpathEncodeTypeSwitchMap</code> #loc json_bytes.go 226 light_idea_test_case Unused function inspection Unused function <code>rwFloatBytes</code> #loc errors.go 55 light_idea_test_case Unused function inspection Unused function <code>isDecodeFailedWithErr</code> #loc time.go 173 light_idea_test_case Unused function inspection Unused function <code>timeLocUTCName</code> #loc helper_internal.go 77 light_idea_test_case Unused function inspection Unused function <code>debugf</code> #loc parse.go 495 light_idea_test_case Unused function inspection Unused function <code>isStringType</code> #loc encode.go 494 light_idea_test_case Unused function inspection Unused function <code>isValidKeyName</code> #loc dispatchers.go 38 light_idea_test_case Unused function inspection Unused function <code>nullDispatch</code> #loc internals_unix.go 10 light_idea_test_case Unused function inspection Unused function <code>fixPermissions</code> #loc utils.go 12 light_idea_test_case Unused function inspection Unused function <code>getExitCode</code> #loc utils.go 16 light_idea_test_case Unused function inspection Unused function <code>processExitCode</code> #loc utils.go 36 light_idea_test_case Unused function inspection Unused function <code>runCommandWithOutputAndTimeout</code> #loc docker_utils.go 793 light_idea_test_case Unused function inspection Unused function <code>dockerCmdInDirWithTimeout</code> #loc docker_utils.go 1145 light_idea_test_case Unused function inspection Unused function <code>getContainerState</code> #loc docker_cli_nat_test.go 45 light_idea_test_case Unused function inspection Unused function <code>getContainerLogs</code> #loc docker_cli_nat_test.go 50 light_idea_test_case Unused function inspection Unused function <code>getContainerStatus</code> #loc ================================================ FILE: testData/performance/GoUnusedGlobalVariable/expected.xml ================================================ flag.go 594 light_idea_test_case Unused global variable inspection Unused variable 'ShortUsage' random.go 18 light_idea_test_case Unused global variable inspection Unused variable 'Reader' copy.go 21 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidCopySource' archive.go 76 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotImplemented' stdcopy.go 24 light_idea_test_case Unused global variable inspection Unused variable 'Stdin' discovery.go 14 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotImplemented' mimetype.go 9 light_idea_test_case Unused global variable inspection Unused variable 'MimeTypes' checker.go 14 light_idea_test_case Unused global variable inspection Unused variable 'DeepEquals' checker.go 15 light_idea_test_case Unused global variable inspection Unused variable 'Equals' checker.go 16 light_idea_test_case Unused global variable inspection Unused variable 'ErrorMatches' checker.go 17 light_idea_test_case Unused global variable inspection Unused variable 'FitsTypeOf' checker.go 18 light_idea_test_case Unused global variable inspection Unused variable 'HasLen' checker.go 19 light_idea_test_case Unused global variable inspection Unused variable 'Implements' checker.go 20 light_idea_test_case Unused global variable inspection Unused variable 'IsNil' checker.go 21 light_idea_test_case Unused global variable inspection Unused variable 'Matches' checker.go 22 light_idea_test_case Unused global variable inspection Unused variable 'Not' checker.go 23 light_idea_test_case Unused global variable inspection Unused variable 'NotNil' checker.go 24 light_idea_test_case Unused global variable inspection Unused variable 'PanicMatches' checker.go 25 light_idea_test_case Unused global variable inspection Unused variable 'Panics' hosts_unix.go 8 light_idea_test_case Unused global variable inspection Unused variable 'DefaultHost' names.go 9 light_idea_test_case Unused global variable inspection Unused variable 'RestrictedNamePattern' logger.go 18 light_idea_test_case Unused global variable inspection Unused variable 'ErrReadLogsNotSupported' driver.go 22 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotRunning' driver.go 23 light_idea_test_case Unused global variable inspection Unused variable 'ErrWaitTimeoutReached' driver.go 24 light_idea_test_case Unused global variable inspection Unused variable 'ErrDriverAlreadyRegistered' driver.go 25 light_idea_test_case Unused global variable inspection Unused variable 'ErrDriverNotFound' image.go 14 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeInvalidImageID' daemon.go 15 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoSuchContainer' daemon.go 24 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeUnregisteredContainer' daemon.go 33 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeContainerBeingRemoved' daemon.go 42 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeUnpauseContainer' daemon.go 51 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeAlreadyPaused' daemon.go 60 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotPaused' daemon.go 69 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeImageUnregContainer' daemon.go 77 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeEmptyID' daemon.go 86 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeLoggingFactory' daemon.go 95 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeInitLogger' daemon.go 104 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotRunning' daemon.go 113 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeLinkNotRunning' daemon.go 123 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeDeviceInfo' daemon.go 132 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeEmptyEndpoint' daemon.go 141 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeEmptyNetwork' daemon.go 150 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeParsingPort' daemon.go 159 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoSandbox' daemon.go 168 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNetworkUpdate' daemon.go 177 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNetworkRefresh' daemon.go 186 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeHostPort' daemon.go 195 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNetworkConflict' daemon.go 204 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeJoinInfo' daemon.go 213 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeIPCRunning' daemon.go 222 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotADir' daemon.go 231 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeParseContainer' daemon.go 239 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeJoinSelf' daemon.go 247 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeJoinRunning' daemon.go 256 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeModeNotContainer' daemon.go 265 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRemovingVolume' daemon.go 274 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeInvalidNetworkMode' daemon.go 283 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeGetGraph' daemon.go 292 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeGetLayer' daemon.go 301 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodePutLayer' daemon.go 310 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeGetLayerMetadata' daemon.go 319 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeEmptyConfig' daemon.go 328 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoSuchImageHash' daemon.go 337 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoSuchImageTag' daemon.go 346 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeMountOverFile' daemon.go 355 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeMountSetup' daemon.go 364 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeInvalidMode' daemon.go 373 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeInvalid' daemon.go 381 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeAbs' daemon.go 389 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeName' daemon.go 397 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeFromBlank' daemon.go 406 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeMode' daemon.go 415 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeDup' daemon.go 424 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeCantUnpause' daemon.go 432 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodePSError' daemon.go 441 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoPID' daemon.go 449 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeBadPID' daemon.go 458 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoTop' daemon.go 467 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeStopped' daemon.go 476 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeCantStop' daemon.go 485 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeBadCPUFields' daemon.go 493 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeBadCPUInt' daemon.go 502 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeBadStatFormat' daemon.go 510 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeTimedOut' daemon.go 519 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeAlreadyRemoving' daemon.go 527 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeStartPaused' daemon.go 536 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeAlreadyStarted' daemon.go 545 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeHostConfigStart' daemon.go 554 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeCantStart' daemon.go 563 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeCantRestart' daemon.go 572 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeEmptyRename' daemon.go 581 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRenameTaken' daemon.go 590 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRenameDelete' daemon.go 599 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodePauseError' daemon.go 608 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNeedStream' daemon.go 617 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeDanglingOne' daemon.go 626 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeImgDelUsed' daemon.go 635 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeImgNoParent' daemon.go 643 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExportFailed' daemon.go 652 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecResize' daemon.go 661 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeContainerNotRunning' daemon.go 670 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoExecID' daemon.go 679 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecPaused' daemon.go 688 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecRunning' daemon.go 697 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecCantRun' daemon.go 706 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecAttach' daemon.go 715 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExecContainerStopped' daemon.go 724 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeDefaultName' daemon.go 733 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNoParent' daemon.go 742 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeCantDestroy' daemon.go 751 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmRunning' daemon.go 760 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmFailed' daemon.go 769 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmNotFound' daemon.go 778 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmState' daemon.go 787 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmDriverFS' daemon.go 796 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmInit' daemon.go 805 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmFS' daemon.go 814 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmExecDriver' daemon.go 823 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmVolumeInUse' daemon.go 832 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeRmVolume' daemon.go 841 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeInvalidCpusetCpus' daemon.go 850 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeInvalidCpusetMems' daemon.go 859 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotAvailableCpusetCpus' daemon.go 868 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotAvailableCpusetMems' daemon.go 877 light_idea_test_case Unused global variable inspection Unused variable 'ErrorVolumeNameTaken' server.go 12 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNewerClientVersion' server.go 21 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeOldClientVersion' server.go 30 light_idea_test_case Unused global variable inspection Unused variable 'ErrorNetworkControllerNotEnabled' builder.go 15 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeAtLeastOneArg' builder.go 24 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeExactlyOneArg' builder.go 33 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeAtLeastTwoArgs' builder.go 42 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeTooManyArgs' builder.go 51 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeChainOnBuild' builder.go 60 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeBadOnBuildCmd' builder.go 69 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeMissingFrom' builder.go 78 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeNotOnWindows' builder.go 87 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeVolumeEmpty' const.go 19 light_idea_test_case Unused global variable inspection Unused variable 'A' config.go 34 light_idea_test_case Unused global variable inspection Unused variable 'DefaultConfig' credentials.go 67 light_idea_test_case Unused global variable inspection Unused variable 'AnonymousCredentials' error.go 25 light_idea_test_case Unused global variable inspection Unused variable 'ErrError' error.go 26 light_idea_test_case Unused global variable inspection Unused variable 'ErrInternal' error.go 27 light_idea_test_case Unused global variable inspection Unused variable 'ErrPerm' error.go 31 light_idea_test_case Unused global variable inspection Unused variable 'ErrNomem' error.go 33 light_idea_test_case Unused global variable inspection Unused variable 'ErrInterrupt' error.go 36 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotFound' error.go 37 light_idea_test_case Unused global variable inspection Unused variable 'ErrFull' error.go 39 light_idea_test_case Unused global variable inspection Unused variable 'ErrProtocol' error.go 40 light_idea_test_case Unused global variable inspection Unused variable 'ErrEmpty' error.go 41 light_idea_test_case Unused global variable inspection Unused variable 'ErrSchema' error.go 42 light_idea_test_case Unused global variable inspection Unused variable 'ErrTooBig' error.go 44 light_idea_test_case Unused global variable inspection Unused variable 'ErrMismatch' error.go 45 light_idea_test_case Unused global variable inspection Unused variable 'ErrMisuse' error.go 46 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoLFS' error.go 47 light_idea_test_case Unused global variable inspection Unused variable 'ErrAuth' error.go 48 light_idea_test_case Unused global variable inspection Unused variable 'ErrFormat' error.go 49 light_idea_test_case Unused global variable inspection Unused variable 'ErrRange' error.go 50 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotADB' error.go 76 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrRead' error.go 77 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrShortRead' error.go 78 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrWrite' error.go 79 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrFsync' error.go 80 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrDirFsync' error.go 81 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrTruncate' error.go 82 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrFstat' error.go 83 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrUnlock' error.go 84 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrRDlock' error.go 85 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrDelete' error.go 86 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrBlocked' error.go 87 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrNoMem' error.go 88 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrAccess' error.go 89 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrCheckReservedLock' error.go 90 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrLock' error.go 91 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrClose' error.go 92 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrDirClose' error.go 93 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrSHMOpen' error.go 94 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrSHMSize' error.go 95 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrSHMLock' error.go 96 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrSHMMap' error.go 97 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrSeek' error.go 98 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrDeleteNoent' error.go 99 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrMMap' error.go 100 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrGetTempPath' error.go 101 light_idea_test_case Unused global variable inspection Unused variable 'ErrIoErrConvPath' error.go 102 light_idea_test_case Unused global variable inspection Unused variable 'ErrLockedSharedCache' error.go 103 light_idea_test_case Unused global variable inspection Unused variable 'ErrBusyRecovery' error.go 104 light_idea_test_case Unused global variable inspection Unused variable 'ErrBusySnapshot' error.go 105 light_idea_test_case Unused global variable inspection Unused variable 'ErrCantOpenNoTempDir' error.go 106 light_idea_test_case Unused global variable inspection Unused variable 'ErrCantOpenIsDir' error.go 107 light_idea_test_case Unused global variable inspection Unused variable 'ErrCantOpenFullPath' error.go 108 light_idea_test_case Unused global variable inspection Unused variable 'ErrCantOpenConvPath' error.go 109 light_idea_test_case Unused global variable inspection Unused variable 'ErrCorruptVTab' error.go 110 light_idea_test_case Unused global variable inspection Unused variable 'ErrReadonlyRecovery' error.go 111 light_idea_test_case Unused global variable inspection Unused variable 'ErrReadonlyCantLock' error.go 112 light_idea_test_case Unused global variable inspection Unused variable 'ErrReadonlyRollback' error.go 113 light_idea_test_case Unused global variable inspection Unused variable 'ErrReadonlyDbMoved' error.go 114 light_idea_test_case Unused global variable inspection Unused variable 'ErrAbortRollback' error.go 115 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintCheck' error.go 116 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintCommitHook' error.go 117 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintForeignKey' error.go 118 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintFunction' error.go 119 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintNotNull' error.go 120 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintPrimaryKey' error.go 121 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintTrigger' error.go 122 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintUnique' error.go 123 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintVTab' error.go 124 light_idea_test_case Unused global variable inspection Unused variable 'ErrConstraintRowId' error.go 125 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoticeRecoverWAL' error.go 126 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoticeRecoverRollback' error.go 127 light_idea_test_case Unused global variable inspection Unused variable 'ErrWarningAutoIndex' errors.go 13 light_idea_test_case Unused global variable inspection Unused variable 'ErrDatabaseOpen' client.go 40 light_idea_test_case Unused global variable inspection Unused variable 'DefaultRequestTimeout' keys.generated.go 25 light_idea_test_case Unused global variable inspection Unused variable 'codecSelferBitsize5311' store.go 25 light_idea_test_case Unused global variable inspection Unused variable 'ErrBackendNotSupported' store.go 27 light_idea_test_case Unused global variable inspection Unused variable 'ErrCallNotSupported' store.go 29 light_idea_test_case Unused global variable inspection Unused variable 'ErrNotReachable' store.go 31 light_idea_test_case Unused global variable inspection Unused variable 'ErrCannotLock' store.go 33 light_idea_test_case Unused global variable inspection Unused variable 'ErrKeyModified' store.go 35 light_idea_test_case Unused global variable inspection Unused variable 'ErrKeyNotFound' store.go 37 light_idea_test_case Unused global variable inspection Unused variable 'ErrPreviousNotSpecified' client.go 61 light_idea_test_case Unused global variable inspection Unused variable 'ErrRepositoryNotExist' jsonsign.go 18 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidSignContent' contract.go 32 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidIpamService' contract.go 33 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidIpamConfigService' contract.go 34 light_idea_test_case Unused global variable inspection Unused variable 'ErrIpamNotAvailable' contract.go 35 light_idea_test_case Unused global variable inspection Unused variable 'ErrIpamInternalError' contract.go 36 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidAddressSpace' contract.go 37 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidPool' contract.go 38 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidSubPool' contract.go 39 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidRequest' contract.go 40 light_idea_test_case Unused global variable inspection Unused variable 'ErrPoolNotFound' contract.go 41 light_idea_test_case Unused global variable inspection Unused variable 'ErrOverlapPool' contract.go 42 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoAvailablePool' contract.go 43 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoAvailableIPs' contract.go 44 light_idea_test_case Unused global variable inspection Unused variable 'ErrIPAlreadyAllocated' contract.go 45 light_idea_test_case Unused global variable inspection Unused variable 'ErrIPOutOfRange' contract.go 46 light_idea_test_case Unused global variable inspection Unused variable 'ErrPoolOverlap' contract.go 47 light_idea_test_case Unused global variable inspection Unused variable 'ErrBadPool' labels.go 48 light_idea_test_case Unused global variable inspection Unused variable 'GlobalKVProvider' labels.go 51 light_idea_test_case Unused global variable inspection Unused variable 'GlobalKVProviderURL' labels.go 54 light_idea_test_case Unused global variable inspection Unused variable 'GlobalKVProviderConfig' labels.go 57 light_idea_test_case Unused global variable inspection Unused variable 'LocalKVProvider' labels.go 60 light_idea_test_case Unused global variable inspection Unused variable 'LocalKVProviderURL' labels.go 63 light_idea_test_case Unused global variable inspection Unused variable 'LocalKVProviderConfig' utils.go 24 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoDefaultRoute' datastore.go 55 light_idea_test_case Unused global variable inspection Unused variable 'ErrKeyModified' utils.go 12 light_idea_test_case Unused global variable inspection Unused variable 'PredefinedGranularNetworks' tarsum.go 10 light_idea_test_case Unused global variable inspection Unused variable 'TarsumRegexp' blobs.go 16 light_idea_test_case Unused global variable inspection Unused variable 'ErrBlobExists' blobs.go 19 light_idea_test_case Unused global variable inspection Unused variable 'ErrBlobDigestUnsupported' blobs.go 22 light_idea_test_case Unused global variable inspection Unused variable 'ErrBlobUnknown' blobs.go 25 light_idea_test_case Unused global variable inspection Unused variable 'ErrBlobUploadUnknown' blobs.go 29 light_idea_test_case Unused global variable inspection Unused variable 'ErrBlobInvalidLength' blobs.go 32 light_idea_test_case Unused global variable inspection Unused variable 'ErrUnsupported' names.go 49 light_idea_test_case Unused global variable inspection Unused variable 'TagNameAnchoredRegexp' errors.go 13 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeUnsupported' errors.go 44 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeSizeInvalid' errors.go 116 light_idea_test_case Unused global variable inspection Unused variable 'ErrorCodeManifestBlobUnknown' routes.go 17 light_idea_test_case Unused global variable inspection Unused variable 'allEndpoints' descriptors.go 196 light_idea_test_case Unused global variable inspection Unused variable 'APIDescriptor' registry.go 23 light_idea_test_case Unused global variable inspection Unused variable 'GlobalScope' call.go 26 light_idea_test_case Unused global variable inspection Unused variable 'errSignature' dbus.go 12 light_idea_test_case Unused global variable inspection Unused variable 'uint8Type' rpc.go 170 light_idea_test_case Unused global variable inspection Unused variable 'GoRpc' helper.go 233 light_idea_test_case Unused global variable inspection Unused variable 'bsAll0x00' msgpack.go 832 light_idea_test_case Unused global variable inspection Unused variable 'MsgpackSpecRpc' write.go 33 light_idea_test_case Unused global variable inspection Unused variable 'Nowhere' checkers.go 109 light_idea_test_case Unused global variable inspection Unused variable 'IsNil' checkers.go 145 light_idea_test_case Unused global variable inspection Unused variable 'NotNil' checkers.go 167 light_idea_test_case Unused global variable inspection Unused variable 'Equals' checkers.go 198 light_idea_test_case Unused global variable inspection Unused variable 'DeepEquals' checkers.go 223 light_idea_test_case Unused global variable inspection Unused variable 'HasLen' checkers.go 255 light_idea_test_case Unused global variable inspection Unused variable 'ErrorMatches' checkers.go 287 light_idea_test_case Unused global variable inspection Unused variable 'Matches' checkers.go 331 light_idea_test_case Unused global variable inspection Unused variable 'Panics' checkers.go 366 light_idea_test_case Unused global variable inspection Unused variable 'PanicMatches' checkers.go 412 light_idea_test_case Unused global variable inspection Unused variable 'FitsTypeOf' checkers.go 444 light_idea_test_case Unused global variable inspection Unused variable 'Implements' db.go 10 light_idea_test_case Unused global variable inspection Unused variable 'ErrWrongType' db.go 11 light_idea_test_case Unused global variable inspection Unused variable 'ErrExists' db.go 12 light_idea_test_case Unused global variable inspection Unused variable 'ErrWrongID' db.go 13 light_idea_test_case Unused global variable inspection Unused variable 'ErrInvalidKey' errors.go 9 light_idea_test_case Unused global variable inspection Unused variable 'ErrNoRootKeys' errors.go 10 light_idea_test_case Unused global variable inspection Unused variable 'ErrInsufficientKeys' errors.go 9 light_idea_test_case Unused global variable inspection Unused variable 'ErrInitNotAllowed' verify.go 15 light_idea_test_case Unused global variable inspection Unused variable 'ErrMissingKey' verify.go 18 light_idea_test_case Unused global variable inspection Unused variable 'ErrWrongMethod' rpc.go 142 light_idea_test_case Unused global variable inspection Unused variable 'GoRpc' helper.go 131 light_idea_test_case Unused global variable inspection Unused variable 'boolSliceTypId' helper.go 132 light_idea_test_case Unused global variable inspection Unused variable 'uintSliceTypId' helper.go 134 light_idea_test_case Unused global variable inspection Unused variable 'uint16SliceTypId' helper.go 135 light_idea_test_case Unused global variable inspection Unused variable 'uint32SliceTypId' helper.go 137 light_idea_test_case Unused global variable inspection Unused variable 'intSliceTypId' helper.go 138 light_idea_test_case Unused global variable inspection Unused variable 'int8SliceTypId' helper.go 139 light_idea_test_case Unused global variable inspection Unused variable 'int16SliceTypId' helper.go 140 light_idea_test_case Unused global variable inspection Unused variable 'int32SliceTypId' helper.go 142 light_idea_test_case Unused global variable inspection Unused variable 'float32SliceTypId' helper.go 143 light_idea_test_case Unused global variable inspection Unused variable 'float64SliceTypId' helper.go 148 light_idea_test_case Unused global variable inspection Unused variable 'mapIntIntfTypId' helper.go 150 light_idea_test_case Unused global variable inspection Unused variable 'mapUintIntfTypId' helper.go 155 light_idea_test_case Unused global variable inspection Unused variable 'binaryMarshalerTypId' helper.go 156 light_idea_test_case Unused global variable inspection Unused variable 'binaryUnmarshalerTypId' helper.go 161 light_idea_test_case Unused global variable inspection Unused variable 'bsAll0x00' msgpack.go 805 light_idea_test_case Unused global variable inspection Unused variable 'MsgpackSpecRpc' hcsshim.go 89 light_idea_test_case Unused global variable inspection Unused variable 'temp' encode.go 30 light_idea_test_case Unused global variable inspection Unused variable 'errAnything' hybi.go 45 light_idea_test_case Unused global variable inspection Unused variable 'ErrBadPongMessage' hybi.go 46 light_idea_test_case Unused global variable inspection Unused variable 'ErrBadClosingStatus' websocket.go 54 light_idea_test_case Unused global variable inspection Unused variable 'ErrBadFrame' websocket.go 55 light_idea_test_case Unused global variable inspection Unused variable 'ErrBadFrameBoundary' websocket.go 382 light_idea_test_case Unused global variable inspection Unused variable 'Message' websocket.go 412 light_idea_test_case Unused global variable inspection Unused variable 'JSON' command.go 25 light_idea_test_case Unused global variable inspection Unused variable 'Commands' parse.go 23 light_idea_test_case Unused global variable inspection Unused variable 'ErrConflictSharedNetwork' parse.go 25 light_idea_test_case Unused global variable inspection Unused variable 'ErrConflictHostNetwork' parse.go 27 light_idea_test_case Unused global variable inspection Unused variable 'ErrConflictNoNetwork' requirements.go 120 light_idea_test_case Unused global variable inspection Unused variable 'NotOverlay' docker_test_vars.go 17 light_idea_test_case Unused global variable inspection Unused variable 'registryImageName' docker_test_vars.go 39 light_idea_test_case Unused global variable inspection Unused variable 'daemonDefaultImage' ================================================ FILE: testData/performance/GoUnusedImport/expected.xml ================================================ consul.go 13 light_idea_test_case Unused import inspection Redundant alias zookeeper.go 9 light_idea_test_case Unused import inspection Redundant alias dbstore.go 11 light_idea_test_case Unused import inspection Redundant alias criurpc.pb.go 27 light_idea_test_case Unused import inspection Redundant alias criurpc.pb.go 28 light_idea_test_case Unused import inspection Redundant alias ================================================ FILE: testData/performance/GoUnusedVariable/expected.xml ================================================ firewalld.go 128 light_idea_test_case Unused variable inspection Unused variable 'pf' ================================================ FILE: testData/performance/performanceA.go ================================================ package main //var a int = 1 func main() { a := 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 print(a) } ================================================ FILE: testData/performance/performanceA2.go ================================================ package main var a int = 1 func main() { a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 a = 1 print(a) } ================================================ FILE: testData/psi/importDeclaration/addImportBeforeFunction.go ================================================ package test import "test" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/addImportBeforeFunction_after.go ================================================ package test import ( "test" "package/path" ) func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/addImportToEmptyList.go ================================================ package test ================================================ FILE: testData/psi/importDeclaration/addImportToEmptyListBeforeFunction.go ================================================ package test func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/addImportToEmptyListBeforeFunction_after.go ================================================ package test import "package/path" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/addImportToEmptyList_after.go ================================================ package test import "package/path" ================================================ FILE: testData/psi/importDeclaration/addImportToListWithMultiSpecDeclaration.go ================================================ package test import ( "test" "test2") ================================================ FILE: testData/psi/importDeclaration/addImportToListWithMultiSpecDeclaration_after.go ================================================ package test import ( "test" "test2" "package/path" ) ================================================ FILE: testData/psi/importDeclaration/addImportToListWithSingleSpecDeclaration.go ================================================ package test import "test" ================================================ FILE: testData/psi/importDeclaration/addImportToListWithSingleSpecDeclarationWithParens.go ================================================ package test import ( "test" ) ================================================ FILE: testData/psi/importDeclaration/addImportToListWithSingleSpecDeclarationWithParens_after.go ================================================ package test import ( "test" "package/path" ) ================================================ FILE: testData/psi/importDeclaration/addImportToListWithSingleSpecDeclaration_after.go ================================================ package test import ( "test" "package/path" ) ================================================ FILE: testData/psi/importDeclaration/doNotModifyCImport_1.go ================================================ package test /* #cgo LDFLAGS: -L${SRCDIR}/libs -lopus #include "include/opus.h" */ import "C" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/doNotModifyCImport_1_after.go ================================================ package test /* #cgo LDFLAGS: -L${SRCDIR}/libs -lopus #include "include/opus.h" */ import "C" import "package/path" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/doNotModifyCImport_2.go ================================================ package test import "test" /* #cgo LDFLAGS: -L${SRCDIR}/libs -lopus #include "include/opus.h" */ import "C" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/doNotModifyCImport_2_after.go ================================================ package test import ( "test" "package/path" ) /* #cgo LDFLAGS: -L${SRCDIR}/libs -lopus #include "include/opus.h" */ import "C" func hello() string { return "hello" } ================================================ FILE: testData/psi/importDeclaration/invalidImport.go ================================================ package main; import func main() { vendorpackage.Hello() } ================================================ FILE: testData/psi/importDeclaration/invalidImport2.go ================================================ package main import ( "fmt2" "fe func main() { fmt.Println("") } ================================================ FILE: testData/psi/importDeclaration/invalidImport2_after.go ================================================ package main import ( "fmt2" "fe" "package/path" ) func main() { fmt.Println("") } ================================================ FILE: testData/psi/importDeclaration/invalidImport_after.go ================================================ package main; import import "package/path" func main() { vendorpackage.Hello() } ================================================ FILE: testData/psi/resolve/builtin/BuiltinConversion.go ================================================ package main var a = /*ref*/int(3) ================================================ FILE: testData/psi/resolve/builtin/BuiltinTypes.go ================================================ package main type A /*ref*/int ================================================ FILE: testData/psi/resolve/builtin/MethodName.go ================================================ package main func F() { /*ref*/len() } ================================================ FILE: testData/psi/resolve/builtin/ParameterType.go ================================================ package main func F(a /*ref*/rune) { } ================================================ FILE: testData/psi/resolve/builtin/VarBuiltinType.go ================================================ package main var x /*ref*/int ================================================ FILE: testData/psi/resolve/builtin/VarMethodType.go ================================================ package main func F() { var x /*ref*/float32 } ================================================ FILE: testData/psi/resolve/calls/CallFromTestToMethodDefinedInTestFile/main2_test.go ================================================ package main type T struct { } func f() { r := T() x := r./*ref*/TestMethod() } ================================================ FILE: testData/psi/resolve/calls/CallFromTestToMethodDefinedInTestFile/main_test.go ================================================ package main func (t *T) /*def*/TestMethod() { } ================================================ FILE: testData/psi/resolve/calls/CallToDifferentBuildTargetFiles/disabledFile.go ================================================ // +build disabled package main func function() string { return "Hello" } ================================================ FILE: testData/psi/resolve/calls/CallToDifferentBuildTargetFiles/enabledFile.go ================================================ // +build enabled package main func /*def*/function() string { return "Hello" } ================================================ FILE: testData/psi/resolve/calls/CallToDifferentBuildTargetFiles/main.go ================================================ package main func main() { println(/*ref*/function()) } ================================================ FILE: testData/psi/resolve/calls/CallToEmbeddedInterfaceMethod.go ================================================ package main type Bird interface { /*def*/Fly() } type Swan interface { Bird Swim() } func Play(x Swan) { x./*ref*/Fly() } ================================================ FILE: testData/psi/resolve/calls/CallToFunctionLiteral.go ================================================ package main func main() { var /*def*/good1 = func(s string) { } /*ref*/good1("Hello, world!\n") } ================================================ FILE: testData/psi/resolve/calls/CallToFunctionVariable.go ================================================ package main func Foo() int { return 5 } func main() { /*def*/f := Foo println(Foo(), /*ref*/f()) } ================================================ FILE: testData/psi/resolve/calls/CallToFunctionWithSameNameAsMethod.go ================================================ package main type T int func /*def*/F() { } func (T) F() { } func main() { /*ref*/F() } ================================================ FILE: testData/psi/resolve/calls/CallToFunctionWithSameNameAsMethodAcrossPackages/main.go ================================================ package main import "p1" func main() { p1./*ref*/F() } ================================================ FILE: testData/psi/resolve/calls/CallToFunctionWithSameNameAsMethodAcrossPackages/p1/p1.go ================================================ package p1 type T int func /*def*/F() { } func (T) F() { } ================================================ FILE: testData/psi/resolve/calls/CallToLocalFunction.go ================================================ package main func /*def*/f() { } func main() { /*ref*/f() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalInterfaceMethod.go ================================================ package main type T interface { /*def*/Method1() } func main() { var x T x./*ref*/Method1() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalInterfaceMethodNested.go ================================================ package main type T interface { Method1() T /*def*/Method2() } func main() { var x T x.Method1()./*ref*/Method2() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalInterfaceMethodViaMap.go ================================================ package main type T interface { Method1() T /*def*/Method2() } func main() { var x map[int]T x[1].Method1()./*ref*/Method2() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalInterfaceMethodViaSlice.go ================================================ package main type T interface { Method1() T /*def*/Method2() } func main() { var x []T x[1].Method1()./*ref*/Method2() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalInterfaceMethodViaTypeAssert.go ================================================ package main type T interface { Method1() T /*def*/Method2() } func main() { x.(T).Method1()./*ref*/Method2() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethod.go ================================================ package main type T int func (t T) /*def*/Fyy() { } func main() { var x T x./*ref*/Fyy() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodByPointer.go ================================================ package main type T int func (t *T) /*def*/Fyy() { } func main() { var x *T x./*ref*/Fyy() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodNested.go ================================================ package main type T int func (t T) /*def*/F1() { } func (t T) F2() T { } func main() { var x T x.F2()./*ref*/F1() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodViaMap.go ================================================ package main type T int func (t T) /*def*/F1() { } func (t T) F2() T { } func main() { var x map[int]T x[1].F2()./*ref*/F1() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodViaShortVarDeclaration.go ================================================ package main type T int func (t T) /*def*/F1() { } func (t T) F2() T { } func main() { x := t.(T) x.F2()./*ref*/F1() } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodViaSlice.go ================================================ package main type T int func (t T) /*def*/F1() { } func (t T) F2() T { } func _(x map[int]T) { x[1].F2()./*ref*/F1() } func main() { } ================================================ FILE: testData/psi/resolve/calls/CallToLocalMethodViaTypeAssert.go ================================================ package main type T int func (t T) /*def*/F1() { } func (t T) F2() T { } func main() { x.(T).F2()./*ref*/F1() } ================================================ FILE: testData/psi/resolve/calls/CallToMethodDefinedInTestFile/main.go ================================================ package main type T struct { } func f() { r := T() x := r./*no ref*/TestMethod() } ================================================ FILE: testData/psi/resolve/calls/CallToMethodDefinedInTestFile/main_test.go ================================================ package main func (t *T) /*def*/TestMethod() { } ================================================ FILE: testData/psi/resolve/calls/CallToMethodParameter.go ================================================ package main func F(/*def*/n func()) { /*ref*/n() // <-- first place } ================================================ FILE: testData/psi/resolve/calls/CallToMethodViaShortVar/main.go ================================================ package main import "test" func f() { r := test.Method() x := r./*ref*/ActualMethod() } ================================================ FILE: testData/psi/resolve/calls/CallToMethodViaShortVar/test/test.go ================================================ package test type T struct { } func Method() *T { return nil } func (t *T) /*def*/ActualMethod() { } ================================================ FILE: testData/psi/resolve/calls/CallToMethodWithTheSameNameAsFunction.go ================================================ package main type T int func F() { } func (T) /*def*/F() { } func main() { T(1)./*ref*/F() } ================================================ FILE: testData/psi/resolve/calls/CallToMethodWithTheSameNameAsFunctionAcrossPackages/main.go ================================================ package main import "p1" func main() { p1.T(1)./*ref*/F() } ================================================ FILE: testData/psi/resolve/calls/CallToMethodWithTheSameNameAsFunctionAcrossPackages/p1/p1.go ================================================ package p1 type T int func F() { } func (T) /*def*/F() { } ================================================ FILE: testData/psi/resolve/calls/ConversionToImportedFunction/main.go ================================================ package main import "test" func main() { println(test./*ref*/Func(10)) } ================================================ FILE: testData/psi/resolve/calls/ConversionToImportedFunction/test/test.go ================================================ package test func /*def*/Func() { } ================================================ FILE: testData/psi/resolve/calls/ConversionToImportedType/main.go ================================================ package main import "test" func main() { println(test./*ref*/Type(10)) } ================================================ FILE: testData/psi/resolve/calls/ConversionToImportedType/test/test.go ================================================ package test type /*def*/Type int ================================================ FILE: testData/psi/resolve/calls/ConversionToLocallyImportedType/main.go ================================================ package main import . "test" func main() { println(/*ref*/Type(10)) } ================================================ FILE: testData/psi/resolve/calls/ConversionToLocallyImportedType/test/test.go ================================================ package test type /*def*/Type int ================================================ FILE: testData/psi/resolve/calls/DirectlyInheritedMethodSet.go ================================================ package main type Common struct { } type Derived struct { Common derivedMember int } func (c*Common) /*def*/commonMethod() { } func (c*Derived) derivedMethod() { } func f() { var x Derived x./*ref*/commonMethod(); } ================================================ FILE: testData/psi/resolve/calls/FunctionInSamePackageDifferentFile/callee.go ================================================ package bananarama; func /*def*/Call() { } ================================================ FILE: testData/psi/resolve/calls/FunctionInSamePackageDifferentFile/caller.go ================================================ package bananarama; func main() { /*ref*/Call(); } ================================================ FILE: testData/psi/resolve/calls/GrandParentDirectlyInheritedMethodSet.go ================================================ package main type MoreCommon struct { } type Common struct { MoreCommon } type Derived struct { Common derivedMember int } func (c*MoreCommon) /*def*/moreCommonMethod() { } func (c*Common) commonMethod() { } func (c*Derived) derivedMethod() { } func f() { var x Derived x./*ref*/moreCommonMethod(); } ================================================ FILE: testData/psi/resolve/calls/ImportedEmbeddedTypeMethod/main.go ================================================ package main import "p" type SomeOtherFoo struct { p.Embedded } func (s SomeOtherFoo) GetThing() string { return "" } type Foo struct { SomeOtherFoo } func test() { x := Foo{} x./*ref*/Get("asdf") } func main() { } ================================================ FILE: testData/psi/resolve/calls/ImportedEmbeddedTypeMethod/p/p.go ================================================ package p type Embedded struct { } func (s Embedded) /*def*/Get(string) string { return "" } ================================================ FILE: testData/psi/resolve/calls/NoConversionToBlankImportedType/main.go ================================================ package main import _ "test" func main() { println(/*no ref*/Type(10)) } ================================================ FILE: testData/psi/resolve/calls/NoConversionToBlankImportedType/test/test.go ================================================ package test type Type int ================================================ FILE: testData/psi/resolve/calls/RecursiveMethodCall.go ================================================ package main func /*def*/F(n int) int { if n <= 1 { return 1 } return n * /*ref*/F(n-1) } ================================================ FILE: testData/psi/resolve/calls/RelativePackageReference/main/main.go ================================================ package main import "../test2" func main() { x := test2./*ref*/Exported } ================================================ FILE: testData/psi/resolve/calls/RelativePackageReference/test2/test2.go ================================================ package test2 var /*def*/Exported = 10 ================================================ FILE: testData/psi/resolve/calls/RelativePackageReferenceDeep/level1/level2/level2.go ================================================ package level2 var /*def*/Exported = 10 ================================================ FILE: testData/psi/resolve/calls/RelativePackageReferenceDeep/level1/main/main.go ================================================ package main import "../../level1/level2" func main() { x := level2./*ref*/Exported } ================================================ FILE: testData/psi/resolve/calls/TypeConversionToLocalType.go ================================================ package main type /*def*/f int func ff() { } func main() { /*ref*/f() } ================================================ FILE: testData/psi/resolve/composite/ExpressionKey.go ================================================ package main type error interface { Error() string } type scanError struct { err error } func (s *ss) error(/*def*/err error) { panic(scanError{/*ref*/err}) } ================================================ FILE: testData/psi/resolve/composite/KeyAsConstantExpression.go ================================================ package main const /*def*/MyConstant = "Hello" type MyMap map[string]int var MyVar = MyMap{ /*ref*/MyConstant:10, } ================================================ FILE: testData/psi/resolve/composite/NestedNamedStruct.go ================================================ package main import "fmt" type T struct { /*def*/a, b int } type T2 struct { a, b int c []T } var x = T2{ c:[]T{{/*ref*/a:1, b:2}} } func main() { fmt.Println(x) } ================================================ FILE: testData/psi/resolve/composite/NestedStruct.go ================================================ package main type T struct { /*def*/a, b int } type T2 struct { a, b int c T } var x = T2{ c:T{/*ref*/a:1, b:2} } ================================================ FILE: testData/psi/resolve/composite/PromotedAnonymousField1.go ================================================ package main type T1 struct { /*def*/intValue int } type T2 struct { T1 } func foo(t2 T2) { t2./*ref*/intValue } ================================================ FILE: testData/psi/resolve/composite/PromotedAnonymousField2.go ================================================ package main type T1 struct { /*def*/t1Value int } type T2 struct { T1 } type T3 struct { T2 } type T4 struct { T3 } func foo(t4 T4) { t4./*ref*/t1Value } ================================================ FILE: testData/psi/resolve/composite/PromotedAnonymousField3.go ================================================ package main type T1 struct { value int } type T2 struct { T1 /*def*/value int } type T3 struct { T2 } type T4 struct { T3 } func foo(t4 T4) { t4./*ref*/value } ================================================ FILE: testData/psi/resolve/composite/PromotedAnonymousField4.go ================================================ package main type T1 struct { value int } type T2 struct { T1 } type T3 struct { /*def*/T2 } type T4 struct { T3 } func foo(t4 T4) { t4./*ref*/T2 } ================================================ FILE: testData/psi/resolve/composite/TypeName.go ================================================ package main type T struct { /*def*/a, b int c *T } var x = T{/*ref*/a:1, b:2, c:nil } ================================================ FILE: testData/psi/resolve/composite/TypeNameArray.go ================================================ package main type T struct { /*def*/a, b int c *T } var x = [1]T{ {/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeNameMap.go ================================================ package main type T struct { /*def*/a, b int c *T } var x = map[string]T{ "1":{/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeNameSlice.go ================================================ package main type T struct { /*def*/a, b int c *T } var x = []T{ {/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeStruct.go ================================================ package main var x = struct { /*def*/a, b int c *T }{/*ref*/a:1, b:2, c:nil } ================================================ FILE: testData/psi/resolve/composite/TypeStructArray.go ================================================ package main var x = [1]struct { /*def*/a, b int c *T }{ {/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeStructMap.go ================================================ package main var x = map[string]struct { /*def*/a, b int c *T }{ "1": {/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeStructSlice.go ================================================ package main var x = []struct { /*def*/a, b int c *T }{ {/*ref*/a:1, b:2, c:nil} } ================================================ FILE: testData/psi/resolve/composite/TypeSwitch.go ================================================ package main type S struct { /*def*/a int } func main() { var a interface{} switch t := a.(type) { case S: println(t./*ref*/a) } } ================================================ FILE: testData/psi/resolve/package/ImportAlias.go ================================================ package main import /*def*/xx "a" func main() { /*ref*/xx. } ================================================ FILE: testData/psi/resolve/struct/AnonymousDirectStructField.go ================================================ package main type T1 int type T2 struct { a, b, c int /*def*/T1 } func main() { var x = T2{} x./*ref*/T1 } ================================================ FILE: testData/psi/resolve/struct/DirectExportedFieldFromImportedPackage/main.go ================================================ package main import "pack" func main() { var x = pack.S{} x./*ref*/A } ================================================ FILE: testData/psi/resolve/struct/DirectExportedFieldFromImportedPackage/pack/pack.go ================================================ package pack type S struct { AA, /*def*/A, B, C, AA int } ================================================ FILE: testData/psi/resolve/struct/DirectPrivateFieldFromImportedPackage/main.go ================================================ package main import "pack" func main() { var x = pack.S{} x./*no ref*/a } ================================================ FILE: testData/psi/resolve/struct/DirectPrivateFieldFromImportedPackage/pack/pack.go ================================================ package pack type S struct { AA, a, B, C, AA int } ================================================ FILE: testData/psi/resolve/struct/DirectStructField.go ================================================ package main type S struct { b, c, /*def*/a int } func main() { var x = S{} x./*ref*/a } ================================================ FILE: testData/psi/resolve/struct/FieldVsParam.go ================================================ package main type A struct { /*def*/b int c int } func NewA(b int) *A { return &A{ /*ref*/b: b, c: 1, } } ================================================ FILE: testData/psi/resolve/struct/FieldVsParam2.go ================================================ package main type A struct { b int c int } func NewA(/*def*/b int) *A { return &A{ b: /*ref*/b, c: 1, } } ================================================ FILE: testData/psi/resolve/struct/FieldVsParam3.go ================================================ package main func _() { /*def*/addr := "test" x := struct{ addr string }{addr: /*ref*/addr} fmt.Println(x) } ================================================ FILE: testData/psi/resolve/struct/FieldVsParam4.go ================================================ package main func _() { addr := "test" x := struct{ /*def*/addr string }{/*ref*/addr: addr} fmt.Println(x) } ================================================ FILE: testData/psi/resolve/struct/PromotedStructField.go ================================================ package main type S1 struct { /*def*/a, b int } type S2 struct { c, d int S1 } func main() { var x = S2{} x./*ref*/a } ================================================ FILE: testData/psi/resolve/struct/StructFieldInMap.go ================================================ package main type S struct { /*def*/a int } func main() { _ = map[string][]S{ "key": {{/*ref*/a: 5}}, } } ================================================ FILE: testData/psi/resolve/types/CompositeLiteralFromImportedPackage/datatier/datatier.go ================================================ package datatier type /*def*/MyType string ================================================ FILE: testData/psi/resolve/types/CompositeLiteralFromImportedPackage/main/main.go ================================================ package main import "datatier" var MyVar datatier./*ref*/MyType == 1 func main() { } ================================================ FILE: testData/psi/resolve/types/DontResolveIfImportedInAnotherFileSamePackage/imported/imported.go ================================================ package imported type Type int ================================================ FILE: testData/psi/resolve/types/DontResolveIfImportedInAnotherFileSamePackage/main1.go ================================================ package main type t imported./*no ref*/Type ================================================ FILE: testData/psi/resolve/types/DontResolveIfImportedInAnotherFileSamePackage/main2.go ================================================ package main import "imported" type t1 imported.Type ================================================ FILE: testData/psi/resolve/types/FromCustomImportedPackage/main.go ================================================ package main import test_x "test" var x test_x./*ref*/ExportedType func main() { } ================================================ FILE: testData/psi/resolve/types/FromCustomImportedPackage/test/packageTest.go ================================================ package test; type /*def*/ExportedType int; ================================================ FILE: testData/psi/resolve/types/FromDefaultImportedPackage/main.go ================================================ package main import "test" var x test./*ref*/ExportedType func main() { } ================================================ FILE: testData/psi/resolve/types/FromDefaultImportedPackage/test/packageTest.go ================================================ package test; type /*def*/ExportedType int; ================================================ FILE: testData/psi/resolve/types/FromInjectedPackage/main.go ================================================ package main import . "test" var x /*ref*/ExportedType func main() { } ================================================ FILE: testData/psi/resolve/types/FromInjectedPackage/test/packageTest.go ================================================ package test; type /*def*/ExportedType int; ================================================ FILE: testData/psi/resolve/types/FromLowerCasePackageInMixedCaseFolder/Gongo/gongo.go ================================================ package gongo type /*def*/MyType string ================================================ FILE: testData/psi/resolve/types/FromLowerCasePackageInMixedCaseFolder/main.go ================================================ package main import "Gongo" // unused import error here var MyVar = gongo./*ref*/MyType{} // unresolved symbol error here func main() { } ================================================ FILE: testData/psi/resolve/types/FromMethodReceiver.go ================================================ package main type /*def*/T struct { a, b int } func (t */*ref*/T) f() { } ================================================ FILE: testData/psi/resolve/types/FromMixedCaseImportedPackage/dataTier/dataTier.go ================================================ package dataTier type /*def*/MyType string ================================================ FILE: testData/psi/resolve/types/FromMixedCaseImportedPackage/main.go ================================================ package main import "dataTier" // unused import error here var MyVar dataTier./*ref*/MyType = "" // unresolved symbol error here ================================================ FILE: testData/psi/resolve/types/FromMultipleImportedPackage/imported/imported1.go ================================================ package imported type ImportedType1 int ================================================ FILE: testData/psi/resolve/types/FromMultipleImportedPackage/imported/imported2.go ================================================ package imported type ( /*def*/ImportedType int A string ) ================================================ FILE: testData/psi/resolve/types/FromMultipleImportedPackage/main.go ================================================ package main import "imported" var x imported./*ref*/ImportedType = 10 func main() { } ================================================ FILE: testData/psi/resolve/types/FunctionTypeByRef.go ================================================ package main import ( "fmt" ) type S struct { /*def*/a int } type F func() []S var f F = func() []S { return make([]S, 1) } func main() { fmt.Println(f()[0]./*ref*/a) } ================================================ FILE: testData/psi/resolve/types/IgnoreBlankImportedPackage/main.go ================================================ package main import _ "test" var x /*no ref*/test.ExportedType func main() { } ================================================ FILE: testData/psi/resolve/types/IgnoreBlankImportedPackage/packageTest.go ================================================ package test; type ExportedType int; ================================================ FILE: testData/psi/resolve/types/IgnoreBlankImportedPackage/packageTest2.go ================================================ package test2; type ExportedType int; ================================================ FILE: testData/psi/resolve/types/LocalType.go ================================================ package main type /*def*/Type int func main() { var a /*ref*/Type = 10 } ================================================ FILE: testData/psi/resolve/types/MethodsOrder.go ================================================ package main type One struct {} func (m *One) Method() {} type Two struct { One } type Three struct { One } func (m *Three) /*def*/Method() {} func main() { one := One{} one.Method() two := Two{} two.Method() three := Three{} three./*ref*/Method() } ================================================ FILE: testData/psi/resolve/types/ResolveArrayInRange.go ================================================ package main; import ( "fmt" ) func aaa() { fmt.Println() } type RateHistoryResponse struct {} type RateHistoryResponses []RateHistoryResponse func (r *RateHistoryResponses) persist() { for _, rh := range []RateHistoryResponse(*r) { rh./*ref*/persist() } } func (r *RateHistoryResponse) /*def*/persist() { } ================================================ FILE: testData/psi/resolve/types/ResolveTypeInCast.go ================================================ package main import "unsafe" type emptyInterface struct { /*def*/typ uintptr word unsafe.Pointer } func TypId(i interface{}) uintptr { return (*emptyInterface)(unsafe.Pointer(&i))./*ref*/typ } ================================================ FILE: testData/psi/resolve/types/ResolveTypeNameInTypeSpec.go ================================================ package main type /*def*/Type int type T2 /*ref*/Type ================================================ FILE: testData/psi/resolve/vars/AnonymousFunctionInvocation.go ================================================ package main func someFunc(){ /*def*/sub1 := func(){ } /*ref*/sub1() } func main() { } ================================================ FILE: testData/psi/resolve/vars/ChainedSelector.go ================================================ package main var /*def*/x int func method() { /*ref*/x. a.b() } ================================================ FILE: testData/psi/resolve/vars/DeclarationInsideLabeledStatement.go ================================================ package main func main2() { Test: /*def*/i := 0 println(i) if /*ref*/i > 0 { goto Test } } ================================================ FILE: testData/psi/resolve/vars/DeclaredInForClause.go ================================================ package main const i iota func main() { i := 1 for /*def*/i := 1;; i++ { y := /*ref*/i } } ================================================ FILE: testData/psi/resolve/vars/DeclaredInForRange1.go ================================================ package main const key = iota func main() { key := 1 for /*def*/key, val := range m { y := /*ref*/key } } ================================================ FILE: testData/psi/resolve/vars/DeclaredInForRange2.go ================================================ package main const i = iota func main() { i := 0 for /*def*/i, _ := range m { println(/*ref*/i) } } ================================================ FILE: testData/psi/resolve/vars/DeclaredInForRangeAsValue.go ================================================ package main const key2 = iota func main() { key1 := 1 for key1, /*def*/key2 := range { x := /*ref*/key2 } } ================================================ FILE: testData/psi/resolve/vars/DefaultImportDifferentPackage/main.go ================================================ package main import "test" var x = test./*ref*/Var ================================================ FILE: testData/psi/resolve/vars/DefaultImportDifferentPackage/test/file.go ================================================ package test var /*def*/Var = 10 ================================================ FILE: testData/psi/resolve/vars/DontProcessExpressions.go ================================================ package main func main() { fs := *(*func(width int) struct{})(nil) /*def*/width := 1 _, _ = fs, /*ref*/width } ================================================ FILE: testData/psi/resolve/vars/FromCustomImportedPackage/main.go ================================================ package main import tictic "test" var x = tictic./*ref*/Var ================================================ FILE: testData/psi/resolve/vars/FromCustomImportedPackage/test/test.go ================================================ package test var /*def*/Var = 10 ================================================ FILE: testData/psi/resolve/vars/FromDefaultImportedPackage/main.go ================================================ package main import "test" var x = test1./*ref*/Var ================================================ FILE: testData/psi/resolve/vars/FromDefaultImportedPackage/test/test.go ================================================ package test1 var /*def*/Var = 10 ================================================ FILE: testData/psi/resolve/vars/FromInjectedImportedPackage/main.go ================================================ package main import . "test" var x = /*ref*/Var ================================================ FILE: testData/psi/resolve/vars/FromInjectedImportedPackage/test/test.go ================================================ package test const /*def*/Var = 10 ================================================ FILE: testData/psi/resolve/vars/GlobalConstDeclaration.go ================================================ package main const /*def*/x = iota func main() { println(/*ref*/x) } ================================================ FILE: testData/psi/resolve/vars/GlobalShadowedVarDeclaration.go ================================================ package main var x int = 10 func main() { /*def*/x := 20 println(/*ref*/x) } ================================================ FILE: testData/psi/resolve/vars/GlobalVarDeclaration.go ================================================ package main var /*def*/x int = 10 func main() { println(/*ref*/x) } ================================================ FILE: testData/psi/resolve/vars/GlobalVarDeclarationFromBlock.go ================================================ package main var /*def*/x int = 10 func main() { if true { /*ref*/x = 100 } println(x) } ================================================ FILE: testData/psi/resolve/vars/LocalConstDeclaration.go ================================================ package main func main() { const /*def*/CC = 3 println(/*ref*/CC) } ================================================ FILE: testData/psi/resolve/vars/LocalPackageDefinitionsShouldBeResolvedFirst/package1/package1.go ================================================ package package1 type Type int ================================================ FILE: testData/psi/resolve/vars/LocalPackageDefinitionsShouldBeResolvedFirst/package2/package21.go ================================================ package package2 type /*def*/Type int ================================================ FILE: testData/psi/resolve/vars/LocalPackageDefinitionsShouldBeResolvedFirst/package2/package22.go ================================================ package package2 import "package1" func GetType() /*ref*/Type { return nil } ================================================ FILE: testData/psi/resolve/vars/MethodReturn.go ================================================ package main func function(a, b int) (/*def*/c, d int) { /*ref*/c, d = b, a return } ================================================ FILE: testData/psi/resolve/vars/MethodReturn2.go ================================================ package main func gen1() (/*def*/g1v int) { /*ref*/g1v = 5 return } ================================================ FILE: testData/psi/resolve/vars/MultipleApplications/Application1/main.go ================================================ package main func main() { /*no ref*/Test() } ================================================ FILE: testData/psi/resolve/vars/MultipleApplications/Application1/test.go ================================================ package main func Test1() { } ================================================ FILE: testData/psi/resolve/vars/MultipleApplications/Application2/main.go ================================================ package main func main() { Test1() } ================================================ FILE: testData/psi/resolve/vars/MultipleApplications/Application2/test.go ================================================ package main func Test() { } ================================================ FILE: testData/psi/resolve/vars/MultipleGlobalConsts.go ================================================ package main const ( a = /*ref*/b /*def*/b = 10 ) func main() { println(a, b) } ================================================ FILE: testData/psi/resolve/vars/MultipleGlobalVars.go ================================================ package main var ( bb = /*ref*/cc /*def*/cc = 1 ) func main() { println(bb, cc) } ================================================ FILE: testData/psi/resolve/vars/RangeExpressionVarsShouldNotResolveToRangeVars.go ================================================ package main import "bytes" func main() { var /*def*/b bytes.Buffer for i, b := range /*ref*/b { _, _ = i, b } } ================================================ FILE: testData/psi/resolve/vars/ResolveMethodReceiver.go ================================================ package main func (/*def*/p *Point) Length() float64 { return math.Sqrt(p.x * /*ref*/p.x + p.y * p.y) } ================================================ FILE: testData/psi/resolve/vars/ResolveToFunctionName.go ================================================ package main func /*def*/Pff() { println("hi") } func F(func()) { } func main() { F(/*ref*/Pff) // <-- second place } ================================================ FILE: testData/psi/resolve/vars/ResolveToMethodName.go ================================================ package main func (*int) Pmm() { println("hi") } func F(func()) { } func main() { F(/*no ref*/Pmm) // <-- second place } ================================================ FILE: testData/psi/resolve/vars/ShortAssignToReturnVar.go ================================================ package main func Test(x int) (/*def*/r int) { /*ref*/r, a := x, 1 _ = a return } ================================================ FILE: testData/psi/resolve/vars/ShortVarDeclaration.go ================================================ package main func main() { /*def*/x := 10 println(/*ref*/x) } ================================================ FILE: testData/psi/resolve/vars/ShortVarDeclarationFromBlock.go ================================================ package main func main() { /*def*/x, test := 10, true if test { /*ref*/x = 11 } println(x) } ================================================ FILE: testData/psi/resolve/vars/ShortVarDeclarationFromSelectClause.go ================================================ package main func main() { i := 1 select { case /*def*/i := <-c: { /*ref*/i } } } ================================================ FILE: testData/psi/resolve/vars/ShortVarRedeclaration.go ================================================ package main func main() { /*def*/x := 10 x, a := 11, 2 println(/*ref*/x, a) } ================================================ FILE: testData/psi/resolve/vars/SimpleMethodParameter.go ================================================ package main func method(/*def*/x int) { /*ref*/x } ================================================ FILE: testData/psi/resolve/vars/StructFieldViaChannel.go ================================================ package main type polar struct { /*def*/radius float64 theta float64 } func foo(thing chan polar) { aPolarObject := <-thing aPolarObject./*ref*/radius } ================================================ FILE: testData/psi/resolve/vars/VarDeclarationInSelectCommClauseDefault.go ================================================ package main func main() { select { case: { /*def*/test := 1 print(/*ref*/test) } } } ================================================ FILE: testData/psi/resolve/vars/VarDeclarationInSelectCommClauseRecv.go ================================================ package main func main() { var ch = make(chan int) select { case ch <- 1: { /*def*/test := 1 print(/*ref*/test) } } } ================================================ FILE: testData/psi/resolve/vars/VarDeclarationInSelectCommClauseSend.go ================================================ package main func main() { var ch = make(chan int) select { case test := <-ch: { /*def*/test := 1 print(/*ref*/test) } } } ================================================ FILE: testData/psi/resolve/vars/VarDeclarationOutsideSwitch.go ================================================ package main func demoFunc(/*def*/demo1 int) { switch { case 1==2 : demo1 := 1 default: } _ = /*ref*/demo1 } ================================================ FILE: testData/psi/resolve/vars/VarDereferenceAsTypeCast.go ================================================ package main type Foo struct { Things []string } func doSomething() *Foo { return &Foo{} } func main() { /*def*/foo := doSomething() // foo marked as Unused for _, v := range (*/*ref*/foo).Things { // foo marked as Unresolved _ = v } } ================================================ FILE: testData/psi/resolve/vars/VarInSwitchExpr.go ================================================ package main func main() (int) { switch e { case a: /*def*/x := a; return /*ref*/x } return nil } ================================================ FILE: testData/psi/resolve/vars/VarInSwitchExprInitialization.go ================================================ package main func main() (int) { switch /*def*/i := 1; e { case a: return /*ref*/i } return nil } ================================================ FILE: testData/psi/resolve/vars/VarInSwitchType.go ================================================ package main func main() (int) { switch x.(type) { case int: /*def*/x := 10; return /*ref*/x } return nil } ================================================ FILE: testData/psi/resolve/vars/VarInSwitchTypeInitialization.go ================================================ package main func main() (int) { switch /*def*/x := 10; x.(type) { case int: return /*ref*/x } return nil } ================================================ FILE: testData/psi/resolve/vars/VarInSwitchTypeWithNamedSwitchGuard.go ================================================ package main func main() (int) { switch /*def*/y := x.(type) { case int: return /*ref*/y } return nil } ================================================ FILE: testData/psi/resolve/vars/VarTypeGuard.go ================================================ package main func Test(/*def*/p interface{}) error { switch p := /*ref*/p.(type) { case error: return nil } return nil } ================================================ FILE: testData/psi/resolve/vars/VarVsInnerTypes.go ================================================ package main func main() { type demo struct { Field1 int } var /*def*/Field1 int /*ref*/Field1 = 1 } ================================================ FILE: testData/quickfixes/add-comma/simple-after.go ================================================ package foo func main() { e12 := S{ a:1, } } ================================================ FILE: testData/quickfixes/add-comma/simple.go ================================================ package foo func main() { e12 := S{ a:1 } } ================================================ FILE: testData/quickfixes/add-missing-return/simple-after.go ================================================ package main func _() int { return } ================================================ FILE: testData/quickfixes/add-missing-return/simple.go ================================================ package main func _() int { } ================================================ FILE: testData/quickfixes/assignment-to-comparison/assignment-after.go ================================================ package foo func demo(v bool) { if a == v { } } ================================================ FILE: testData/quickfixes/assignment-to-comparison/assignment.go ================================================ package foo func demo(v bool) { if a := v { } } ================================================ FILE: testData/quickfixes/assignment-to-comparison/shortVar-after.go ================================================ package foo func demo(v bool) { if a == v { } } ================================================ FILE: testData/quickfixes/assignment-to-comparison/shortVar.go ================================================ package foo func demo(v bool) { if a = v { } } ================================================ FILE: testData/quickfixes/continue-outside-loop/simple-after.go ================================================ package continue_outside_loop func _() { return } ================================================ FILE: testData/quickfixes/continue-outside-loop/simple.go ================================================ package continue_outside_loop func _() { continue } ================================================ FILE: testData/quickfixes/create-type/global-after.go ================================================ package foo type A type ServerFunc func(params A) (error) ================================================ FILE: testData/quickfixes/create-type/global.go ================================================ package foo type ServerFunc func(params A) (error) ================================================ FILE: testData/quickfixes/create-type/prohibited.go ================================================ package foo func main() { a := &fmt.A{} } ================================================ FILE: testData/quickfixes/create-type/simple-after.go ================================================ package foo type A func main() { a := &A{} } ================================================ FILE: testData/quickfixes/create-type/simple.go ================================================ package foo func main() { a := &A{} } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleConstsWithType-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Baz int = 2 Bar int = 1 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleConstsWithType.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleConstsWithoutType-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Baz2 = 2 Bar2 = 1 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleConstsWithoutType.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsOnlyType-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello10 int Hello9 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsOnlyType.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsOnlyValues-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello14 = 2 Hello13 = 1 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsOnlyValues.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsWithTypeAndValues-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello12 int = 2 Hello11 int = 1 Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/multiLineMultipleVarsWithTypeAndValues.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int = 1, 2 Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleConsts-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const ( Hello4 = 4 Hello3 = 3 ) // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleConsts.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleExportedAndPrivateConsts-after.go ================================================ package demo2049 const ( Helllllo = 3 Hello1, hello2, help = 1, 2, 4 ) // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleExportedAndPrivateConsts.go ================================================ package demo2049 const Hello1, hello2, Helllllo, help = 1, 2, 3, 4 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleVars-after.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var ( Hello8 int Hello7 int ) // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/exported-own-declaration/singleLineMultipleVars.go ================================================ package demo2049 const Hello1, hello2, Helllllo = 1, 2, 3 // This is valid const Hello3, Hello4 = 3, 4 // exported const Hello4 should have its own declaration var Hello5, hello6 int // This is valid // exported var Hello8 should have its own declaration var Hello7, Hello8 int // exported var Hello8 should have its own declaration const ( Foo = 1 Bar, Baz int = 1, 2 Bar2, Baz2 = 1, 2 ) var ( Hello9, Hello10 int Hello11, Hello12 int Hello13, Hello14 = 1, 2 ) func _() { _, _, _, _ = Hello5, hello6, Hello7, Hello8 _, _, _, _ = Hello9, Hello10, Hello11, Hello12 _, _ = Hello13, Hello14 } ================================================ FILE: testData/quickfixes/global-constant/doNotSuggestCreatingConstOnAssignment.go ================================================ package foo func main() { a = 1 } ================================================ FILE: testData/quickfixes/global-constant/doNotSuggestCreatingConstOnChanRead.go ================================================ package foo func main() { a <- Struct{"foo"} } ================================================ FILE: testData/quickfixes/global-constant/simple-after.go ================================================ package foo const a = func main() { b := a } ================================================ FILE: testData/quickfixes/global-constant/simple.go ================================================ package foo func main() { b := a } ================================================ FILE: testData/quickfixes/global-variable/simple-after.go ================================================ package foo var a = func main() { b := a } ================================================ FILE: testData/quickfixes/global-variable/simple.go ================================================ package foo func main() { b := a } ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArg-after.go ================================================ package main func main() { a(1,asd()) } func asd() string { } func a(i int, s string) {} ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArg.go ================================================ package main func main() { a(1,asd()) } func a(i int, s string) {} ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArg2-after.go ================================================ package main func main() { a(asd()) } func asd() (int, string) { } func a(i int, s string) {} ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArg2.go ================================================ package main func main() { a(asd()) } func a(i int, s string) {} ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArgWithoutReference-after.go ================================================ package main func main() { a(1,asd()) } func asd() interface{} { } ================================================ FILE: testData/quickfixes/introduce-function/asFunctionArgWithoutReference.go ================================================ package main func main() { a(1,asd()) } ================================================ FILE: testData/quickfixes/introduce-function/dontCreate.go ================================================ package main func main() { asd() } func asd() { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithOneParam-after.go ================================================ package main func main() { var i int asd(i) } func asd(i int) { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithOneParam.go ================================================ package main func main() { var i int asd(i) } ================================================ FILE: testData/quickfixes/introduce-function/funcWithResultType-after.go ================================================ package main func main() { var a int a = asd() } func asd() int { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithResultType.go ================================================ package main func main() { var a int a = asd() } ================================================ FILE: testData/quickfixes/introduce-function/funcWithThreeParams-after.go ================================================ package main func main() { var ( i int r struct {i int} q string ) asd(i, r, q) } func asd(i int, i2 struct {i int}, i3 string) { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithThreeParams.go ================================================ package main func main() { var ( i int r struct {i int} q string ) asd(i, r, q) } ================================================ FILE: testData/quickfixes/introduce-function/funcWithThreeResultValues-after.go ================================================ package main func main() { var ( i int r struct {i int} q string ) i, r, q = asd() } func asd() (int, struct {i int}, string) { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithThreeResultValues.go ================================================ package main func main() { var ( i int r struct {i int} q string ) i, r, q = asd() } ================================================ FILE: testData/quickfixes/introduce-function/funcWithUnknownResultType-after.go ================================================ package main func main() { a = asd() } func asd() interface{} { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithUnknownResultType.go ================================================ package main func main() { a = asd() } ================================================ FILE: testData/quickfixes/introduce-function/funcWithUnknownTypeParam-after.go ================================================ package main func main() { asd(q) } func asd(i interface{}) { } ================================================ FILE: testData/quickfixes/introduce-function/funcWithUnknownTypeParam.go ================================================ package main func main() { asd(q) } ================================================ FILE: testData/quickfixes/introduce-function/inConstDeclaration.go ================================================ package main const ( t = asd() ) func main() { } ================================================ FILE: testData/quickfixes/introduce-function/shortVarDecl-after.go ================================================ package main func main() { i, g, q := asd() } func asd() (interface{}, interface{}, interface{}) { } ================================================ FILE: testData/quickfixes/introduce-function/shortVarDecl.go ================================================ package main func main() { i, g, q := asd() } ================================================ FILE: testData/quickfixes/introduce-function/simpleFunction-after.go ================================================ package main func main() { asd() } func asd() { } ================================================ FILE: testData/quickfixes/introduce-function/simpleFunction.go ================================================ package main func main() { asd() } ================================================ FILE: testData/quickfixes/introduce-function/varSpec-after.go ================================================ package main func main() { var ( q, w, e string a, b, c int = asd() ) } func asd() (int, int, int) { } ================================================ FILE: testData/quickfixes/introduce-function/varSpec.go ================================================ package main func main() { var ( q, w, e string a, b, c int = asd() ) } ================================================ FILE: testData/quickfixes/introduce-function/withChan-after.go ================================================ package main func main() { var ( i chan chan int ) asd(i) } func asd(ints chan chan int) { } ================================================ FILE: testData/quickfixes/introduce-function/withChan.go ================================================ package main func main() { var ( i chan chan int ) asd(i) } ================================================ FILE: testData/quickfixes/local-constant/if-after.go ================================================ package foo func main() { const a = if a { return 1 } } ================================================ FILE: testData/quickfixes/local-constant/if.go ================================================ package foo func main() { if a { return 1 } } ================================================ FILE: testData/quickfixes/local-constant/onAssignment.go ================================================ package foo func main() { a = 1 } ================================================ FILE: testData/quickfixes/local-constant/onChanRead.go ================================================ package foo func main() { a <- Struct{"foo"} } ================================================ FILE: testData/quickfixes/local-constant/onTopLevel.go ================================================ package main var b = a ================================================ FILE: testData/quickfixes/local-constant/resolved-after.go ================================================ package foo func main() { if true { a := 123 _ = a } const a = b := a } ================================================ FILE: testData/quickfixes/local-constant/resolved.go ================================================ package foo func main() { if true { a := 123 _ = a } b := a } ================================================ FILE: testData/quickfixes/local-constant/simple-after.go ================================================ package foo func main() { const a = b := a } ================================================ FILE: testData/quickfixes/local-constant/simple.go ================================================ package foo func main() { b := a } ================================================ FILE: testData/quickfixes/local-constant/unresolved-after.go ================================================ package foo func main() { const a = if true { _ = a } b := a } ================================================ FILE: testData/quickfixes/local-constant/unresolved.go ================================================ package foo func main() { if true { _ = a } b := a } ================================================ FILE: testData/quickfixes/local-variable/if-after.go ================================================ package foo func main() { a := if a { return 1 } } ================================================ FILE: testData/quickfixes/local-variable/if.go ================================================ package foo func main() { if a { return 1 } } ================================================ FILE: testData/quickfixes/local-variable/onTopLevel.go ================================================ package main var b = a ================================================ FILE: testData/quickfixes/local-variable/resolved-after.go ================================================ package foo func main() { if true { a := 123 _ = a } a := b := a } ================================================ FILE: testData/quickfixes/local-variable/resolved.go ================================================ package foo func main() { if true { a := 123 _ = a } b := a } ================================================ FILE: testData/quickfixes/local-variable/simple-after.go ================================================ package foo func main() { a := b := a } ================================================ FILE: testData/quickfixes/local-variable/simple.go ================================================ package foo func main() { b := a } ================================================ FILE: testData/quickfixes/local-variable/unresolved-after.go ================================================ package foo func main() { a := if true { _ = a } b := a } ================================================ FILE: testData/quickfixes/local-variable/unresolved.go ================================================ package foo func main() { if true { _ = a } b := a } ================================================ FILE: testData/quickfixes/multiple-packages/a-after.go ================================================ package a ================================================ FILE: testData/quickfixes/multiple-packages/a.go ================================================ package a ================================================ FILE: testData/quickfixes/multiple-packages/b-after.go ================================================ package a ================================================ FILE: testData/quickfixes/multiple-packages/b.go ================================================ package b ================================================ FILE: testData/quickfixes/multiple-packages/b_test-after.go ================================================ package a_test ================================================ FILE: testData/quickfixes/multiple-packages/b_test.go ================================================ package b_test ================================================ FILE: testData/quickfixes/multiple-packages/c_test-after.go ================================================ package a ================================================ FILE: testData/quickfixes/multiple-packages/c_test.go ================================================ package c ================================================ FILE: testData/quickfixes/rename-function/simple-after.go ================================================ package foo func _() { } ================================================ FILE: testData/quickfixes/rename-function/simple.go ================================================ package foo func unused() { } ================================================ FILE: testData/quickfixes/rename-var/prohibited.go ================================================ package foo func main() { a, b := demo() _ = a _ = b } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignmentOnRange-after.go ================================================ package foo func main() { for _ = range "asdf" { } } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignmentOnRange.go ================================================ package foo func main() { for foo := range "asdf"{ } } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_1-after.go ================================================ package foo func main() { _, bar := 0 } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_1.go ================================================ package foo func main() { foo, bar := 0 } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_2-after.go ================================================ package foo func main() { _, _ = 0 } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_2.go ================================================ package foo func main() { foo, _ := 0 } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_3-after.go ================================================ package foo func main() { _ = 0 } ================================================ FILE: testData/quickfixes/rename-var/renameAndReplaceWithAssignment_3.go ================================================ package foo func main() { foo := 0 } ================================================ FILE: testData/quickfixes/rename-var/simple-after.go ================================================ package foo func main() { a, _ := demo() _ = a } ================================================ FILE: testData/quickfixes/rename-var/simple.go ================================================ package foo func main() { a, b := demo() _ = a } ================================================ FILE: testData/quickfixes/replace-with-assignment/rangeClause-after.go ================================================ package main func main() { c := make(chan int) for _ = range "asd" { fmt.Printf("%v\n", 1) } } ================================================ FILE: testData/quickfixes/replace-with-assignment/rangeClause.go ================================================ package main func main() { c := make(chan int) for _ := range "asd" { fmt.Printf("%v\n", 1) } } ================================================ FILE: testData/quickfixes/replace-with-assignment/recvStatement-after.go ================================================ package main func main() { c := make(chan int) buzz := 0 println(buzz) buzz = <-c } ================================================ FILE: testData/quickfixes/replace-with-assignment/recvStatement.go ================================================ package main func main() { c := make(chan int) buzz := 0 println(buzz) buzz := <-c } ================================================ FILE: testData/quickfixes/replace-with-assignment/recvStatementInSelect-after.go ================================================ package main func main() { c := make(chan int) select { case _ = <-c: println("Ololo") default: } } ================================================ FILE: testData/quickfixes/replace-with-assignment/recvStatementInSelect.go ================================================ package main func main() { c := make(chan int) select { case _ := <-c: println("Ololo") default: } } ================================================ FILE: testData/quickfixes/replace-with-assignment/severalAssignments-after.go ================================================ package main func main() { var a, b = 1, 2 a, b = 3, 4 } ================================================ FILE: testData/quickfixes/replace-with-assignment/severalAssignments.go ================================================ package main func main() { var a, b = 1, 2 a, b := 3, 4 } ================================================ FILE: testData/quickfixes/replace-with-assignment/simple-after.go ================================================ package main func main() { var a = 1 a = 3 } ================================================ FILE: testData/quickfixes/replace-with-assignment/simple.go ================================================ package main func main() { var a = 1 a := 3 } ================================================ FILE: testData/quickfixes/replace-with-declaration/onAssignment-after.go ================================================ package foo func main() { a := 1 } ================================================ FILE: testData/quickfixes/replace-with-declaration/onAssignment.go ================================================ package foo func main() { a = 1 } ================================================ FILE: testData/quickfixes/replace-with-declaration/onChanRead.go ================================================ package foo func main() { a <- Struct{"foo"} } ================================================ FILE: testData/quickfixes/replace-with-declaration/onRange-after.go ================================================ package foo func main() { for a := range os.Args { } } ================================================ FILE: testData/quickfixes/replace-with-declaration/onRange.go ================================================ package foo func main() { for a = range os.Args { } } ================================================ FILE: testData/quickfixes/replace-with-declaration/onRecv-after.go ================================================ package foo func main() { select { case foo := bar: } } ================================================ FILE: testData/quickfixes/replace-with-declaration/onRecv.go ================================================ package foo func main() { select { case foo = bar: } } ================================================ FILE: testData/quickfixes/replace-with-declaration/onTopLevel.go ================================================ package main var b = a ================================================ FILE: testData/quickfixes/replace-with-select/simple-after.go ================================================ package foo func _() { select { } } ================================================ FILE: testData/quickfixes/replace-with-select/simple.go ================================================ package foo func _() { for { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/equalsCondition-after.go ================================================ package foo func main() { x := "text" if x[0] == 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/equalsCondition.go ================================================ package foo func main() { x := "text" if x[0] == "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/greaterCondition-after.go ================================================ package foo func main() { x := "text" if x[0] > 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/greaterCondition.go ================================================ package foo func main() { x := "text" if x[0] > "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/greaterOrEqualsCondition-after.go ================================================ package foo func main() { x := "text" if x[0] >= 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/greaterOrEqualsCondition.go ================================================ package foo func main() { x := "text" if x[0] >= "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/lessCondition-after.go ================================================ package foo func main() { x := "text" if x[0] < 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/lessCondition.go ================================================ package foo func main() { x := "text" if x[0] < "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/lessOrEqualsCondition-after.go ================================================ package foo func main() { x := "text" if x[0] <= 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/lessOrEqualsCondition.go ================================================ package foo func main() { x := "text" if x[0] <= "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/literals-after.go ================================================ package foo func main() { x := "text" if x[0] == '\n' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/literals.go ================================================ package foo func main() { x := "text" if x[0] == "\n" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/longLiteral-after.go ================================================ package foo func main() { x := "text" if x[0] == '\U00101234' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/longLiteral.go ================================================ package foo func main() { x := "text" if x[0] == "\U00101234" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/moreThanOneCharInString.go ================================================ package foo func main() { x := "text" if x[0] == "tex" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/notEqualsCondition-after.go ================================================ package foo func main() { x := "text" if x[0] != 't' { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/notEqualsCondition.go ================================================ package foo func main() { x := "text" if x[0] != "t" { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/reverse-after.go ================================================ package foo func main() { x := "text" if 't' == x[1] { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/reverse.go ================================================ package foo func main() { x := "text" if "t" == x[1] { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/sliceFromLeft.go ================================================ package foo func main() { x := "text" if "t" == x[1:] { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/sliceFromRight.go ================================================ package foo func main() { x := "text" if "t" == x[:1] { } } ================================================ FILE: testData/quickfixes/string-index-is-byte/sliceUnbound.go ================================================ package foo func main() { x := "text" if "t" == x[:] { } } ================================================ FILE: testData/refactor/introduce-variable/caretAfterRightParenthesis-after.go ================================================ package a func a() { i := 1 + 2 a := i b := i } ================================================ FILE: testData/refactor/introduce-variable/caretAfterRightParenthesis.go ================================================ package a func a() { a := (1 + 2) b := (1 + 2) } ================================================ FILE: testData/refactor/introduce-variable/caretOnCallParenthesis-after.go ================================================ package a func a() { i := 1 var a = b(i) } func b(c int) int { return 1 } ================================================ FILE: testData/refactor/introduce-variable/caretOnCallParenthesis.go ================================================ package a func a() { var a = b(1) } func b(c int) int { return 1 } ================================================ FILE: testData/refactor/introduce-variable/caretOnRightParenthesis-after.go ================================================ package a func a() { i := 2 a := (1 + i) b := (1 + i) } ================================================ FILE: testData/refactor/introduce-variable/caretOnRightParenthesis.go ================================================ package a func a() { a := (1 + 2) b := (1 + 2) } ================================================ FILE: testData/refactor/introduce-variable/compositeLiteral-after.go ================================================ package main type S struct{} func main() () { s := S{} foo := s } ================================================ FILE: testData/refactor/introduce-variable/compositeLiteral.go ================================================ package main type S struct{} func main() () { foo := S{} } ================================================ FILE: testData/refactor/introduce-variable/conversion-after.go ================================================ package main func main() () { int := int(0) var a int = int } type int struct {} ================================================ FILE: testData/refactor/introduce-variable/conversion.go ================================================ package main func main() () { var a int = int(0) } type int struct {} ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestKeywordBasedOnCallName-after.go ================================================ package a func a(s string) { i := Func() } func Func() int { } ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestKeywordBasedOnCallName.go ================================================ package a func a(s string) { Func() } func Func() int { } ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestKeywordBasedOnType-after.go ================================================ package a func a(s string) { foo := 1 i := Foo() } type Func int func Foo() Func { } ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestKeywordBasedOnType.go ================================================ package a func a(s string) { foo := 1 Foo() } type Func int func Foo() Func { } ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestNameEqualsToType-after.go ================================================ package a func a(s string) { i := s println(i) } ================================================ FILE: testData/refactor/introduce-variable/doNotSuggestNameEqualsToType.go ================================================ package a func a(s string) { println(s) } ================================================ FILE: testData/refactor/introduce-variable/extractFunctionLiteral-after.go ================================================ package a func a(s string) { i := func(int, int) {} } ================================================ FILE: testData/refactor/introduce-variable/extractFunctionLiteral.go ================================================ package a func a(s string) { func(int, int) {} } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_1-after.go ================================================ package a func _() { i := 2 + 1 var _ int = i } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_1.go ================================================ package a func _() { 2 + 1 var _ int = 2 + 1 } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_2-after.go ================================================ package a func _() { i := 2 + 1 var _ int = i i } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_2.go ================================================ package a func _() { var _ int = 2 + 1 2 + 1 } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_3-after.go ================================================ package a func _() { i := 2 + 1 i } ================================================ FILE: testData/refactor/introduce-variable/extractSingleExpressionStatement_3.go ================================================ package a func _() { 2 + 1 2 + 1 } ================================================ FILE: testData/refactor/introduce-variable/indexedExpression-after.go ================================================ package main func main() () { s := make([]String, 5) string := s[2] println(s[1] + string) } type String string ================================================ FILE: testData/refactor/introduce-variable/indexedExpression.go ================================================ package main func main() () { s := make([]String, 5) println(s[1] + s[2]) } type String string ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnArrayType-after.go ================================================ package a func a(s []string) { strings := s println(strings) } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnArrayType.go ================================================ package a func a(s []string) { println(s) } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnDefaultName-after.go ================================================ package a func a() { i := 1 i2 := 1 + 2 a := i2 } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnDefaultName.go ================================================ package a func a() { i := 1 a := 1 + 2 } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnGetterFunction-after.go ================================================ package a func a() { offset := getMyOffset() a := offset } func getMyOffset() int { return 42; } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnGetterFunction.go ================================================ package a func a() { a := getMyOffset() } func getMyOffset() int { return 42; } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnParamName-after.go ================================================ package a func a(i int) { i2 := 1 + 2 a := i2 } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnParamName.go ================================================ package a func a(i int) { a := 1 + 2 } ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnType-after.go ================================================ package a func a(s String) { string := s println(string) } type String string ================================================ FILE: testData/refactor/introduce-variable/nameSuggestOnType.go ================================================ package a func a(s String) { println(s) } type String string ================================================ FILE: testData/refactor/introduce-variable/replaceAll-after.go ================================================ package a func a() { i := 1 + 2 var b = i var c = 123 var d = i } ================================================ FILE: testData/refactor/introduce-variable/replaceAll.go ================================================ package a func a() { var b = 1 + 2 var c = 123 var d = 1 + 2 } ================================================ FILE: testData/refactor/introduce-variable/replaceOnly-after.go ================================================ package a func a() { var b = 1 + 2 var c = 123 i := 1 + 2 var d = i } ================================================ FILE: testData/refactor/introduce-variable/replaceOnly.go ================================================ package a func a() { var b = 1 + 2 var c = 123 var d = 1 + 2 } ================================================ FILE: testData/refactor/introduce-variable/topLevelExpression.go ================================================ package a var a = 1 + 2 ================================================ FILE: testData/refactor/introduce-variable/twoOccurrences-after.go ================================================ package a func a() { var i, g int i2 := g i2 = i2 + 2 } ================================================ FILE: testData/refactor/introduce-variable/twoOccurrences.go ================================================ package a func a() { var i, g int g = g + 2 } ================================================ FILE: testData/refactor/introduce-variable/voidCallExpression.go ================================================ package a import "fmt" func a() { a := fmt.Println() } ================================================ FILE: testData/refactor/introduce-variable/voidExpression.go ================================================ package a import "fmt" func a() { a := fmt.Println() } ================================================ FILE: testData/refactor/introduce-variable/wrongSelection.go ================================================ package a func a() { var a = 1 + 2 } ================================================ FILE: testData/regexp/injectingAndHighlighting.go ================================================ package main import "regexp" func main() { var _ = regexp.MustCompile(`\\n`) var _ = regexp.MustCompile(`[a[a-z]b]{2,}`) var _ = regexp.MustCompile(`x*`); var _ = regexp.MustCompile(`x+`); var _ = regexp.MustCompile(`x?`); var _ = regexp.MustCompile(`x{1,4}`); var _ = regexp.MustCompile(`x{1,}`); var _ = regexp.MustCompile(`x{1}`); var _ = regexp.MustCompile(`x*?`); var _ = regexp.MustCompile(`x+?`); var _ = regexp.MustCompile(`x??`); var _ = regexp.MustCompile(`x{1,2}?`); var _ = regexp.MustCompile(`x{1,}?`); var _ = regexp.MustCompile(`x{3}?`); var _ = regexp.MustCompile(`\p{^Han}`) var _ = regexp.MustCompile(`.`) var _ = regexp.MustCompile(`[xyz]`) var _ = regexp.MustCompile(`[^xyz]`) var _ = regexp.MustCompile(`\d`) var _ = regexp.MustCompile(`\D`) var _ = regexp.MustCompile(`[[:alpha:]]`) var _ = regexp.MustCompile(`[^[:alpha:]]`) var _ = regexp.MustCompile(`[[^:alpha:]]`) var _ = regexp.MustCompile(`\pN`) var _ = regexp.MustCompile(`\p{Han}`) var _ = regexp.MustCompile(`\PN`) var _ = regexp.MustCompile(`\P{Han}`) var _ = regexp.MustCompile(`\P{^Coptic}`) var _ = regexp.MustCompile(`y`) var _ = regexp.MustCompile(`|y`) var _ = regexp.MustCompile(`(re)`) var _ = regexp.MustCompile(`(?Pre)`) var _ = regexp.MustCompile(`(?:re)`) var _ = regexp.MustCompile(`(?flags)`) var _ = regexp.MustCompile(`(?flags:re)`) var _ = regexp.MustCompile(`(?im-sU)`) var _ = regexp.MustCompile(`(?imsU:re)`) var _ = regexp.MustCompile(`(?imsGU:re)`) var _ = regexp.MustCompile(`^`) var _ = regexp.MustCompile(`$`) var _ = regexp.MustCompile(`\A`) var _ = regexp.MustCompile(`\b`) var _ = regexp.MustCompile(`\B`) var _ = regexp.MustCompile(`\z`) var _ = regexp.MustCompile(`\a`) var _ = regexp.MustCompile(`\f`) var _ = regexp.MustCompile(`\t`) var _ = regexp.MustCompile(`\n`) var _ = regexp.MustCompile(`\r`) var _ = regexp.MustCompile(`\v`) var _ = regexp.MustCompile(`\*`) var _ = regexp.MustCompile(`\123`) var _ = regexp.MustCompile(`\x7F`) var _ = regexp.MustCompile(`\x{10FFFF}`) var _ = regexp.MustCompile(`\Q...\E`) var _ = regexp.MustCompile(``) var _ = regexp.MustCompile(`-Z`) var _ = regexp.MustCompile(`\d`) var _ = regexp.MustCompile(`[:foo:]`) var _ = regexp.MustCompile(`\p{Han}`) var _ = regexp.MustCompile(`\pC`) var _ = regexp.MustCompile(`[\d]`) var _ = regexp.MustCompile(`[^\d]`) var _ = regexp.MustCompile(`[\D]`) var _ = regexp.MustCompile(`[^\D]`) var _ = regexp.MustCompile(`[[:cntrl:]]`) var _ = regexp.MustCompile(`[^[:cntrl:]]`) var _ = regexp.MustCompile(`[\p{Han}]`) var _ = regexp.MustCompile(`[^\p{Han}]`) var _ = regexp.MustCompile(`\d`) var _ = regexp.MustCompile(`\D`) var _ = regexp.MustCompile(`\s`) var _ = regexp.MustCompile(`\S`) var _ = regexp.MustCompile(`\w`) var _ = regexp.MustCompile(`\W`) var _ = regexp.MustCompile(`[[:alnum:]]`) var _ = regexp.MustCompile(`[[:alpha:]]`) var _ = regexp.MustCompile(`[[:ascii:]]`) var _ = regexp.MustCompile(`[[:blank:]]`) var _ = regexp.MustCompile(`[[:cntrl:]]`) var _ = regexp.MustCompile(`[[:digit:]]`) var _ = regexp.MustCompile(`[[:graph:]]`) var _ = regexp.MustCompile(`[[:lower:]]`) var _ = regexp.MustCompile(`[[:print:]]`) var _ = regexp.MustCompile(`[[:punct:]]`) var _ = regexp.MustCompile(`[[:space:]]`) var _ = regexp.MustCompile(`[[:upper:]]`) var _ = regexp.MustCompile(`[[:word:]]`) var _ = regexp.MustCompile(`[[:xdigit:]]`) var _ = regexp.MustCompile(`[[:^alpha:]]`) // must be fixed in platform } ================================================ FILE: testData/running/producer/directory.xml ================================================ ================================================ FILE: testData/running/producer/fileWithMain.go ================================================ package main func main() { } ================================================ FILE: testData/running/producer/fileWithMain.xml ================================================ ================================================ FILE: testData/running/producer/fileWithMainButNotMainPackage.go ================================================ package otherPackage func main() { } ================================================ FILE: testData/running/producer/fileWithMainButNotMainPackage.xml ================================================ ================================================ FILE: testData/running/producer/fileWithoutMain.go ================================================ package main func init() { } ================================================ FILE: testData/running/producer/fileWithoutMain.xml ================================================ ================================================ FILE: testData/running/producer/packageClause.go ================================================ package main func main() { } ================================================ FILE: testData/running/producer/packageClause.xml ================================================ ================================================ FILE: testData/running/producer/testFile_test.go ================================================ package main func main() { } ================================================ FILE: testData/running/producer/testFile_test.xml ================================================ ================================================ FILE: testData/selectWord/arguments/after1.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/arguments/after2.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/arguments/after3.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/arguments/after4.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/arguments/after5.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/arguments/before.go ================================================ package main import "fmt" func main() { s := "hello" fmt.Printf("%s", s) } ================================================ FILE: testData/selectWord/block/after1.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/block/after2.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/block/after3.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/block/after4.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/block/after5.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/block/before.go ================================================ package main func main() { b, _ := foo() fmt.Println(b) } ================================================ FILE: testData/selectWord/functionName/after1.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/functionName/after2.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/functionName/after3.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/functionName/after4.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/functionName/before.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/importString/after1.go ================================================ package main import "database/sql/driver" ================================================ FILE: testData/selectWord/importString/after2.go ================================================ package main import "database/sql/driver" ================================================ FILE: testData/selectWord/importString/after3.go ================================================ package main import "database/sql/driver" ================================================ FILE: testData/selectWord/importString/after4.go ================================================ package main import "database/sql/driver" ================================================ FILE: testData/selectWord/importString/before.go ================================================ package main import "database/sql/driver" ================================================ FILE: testData/selectWord/multipleImportString/after1.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/after2.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/after3.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/after4.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/after5.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/after6.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/multipleImportString/before.go ================================================ package main import ( "database/sql/driver" "database/sql/driver" "database/sql/driver" ) ================================================ FILE: testData/selectWord/parameters/after1.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after2.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after3.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after4.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after5.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after6.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/after7.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/parameters/before.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after1.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after2.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after3.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after4.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after5.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/after6.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/resultParameters/before.go ================================================ package main func FunctionName(int a, string s) (byte, string) { } ================================================ FILE: testData/selectWord/stringLiteral/after1.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/selectWord/stringLiteral/after2.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/selectWord/stringLiteral/after3.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/selectWord/stringLiteral/after4.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/selectWord/stringLiteral/after5.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/selectWord/stringLiteral/before.go ================================================ package main func main() { println("Hello World") } ================================================ FILE: testData/smartEnter/deferStatement-after.go ================================================ package main func _() { defer function() } func function() { } ================================================ FILE: testData/smartEnter/deferStatement.go ================================================ package main func _() { defer function } func function() { } ================================================ FILE: testData/smartEnter/deferStatementOnNonFunctionType-after.go ================================================ package main func _() { var variable int defer variable } ================================================ FILE: testData/smartEnter/deferStatementOnNonFunctionType.go ================================================ package main func _() { var variable int defer variable } ================================================ FILE: testData/smartEnter/for-after.go ================================================ package main func _() { for i := 0; ; { } } ================================================ FILE: testData/smartEnter/for.go ================================================ package main func _() { for i := 0; ; } ================================================ FILE: testData/smartEnter/forWithBlock-after.go ================================================ package main func _() { for i := 0; ; { } } ================================================ FILE: testData/smartEnter/forWithBlock.go ================================================ package main func _() { for i := 0; ; { } } ================================================ FILE: testData/smartEnter/function-after.go ================================================ package main func _() { } ================================================ FILE: testData/smartEnter/function.go ================================================ package main func _() ================================================ FILE: testData/smartEnter/functionLiteral-after.go ================================================ package main func _() { a := func() { } } ================================================ FILE: testData/smartEnter/functionLiteral.go ================================================ package main func _() { a := func() } ================================================ FILE: testData/smartEnter/functionLiteralWithBlock-after.go ================================================ package main func _() { a := func() {} } ================================================ FILE: testData/smartEnter/functionLiteralWithBlock.go ================================================ package main func _() { a := func() {} } ================================================ FILE: testData/smartEnter/functionWithBlock-after.go ================================================ package main func _() { } ================================================ FILE: testData/smartEnter/functionWithBlock.go ================================================ package main func _() { } ================================================ FILE: testData/smartEnter/goStatement-after.go ================================================ package main func _() { go function() } func function() { } ================================================ FILE: testData/smartEnter/goStatement.go ================================================ package main func _() { go function } func function() { } ================================================ FILE: testData/smartEnter/goStatementOnNonFunctionType-after.go ================================================ package main func _() { var variable int go variable } ================================================ FILE: testData/smartEnter/goStatementOnNonFunctionType.go ================================================ package main func _() { var variable int go variable } ================================================ FILE: testData/smartEnter/if-after.go ================================================ package main func _() { if (true) { } } ================================================ FILE: testData/smartEnter/if.go ================================================ package main func _() { if (true) } ================================================ FILE: testData/smartEnter/ifWithBlock-after.go ================================================ package main func _() { if (true) { } } ================================================ FILE: testData/smartEnter/ifWithBlock.go ================================================ package main func _() { if (true) { } } ================================================ FILE: testData/spellchecker/functionName.go ================================================ package main func intigir() { } ================================================ FILE: testData/spellchecker/suppressed.go ================================================ package main func intigir() { } //noinspection SpellCheckingInspection func intigir() { } //noinspection All func intigir() { } ================================================ FILE: testData/spellchecker/variableName.go ================================================ package main import "fmt" func main() { fmt.Printf("Hello"); integir := 3; } ================================================ FILE: testData/stubs/stub.go ================================================ package main; func main() { type A struct { a int } } ================================================ FILE: testData/stubs/stub.txt ================================================ GoFileStub PACKAGE_CLAUSE:GoPackageClauseStub FUNCTION_DECLARATION:GoFunctionDeclarationStub: main SIGNATURE:GoSignatureStub PARAMETERS:GoParametersStub TYPE_SPEC:GoTypeSpecStub: A SPEC_TYPE:GoTypeStub STRUCT_TYPE:GoTypeStub TYPE:GoTypeStub ================================================ FILE: testData/stubs/stubMismatch2540.go ================================================ package main import ( "fmt" "html/template" ) func main (){ var e template.IsTrue(struct{chan true}) var a, w int var t struct {x int} = struct{x int }{1}; a, w = asasd(1,t,lenz(w)) fmt.Println(w, w) } func asasd(int int, qe struct{ x int }, strings string) (int, int) { } func lenz(a int) string { return "asd" } ================================================ FILE: testData/stubs/stubMismatch2540.txt ================================================ GoFileStub PACKAGE_CLAUSE:GoPackageClauseStub IMPORT_SPEC:GoImportSpecStub IMPORT_SPEC:GoImportSpecStub FUNCTION_DECLARATION:GoFunctionDeclarationStub: main SIGNATURE:GoSignatureStub PARAMETERS:GoParametersStub FUNCTION_DECLARATION:GoFunctionDeclarationStub: asasd SIGNATURE:GoSignatureStub PARAMETERS:GoParametersStub PARAMETER_DECLARATION:GoParameterDeclarationStub PARAM_DEFINITION:GoParamDefinitionStub: int TYPE:GoTypeStub PARAMETER_DECLARATION:GoParameterDeclarationStub PARAM_DEFINITION:GoParamDefinitionStub: qe STRUCT_TYPE:GoTypeStub FIELD_DEFINITION:GoFieldDefinitionStub: x TYPE:GoTypeStub PARAMETER_DECLARATION:GoParameterDeclarationStub PARAM_DEFINITION:GoParamDefinitionStub: strings TYPE:GoTypeStub RESULT:GoResultStub TYPE_LIST:GoTypeStub TYPE:GoTypeStub TYPE:GoTypeStub FUNCTION_DECLARATION:GoFunctionDeclarationStub: lenz SIGNATURE:GoSignatureStub PARAMETERS:GoParametersStub PARAMETER_DECLARATION:GoParameterDeclarationStub PARAM_DEFINITION:GoParamDefinitionStub: a TYPE:GoTypeStub RESULT:GoResultStub TYPE:GoTypeStub ================================================ FILE: testData/testing/gobench/benchmarkWithoutSuffix-expected.txt ================================================ TestStarted - locationHint=gotest://Benchmark - name=Benchmark TestStdOut - name=Benchmark - out=20000000 109 ns/op\n TestStdOut - name=Benchmark - out=ok github.com/cydev/stok/storage 2.311s\n TestFinished - duration=42 - name=Benchmark ================================================ FILE: testData/testing/gobench/benchmarkWithoutSuffix.txt ================================================ PASS Benchmark 20000000 109 ns/op ok github.com/cydev/stok/storage 2.311s ================================================ FILE: testData/testing/gobench/failedBenchmark-expected.txt ================================================ TestStarted - locationHint=gotest://BenchmarkBulk_Read - name=BenchmarkBulk_Read TestStdOut - name=BenchmarkBulk_Read - out= bulk_test.go:157: bulk.Read\n TestStdOut - name=BenchmarkBulk_Read - out=ok github.com/cydev/stok/storage 0.020s\n TestFailed - message= - name=BenchmarkBulk_Read TestFinished - duration=42 - name=BenchmarkBulk_Read ================================================ FILE: testData/testing/gobench/failedBenchmark.txt ================================================ PASS BenchmarkBulk_Read-4 --- FAIL: BenchmarkBulk_Read-4 bulk_test.go:157: bulk.Read ok github.com/cydev/stok/storage 0.020s ================================================ FILE: testData/testing/gobench/failedCompilation-expected.txt ================================================ ================================================ FILE: testData/testing/gobench/failedCompilation.txt ================================================ /usr/local/Cellar/go/1.6/libexec/bin/go test -v github.com/cydev/stok/storage -bench '^BenchmarkBulk_Read2|BenchmarkBulk_Read|BenchmarkBulk_Read3$' -run ^$ # github.com/cydev/stok/storage storage/bulk_test.go:167: no new variables on left side of := FAIL github.com/cydev/stok/storage [build failed] ================================================ FILE: testData/testing/gobench/mixedBenchmark-expected.txt ================================================ TestStarted - locationHint=gotest://BenchmarkBulk_Read2 - name=BenchmarkBulk_Read2 TestStdOut - name=BenchmarkBulk_Read2 - out=2000000000 0.00 ns/op\n TestFinished - duration=42 - name=BenchmarkBulk_Read2 TestStarted - locationHint=gotest://BenchmarkBulk_Read - name=BenchmarkBulk_Read TestStdOut - name=BenchmarkBulk_Read - out= bulk_test.go:162: bulk.Read\n TestStdOut - name=BenchmarkBulk_Read - out= bulk_test.go:163: asdf\n TestFailed - message= - name=BenchmarkBulk_Read TestFinished - duration=42 - name=BenchmarkBulk_Read TestStarted - locationHint=gotest://BenchmarkBulk_Read3 - name=BenchmarkBulk_Read3 TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=Hellooooo\n TestStdOut - name=BenchmarkBulk_Read3 - out=2000000000 0.00 ns/op\n TestStdOut - name=BenchmarkBulk_Read3 - out=ok github.com/cydev/stok/storage 0.021s\n TestFinished - duration=42 - name=BenchmarkBulk_Read3 ================================================ FILE: testData/testing/gobench/mixedBenchmark.txt ================================================ PASS BenchmarkBulk_Read2-4 2000000000 0.00 ns/op BenchmarkBulk_Read-4 --- FAIL: BenchmarkBulk_Read-4 bulk_test.go:162: bulk.Read bulk_test.go:163: asdf BenchmarkBulk_Read3-4 Hellooooo Hellooooo Hellooooo Hellooooo Hellooooo Hellooooo 2000000000 0.00 ns/op ok github.com/cydev/stok/storage 0.021s ================================================ FILE: testData/testing/gobench/successBenchmark-expected.txt ================================================ TestStarted - locationHint=gotest://BenchmarkBulk_Read - name=BenchmarkBulk_Read TestStdOut - name=BenchmarkBulk_Read - out=20000000 109 ns/op\n TestStdOut - name=BenchmarkBulk_Read - out=ok github.com/cydev/stok/storage 2.311s\n TestFinished - duration=42 - name=BenchmarkBulk_Read ================================================ FILE: testData/testing/gobench/successBenchmark.txt ================================================ PASS BenchmarkBulk_Read-4 20000000 109 ns/op ok github.com/cydev/stok/storage 2.311s ================================================ FILE: testData/testing/gocheck/assertions-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://SomeFailSuite - name=SomeFailSuite TestStarted - locationHint=gotest://SomeFailSuite.TestA - name=SomeFailSuite.TestA TestFailed - actual=string = "Foo" - details=Somethingall_fail_test.go:21 - expected= - message=c.Assert("Foo", IsNil) - name=SomeFailSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestA TestStarted - locationHint=gotest://SomeFailSuite.TestB - name=SomeFailSuite.TestB TestFailed - actual== nil - details=Somethingall_fail_test.go:26 - expected= - message=c.Assert(nil, NotNil) - name=SomeFailSuite.TestB - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestB TestStarted - locationHint=gotest://SomeFailSuite.TestC - name=SomeFailSuite.TestC TestFailed - actual=string = "Foo" - details=Somethingall_fail_test.go:31 - expected=string = "[bB].(R|r)" - message=c.Assert("Foo", Matches, "[bB].(R|r)") - name=SomeFailSuite.TestC - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestC TestStarted - locationHint=gotest://SomeFailSuite.TestD - name=SomeFailSuite.TestD TestFailed - actual=string = "Foo" - details=Somethingall_fail_test.go:36 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=SomeFailSuite.TestD - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestD TestStarted - locationHint=gotest://SomeFailSuite.TestE - name=SomeFailSuite.TestE TestFailed - actual=[]string = []string{"a", "b"} - details=Somethingall_fail_test.go:41 - expected=[]string = []string{"a", "B"} - message=c.Assert([]string{"a", "b"}, DeepEquals, []string{"a", "B"}) - name=SomeFailSuite.TestE - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestE TestStarted - locationHint=gotest://SomeFailSuite.TestF - name=SomeFailSuite.TestF TestFailed - actual=string = ""\n"multi\n"\n"\n"\n"\t line\n"\n"\t string" - details=Somethingall_fail_test.go:54 - expected=string = ""\n"Another\n"\n"multi\n"\n"\tline\n"\n"\t\tstring" - message=c.Assert(`multi\n\n line\n string`,\n Equals,\n `Another\n multi\n line\n string`) - name=SomeFailSuite.TestF - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestF TestSuiteFinished - name=SomeFailSuite ================================================ FILE: testData/testing/gocheck/assertions.txt ================================================ === RUN Test START: all_fail_test.go:19: SomeFailSuite.TestA Somethingall_fail_test.go:21: c.Assert("Foo", IsNil) ... value string = "Foo" FAIL: all_fail_test.go:19: SomeFailSuite.TestA START: all_fail_test.go:24: SomeFailSuite.TestB Somethingall_fail_test.go:26: c.Assert(nil, NotNil) ... value = nil FAIL: all_fail_test.go:24: SomeFailSuite.TestB START: all_fail_test.go:29: SomeFailSuite.TestC Somethingall_fail_test.go:31: c.Assert("Foo", Matches, "[bB].(R|r)") ... value string = "Foo" ... regex string = "[bB].(R|r)" FAIL: all_fail_test.go:29: SomeFailSuite.TestC START: all_fail_test.go:34: SomeFailSuite.TestD Somethingall_fail_test.go:36: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: all_fail_test.go:34: SomeFailSuite.TestD START: all_fail_test.go:39: SomeFailSuite.TestE Somethingall_fail_test.go:41: c.Assert([]string{"a", "b"}, DeepEquals, []string{"a", "B"}) ... obtained []string = []string{"a", "b"} ... expected []string = []string{"a", "B"} FAIL: all_fail_test.go:39: SomeFailSuite.TestE START: all_fail_test.go:44: SomeFailSuite.TestF Somethingall_fail_test.go:54: c.Assert(`multi line string`, Equals, `Another multi line string`) ... obtained string = "" + ... "multi\n" + ... "\n" + ... "\t line\n" + ... "\t string" ... expected string = "" + ... "Another\n" + ... "multi\n" + ... "\tline\n" + ... "\t\tstring" FAIL: all_fail_test.go:46: SomeFailSuite.TestF OOPS: 0 passed, 6 FAILED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/all_fail 0.007s ================================================ FILE: testData/testing/gocheck/assertionsInvalidFormat-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://SomeFailSuite - name=SomeFailSuite TestStarted - locationHint=gotest://SomeFailSuite.TestA - name=SomeFailSuite.TestA TestFailed - actual=string = "Foo" - details= - expected= - message= - name=SomeFailSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=SomeFailSuite.TestA TestSuiteFinished - name=SomeFailSuite ================================================ FILE: testData/testing/gocheck/assertionsInvalidFormat.txt ================================================ === RUN Test START: all_fail_test.go:19: SomeFailSuite.TestA ... value string = "Foo" FAIL: all_fail_test.go:19: SomeFailSuite.TestA OOPS: 0 passed, 1 FAILED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/all_fail 0.007s ================================================ FILE: testData/testing/gocheck/fixtureStdOut-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureSuite - name=FixtureSuite TestStarted - locationHint=gotest://FixtureSuite.TestA - name=FixtureSuite.TestA TestStdOut - name=FixtureSuite.TestA - out=SetUp\n\nTearDown\n\n TestFinished - duration=42 - name=FixtureSuite.TestA TestStarted - locationHint=gotest://FixtureSuite.TestB - name=FixtureSuite.TestB TestStdOut - name=FixtureSuite.TestB - out=SetUp\n\nsomethingTearDown\n\n TestFinished - duration=42 - name=FixtureSuite.TestB TestStarted - locationHint=gotest://FixtureSuite.TestC - name=FixtureSuite.TestC TestStdOut - name=FixtureSuite.TestC - out=SetUp\n\nsomethingTearDown\n\n TestFinished - duration=42 - name=FixtureSuite.TestC TestSuiteFinished - name=FixtureSuite TestStdOut - name=SuiteTearDown - out=TearDown\n\nOK: 3 passed\n--- PASS: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/fixtureStdOut.txt ================================================ === RUN Test START: setups_test.go:19: FixtureSuite.SetUpSuite SetUp PASS: setups_test.go:19: FixtureSuite.SetUpSuite 0.000s START: setups_test.go:41: FixtureSuite.TestA START: setups_test.go:30: FixtureSuite.SetUpTest SetUp PASS: setups_test.go:30: FixtureSuite.SetUpTest 0.000s START: setups_test.go:35: FixtureSuite.TearDownTest TearDown PASS: setups_test.go:35: FixtureSuite.TearDownTest 0.000s PASS: setups_test.go:41: FixtureSuite.TestA 0.000s START: setups_test.go:43: FixtureSuite.TestB START: setups_test.go:30: FixtureSuite.SetUpTest SetUp PASS: setups_test.go:30: FixtureSuite.SetUpTest 0.000s somethingSTART: setups_test.go:35: FixtureSuite.TearDownTest TearDown PASS: setups_test.go:35: FixtureSuite.TearDownTest 0.000s PASS: setups_test.go:43: FixtureSuite.TestB 0.000s START: setups_test.go:48: FixtureSuite.TestC START: setups_test.go:30: FixtureSuite.SetUpTest SetUp PASS: setups_test.go:30: FixtureSuite.SetUpTest 0.000s somethingSTART: setups_test.go:35: FixtureSuite.TearDownTest TearDown PASS: setups_test.go:35: FixtureSuite.TearDownTest 0.000s PASS: setups_test.go:48: FixtureSuite.TestC 0.000s START: setups_test.go:25: FixtureSuite.TearDownSuite TearDown PASS: setups_test.go:25: FixtureSuite.TearDownSuite 0.000s OK: 3 passed --- PASS: Test (0.00s) PASS ok github.com/mailgun/sandbox/setups 0.005s ================================================ FILE: testData/testing/gocheck/panic-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://SomePanicSuite - name=SomePanicSuite TestStarted - locationHint=gotest://SomePanicSuite.TestA - name=SomePanicSuite.TestA TestFinished - duration=42 - name=SomePanicSuite.TestA TestStarted - locationHint=gotest://SomePanicSuite.TestB - name=SomePanicSuite.TestB TestFinished - duration=42 - name=SomePanicSuite.TestB TestStarted - locationHint=gotest://SomePanicSuite.TestC - name=SomePanicSuite.TestC TestStdOut - name=SomePanicSuite.TestC - out=something TestFailed - details=/usr/local/go/src/runtime/panic.go:387\n in gopanic\nsome_panic_test.go:27\n in SomePanicSuite.TestC\n/usr/local/go/src/reflect/value.go:296\n in Value.Call\n/usr/local/go/src/runtime/asm_amd64.s:2232\n in goexit\n - message=Panic: foo (PC=0x3B0A5)\n - name=SomePanicSuite.TestC TestFinished - duration=42 - name=SomePanicSuite.TestC TestStarted - locationHint=gotest://SomePanicSuite.TestD - name=SomePanicSuite.TestD TestFailed - details=/usr/local/go/src/runtime/panic.go:387\n in gopanic\nsome_panic_test.go:31\n in SomePanicSuite.TestD\n/usr/local/go/src/reflect/value.go:296\n in Value.Call\n/usr/local/go/src/runtime/asm_amd64.s:2232\n in goexit\n - message=Panic: bar (PC=0x3B0A5)\n - name=SomePanicSuite.TestD TestFinished - duration=42 - name=SomePanicSuite.TestD TestStarted - locationHint=gotest://SomePanicSuite.TestE - name=SomePanicSuite.TestE TestFinished - duration=42 - name=SomePanicSuite.TestE TestSuiteFinished - name=SomePanicSuite ================================================ FILE: testData/testing/gocheck/panic.txt ================================================ === RUN Test START: some_panic_test.go:20: SomePanicSuite.TestA PASS: some_panic_test.go:20: SomePanicSuite.TestA 0.000s START: some_panic_test.go:23: SomePanicSuite.TestB PASS: some_panic_test.go:23: SomePanicSuite.TestB 0.000s START: some_panic_test.go:25: SomePanicSuite.TestC something... Panic: foo (PC=0x3B0A5) /usr/local/go/src/runtime/panic.go:387 in gopanic some_panic_test.go:27 in SomePanicSuite.TestC /usr/local/go/src/reflect/value.go:296 in Value.Call /usr/local/go/src/runtime/asm_amd64.s:2232 in goexit PANIC: some_panic_test.go:25: SomePanicSuite.TestC START: some_panic_test.go:30: SomePanicSuite.TestD ... Panic: bar (PC=0x3B0A5) /usr/local/go/src/runtime/panic.go:387 in gopanic some_panic_test.go:31 in SomePanicSuite.TestD /usr/local/go/src/reflect/value.go:296 in Value.Call /usr/local/go/src/runtime/asm_amd64.s:2232 in goexit PANIC: some_panic_test.go:30: SomePanicSuite.TestD START: some_panic_test.go:36: SomePanicSuite.TestE PASS: some_panic_test.go:36: SomePanicSuite.TestE 0.000s OOPS: 3 passed, 2 PANICKED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/some_panic 0.005s ================================================ FILE: testData/testing/gocheck/panicInvalidFormat-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://SomePanicSuite - name=SomePanicSuite TestStarted - locationHint=gotest://SomePanicSuite.TestD - name=SomePanicSuite.TestD TestFailed - details= in SomePanicSuite.TestD\n/usr/local/go/src/reflect/value.go:296\n in Value.Call\n/usr/local/go/src/runtime/asm_amd64.s:2232\n in goexit\n - message= - name=SomePanicSuite.TestD TestFinished - duration=42 - name=SomePanicSuite.TestD TestSuiteFinished - name=SomePanicSuite ================================================ FILE: testData/testing/gocheck/panicInvalidFormat.txt ================================================ === RUN Test START: some_panic_test.go:30: SomePanicSuite.TestD in SomePanicSuite.TestD /usr/local/go/src/reflect/value.go:296 in Value.Call /usr/local/go/src/runtime/asm_amd64.s:2232 in goexit PANIC: some_panic_test.go:30: SomePanicSuite.TestD OOPS: 0 passed, 1 PANICKED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/some_panic 0.005s ================================================ FILE: testData/testing/gocheck/pass-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://AllPassSuite - name=AllPassSuite TestStarted - locationHint=gotest://AllPassSuite.TestA - name=AllPassSuite.TestA TestFinished - duration=42 - name=AllPassSuite.TestA TestStarted - locationHint=gotest://AllPassSuite.TestB - name=AllPassSuite.TestB TestStdOut - name=AllPassSuite.TestB - out=FooBar TestFinished - duration=42 - name=AllPassSuite.TestB TestStarted - locationHint=gotest://AllPassSuite.TestC - name=AllPassSuite.TestC TestStdOut - name=AllPassSuite.TestC - out=Blah\n TestFinished - duration=42 - name=AllPassSuite.TestC TestStarted - locationHint=gotest://AllPassSuite.TestD - name=AllPassSuite.TestD TestStdOut - name=AllPassSuite.TestD - out=Превед\nМедвед TestFinished - duration=42 - name=AllPassSuite.TestD TestSuiteFinished - name=AllPassSuite ================================================ FILE: testData/testing/gocheck/pass.txt ================================================ === RUN Test START: all_pass_test.go:20: AllPassSuite.TestA PASS: all_pass_test.go:20: AllPassSuite.TestA 0.000s START: all_pass_test.go:22: AllPassSuite.TestB FooBarPASS: all_pass_test.go:22: AllPassSuite.TestB 0.000s START: all_pass_test.go:27: AllPassSuite.TestC Blah PASS: all_pass_test.go:27: AllPassSuite.TestC 0.000s START: all_pass_test.go:31: AllPassSuite.TestD Превед МедведPASS: all_pass_test.go:31: AllPassSuite.TestD 0.000s OK: 4 passed --- PASS: Test (0.00s) PASS ok github.com/mailgun/sandbox/all_pass 0.005s ================================================ FILE: testData/testing/gocheck/skippingTests-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureSuiteSetUpErrorSuite - name=FixtureSuiteSetUpErrorSuite TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestA - name=FixtureSuiteSetUpErrorSuite.TestA TestFailed - actual= - details= - expected= - message= - name=FixtureSuiteSetUpErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestA TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestB - name=FixtureSuiteSetUpErrorSuite.TestB TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestB TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestB TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestC - name=FixtureSuiteSetUpErrorSuite.TestC TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestC TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestC TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestD - name=FixtureSuiteSetUpErrorSuite.TestD TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestD TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestD TestSuiteFinished - name=FixtureSuiteSetUpErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/skippingTests.txt ================================================ === RUN Test START: setups_test.go:19: FixtureSuiteSetUpErrorSuite.SetUpSuite FAIL: setups_test.go:19: FixtureSuiteSetUpErrorSuite.SetUpSuite START: setups_test.go:36: FixtureSuiteSetUpErrorSuite.TestA SKIP: setups_test.go:36: FixtureSuiteSetUpErrorSuite.TestA START: setups_test.go:40: FixtureSuiteSetUpErrorSuite.TestB SKIP: setups_test.go:40: FixtureSuiteSetUpErrorSuite.TestB START: setups_test.go:45: FixtureSuiteSetUpErrorSuite.TestC SKIP: setups_test.go:45: FixtureSuiteSetUpErrorSuite.TestC START: setups_test.go:51: FixtureSuiteSetUpErrorSuite.TestD SKIP: setups_test.go:51: FixtureSuiteSetUpErrorSuite.TestD START: setups_test.go:24: FixtureSuiteSetUpErrorSuite.TearDownSuite PASS: setups_test.go:24: FixtureSuiteSetUpErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureSuiteSetUpError 0.005s ================================================ FILE: testData/testing/gocheck/suiteSetUpError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureSuiteSetUpErrorSuite - name=FixtureSuiteSetUpErrorSuite TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestA - name=FixtureSuiteSetUpErrorSuite.TestA TestFailed - actual=string = "Foo" - details=setups_test.go:21 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureSuiteSetUpErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestA TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestB - name=FixtureSuiteSetUpErrorSuite.TestB TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestB TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestB TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestC - name=FixtureSuiteSetUpErrorSuite.TestC TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestC TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestC TestStarted - locationHint=gotest://FixtureSuiteSetUpErrorSuite.TestD - name=FixtureSuiteSetUpErrorSuite.TestD TestIgnored - name=FixtureSuiteSetUpErrorSuite.TestD TestFinished - duration=42 - name=FixtureSuiteSetUpErrorSuite.TestD TestSuiteFinished - name=FixtureSuiteSetUpErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/suiteSetUpError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureSuiteSetUpErrorSuite.SetUpSuite setups_test.go:21: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:19: FixtureSuiteSetUpErrorSuite.SetUpSuite START: setups_test.go:36: FixtureSuiteSetUpErrorSuite.TestA MISS: setups_test.go:36: FixtureSuiteSetUpErrorSuite.TestA START: setups_test.go:40: FixtureSuiteSetUpErrorSuite.TestB MISS: setups_test.go:40: FixtureSuiteSetUpErrorSuite.TestB START: setups_test.go:45: FixtureSuiteSetUpErrorSuite.TestC MISS: setups_test.go:45: FixtureSuiteSetUpErrorSuite.TestC START: setups_test.go:51: FixtureSuiteSetUpErrorSuite.TestD MISS: setups_test.go:51: FixtureSuiteSetUpErrorSuite.TestD START: setups_test.go:24: FixtureSuiteSetUpErrorSuite.TearDownSuite PASS: setups_test.go:24: FixtureSuiteSetUpErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureSuiteSetUpError 0.005s ================================================ FILE: testData/testing/gocheck/suiteTearDownError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureSuiteTearDownErrorSuite - name=FixtureSuiteTearDownErrorSuite TestStarted - locationHint=gotest://FixtureSuiteTearDownErrorSuite.TestA - name=FixtureSuiteTearDownErrorSuite.TestA TestStdOut - name=FixtureSuiteTearDownErrorSuite.TestA - out=\n\n TestFinished - duration=42 - name=FixtureSuiteTearDownErrorSuite.TestA TestStarted - locationHint=gotest://FixtureSuiteTearDownErrorSuite.TestB - name=FixtureSuiteTearDownErrorSuite.TestB TestStdOut - name=FixtureSuiteTearDownErrorSuite.TestB - out=\n\n TestFinished - duration=42 - name=FixtureSuiteTearDownErrorSuite.TestB TestSuiteFinished - name=FixtureSuiteTearDownErrorSuite TestStdOut - name=SuiteTearDown - out=setups_test.go:25:\n c.Assert("Foo", Equals, "Bar")\n... obtained string = "Foo"\n... expected string = "Bar"\n\n\nOOPS: 2 passed, 1 FAILED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/suiteTearDownError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureSuiteTearDownErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureSuiteTearDownErrorSuite.SetUpSuite 0.000s START: setups_test.go:36: FixtureSuiteTearDownErrorSuite.TestA START: setups_test.go:28: FixtureSuiteTearDownErrorSuite.SetUpTest PASS: setups_test.go:28: FixtureSuiteTearDownErrorSuite.SetUpTest 0.000s START: setups_test.go:32: FixtureSuiteTearDownErrorSuite.TearDownTest PASS: setups_test.go:32: FixtureSuiteTearDownErrorSuite.TearDownTest 0.000s PASS: setups_test.go:36: FixtureSuiteTearDownErrorSuite.TestA 0.000s START: setups_test.go:40: FixtureSuiteTearDownErrorSuite.TestB START: setups_test.go:28: FixtureSuiteTearDownErrorSuite.SetUpTest PASS: setups_test.go:28: FixtureSuiteTearDownErrorSuite.SetUpTest 0.000s START: setups_test.go:32: FixtureSuiteTearDownErrorSuite.TearDownTest PASS: setups_test.go:32: FixtureSuiteTearDownErrorSuite.TearDownTest 0.000s PASS: setups_test.go:40: FixtureSuiteTearDownErrorSuite.TestB 0.000s START: setups_test.go:23: FixtureSuiteTearDownErrorSuite.TearDownSuite setups_test.go:25: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:23: FixtureSuiteTearDownErrorSuite.TearDownSuite OOPS: 2 passed, 1 FAILED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureSuiteTearDownError 0.006s ================================================ FILE: testData/testing/gocheck/testAndTestTearDownError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureTestAndTearDownErrorSuite - name=FixtureTestAndTearDownErrorSuite TestStarted - locationHint=gotest://FixtureTestAndTearDownErrorSuite.TestA - name=FixtureTestAndTearDownErrorSuite.TestA TestStdOut - name=FixtureTestAndTearDownErrorSuite.TestA - out=\nsetups_test.go:38:\n c.Assert("blah", IsNil)\n... value string = "blah"\n TestFailed - actual=string = "Foo" - details=setups_test.go:33 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureTestAndTearDownErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureTestAndTearDownErrorSuite.TestA TestStarted - locationHint=gotest://FixtureTestAndTearDownErrorSuite.TestB - name=FixtureTestAndTearDownErrorSuite.TestB TestIgnored - name=FixtureTestAndTearDownErrorSuite.TestB TestFinished - duration=42 - name=FixtureTestAndTearDownErrorSuite.TestB TestSuiteFinished - name=FixtureTestAndTearDownErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/testAndTestTearDownError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureTestAndTearDownErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureTestAndTearDownErrorSuite.SetUpSuite 0.000s START: setups_test.go:36: FixtureTestAndTearDownErrorSuite.TestA START: setups_test.go:27: FixtureTestAndTearDownErrorSuite.SetUpTest PASS: setups_test.go:27: FixtureTestAndTearDownErrorSuite.SetUpTest 0.000s setups_test.go:38: c.Assert("blah", IsNil) ... value string = "blah" START: setups_test.go:31: FixtureTestAndTearDownErrorSuite.TearDownTest setups_test.go:33: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:31: FixtureTestAndTearDownErrorSuite.TearDownTest ... Panic: Fixture has panicked (see related PANIC) PANIC: setups_test.go:36: FixtureTestAndTearDownErrorSuite.TestA START: setups_test.go:41: FixtureTestAndTearDownErrorSuite.TestB MISS: setups_test.go:41: FixtureTestAndTearDownErrorSuite.TestB START: setups_test.go:23: FixtureTestAndTearDownErrorSuite.TearDownSuite PASS: setups_test.go:23: FixtureTestAndTearDownErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureTestAndTearDownError 0.006s ================================================ FILE: testData/testing/gocheck/testBothFixturesError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureTestBothErrorSuite - name=FixtureTestBothErrorSuite TestStarted - locationHint=gotest://FixtureTestBothErrorSuite.TestA - name=FixtureTestBothErrorSuite.TestA TestStdOut - name=FixtureTestBothErrorSuite.TestA - out=\nsetups_test.go:34:\n c.Assert("Blah", Equals, "Bazz")\n... obtained string = "Blah"\n... expected string = "Bazz"\n\n TestFailed - actual=string = "Foo" - details=setups_test.go:29 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureTestBothErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureTestBothErrorSuite.TestA TestStarted - locationHint=gotest://FixtureTestBothErrorSuite.TestB - name=FixtureTestBothErrorSuite.TestB TestIgnored - name=FixtureTestBothErrorSuite.TestB TestFinished - duration=42 - name=FixtureTestBothErrorSuite.TestB TestSuiteFinished - name=FixtureTestBothErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 2 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/testBothFixturesError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureTestBothErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureTestBothErrorSuite.SetUpSuite 0.000s START: setups_test.go:37: FixtureTestBothErrorSuite.TestA START: setups_test.go:27: FixtureTestBothErrorSuite.SetUpTest setups_test.go:29: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:27: FixtureTestBothErrorSuite.SetUpTest START: setups_test.go:32: FixtureTestBothErrorSuite.TearDownTest setups_test.go:34: c.Assert("Blah", Equals, "Bazz") ... obtained string = "Blah" ... expected string = "Bazz" FAIL: setups_test.go:32: FixtureTestBothErrorSuite.TearDownTest ... Panic: Fixture has panicked (see related PANIC) PANIC: setups_test.go:37: FixtureTestBothErrorSuite.TestA START: setups_test.go:41: FixtureTestBothErrorSuite.TestB MISS: setups_test.go:41: FixtureTestBothErrorSuite.TestB START: setups_test.go:23: FixtureTestBothErrorSuite.TearDownSuite PASS: setups_test.go:23: FixtureTestBothErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 2 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureTestBothError 0.006s ================================================ FILE: testData/testing/gocheck/testErrorWithFixtures-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureTestErrorSuite - name=FixtureTestErrorSuite TestStarted - locationHint=gotest://FixtureTestErrorSuite.TestA - name=FixtureTestErrorSuite.TestA TestStdOut - name=FixtureTestErrorSuite.TestA - out=\n TestFailed - actual=string = "Foo" - details=setups_test.go:37 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureTestErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureTestErrorSuite.TestA TestStarted - locationHint=gotest://FixtureTestErrorSuite.TestB - name=FixtureTestErrorSuite.TestB TestStdOut - name=FixtureTestErrorSuite.TestB - out=\n\n TestFailed - details=/usr/local/go/src/runtime/panic.go:387\n in gopanic\nsetups_test.go:42\n in FixtureTestErrorSuite.TestB\n/usr/local/go/src/reflect/value.go:296\n in Value.Call\n/usr/local/go/src/runtime/asm_amd64.s:2232\n in goexit\n - message=Panic: Kaboom! (PC=0x3B0A5)\n - name=FixtureTestErrorSuite.TestB TestFinished - duration=42 - name=FixtureTestErrorSuite.TestB TestSuiteFinished - name=FixtureTestErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 1 PANICKED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/testErrorWithFixtures.txt ================================================ === RUN Test START: setups_test.go:19: FixtureTestErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureTestErrorSuite.SetUpSuite 0.000s START: setups_test.go:35: FixtureTestErrorSuite.TestA START: setups_test.go:27: FixtureTestErrorSuite.SetUpTest PASS: setups_test.go:27: FixtureTestErrorSuite.SetUpTest 0.000s setups_test.go:37: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" START: setups_test.go:31: FixtureTestErrorSuite.TearDownTest PASS: setups_test.go:31: FixtureTestErrorSuite.TearDownTest 0.000s FAIL: setups_test.go:35: FixtureTestErrorSuite.TestA START: setups_test.go:40: FixtureTestErrorSuite.TestB START: setups_test.go:27: FixtureTestErrorSuite.SetUpTest PASS: setups_test.go:27: FixtureTestErrorSuite.SetUpTest 0.000s START: setups_test.go:31: FixtureTestErrorSuite.TearDownTest PASS: setups_test.go:31: FixtureTestErrorSuite.TearDownTest 0.000s ... Panic: Kaboom! (PC=0x3B0A5) /usr/local/go/src/runtime/panic.go:387 in gopanic setups_test.go:42 in FixtureTestErrorSuite.TestB /usr/local/go/src/reflect/value.go:296 in Value.Call /usr/local/go/src/runtime/asm_amd64.s:2232 in goexit PANIC: setups_test.go:40: FixtureTestErrorSuite.TestB START: setups_test.go:23: FixtureTestErrorSuite.TearDownSuite PASS: setups_test.go:23: FixtureTestErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 1 PANICKED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureTestError 0.006s ================================================ FILE: testData/testing/gocheck/testSetUpError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureTestSetUpErrorSuite - name=FixtureTestSetUpErrorSuite TestStarted - locationHint=gotest://FixtureTestSetUpErrorSuite.TestA - name=FixtureTestSetUpErrorSuite.TestA TestFailed - actual=string = "Foo" - details=setups_test.go:29 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureTestSetUpErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureTestSetUpErrorSuite.TestA TestStarted - locationHint=gotest://FixtureTestSetUpErrorSuite.TestB - name=FixtureTestSetUpErrorSuite.TestB TestIgnored - name=FixtureTestSetUpErrorSuite.TestB TestFinished - duration=42 - name=FixtureTestSetUpErrorSuite.TestB TestSuiteFinished - name=FixtureTestSetUpErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/testSetUpError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureTestSetUpErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureTestSetUpErrorSuite.SetUpSuite 0.000s START: setups_test.go:36: FixtureTestSetUpErrorSuite.TestA START: setups_test.go:27: FixtureTestSetUpErrorSuite.SetUpTest setups_test.go:29: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:27: FixtureTestSetUpErrorSuite.SetUpTest START: setups_test.go:32: FixtureTestSetUpErrorSuite.TearDownTest PASS: setups_test.go:32: FixtureTestSetUpErrorSuite.TearDownTest 0.000s ... Panic: Fixture has panicked (see related PANIC) PANIC: setups_test.go:36: FixtureTestSetUpErrorSuite.TestA START: setups_test.go:40: FixtureTestSetUpErrorSuite.TestB MISS: setups_test.go:40: FixtureTestSetUpErrorSuite.TestB START: setups_test.go:23: FixtureTestSetUpErrorSuite.TearDownSuite PASS: setups_test.go:23: FixtureTestSetUpErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureTestSetUpError 0.006s ================================================ FILE: testData/testing/gocheck/testTearDownError-expected.txt ================================================ TestSuiteStarted - locationHint=gosuite://FixtureTestTearDownErrorSuite - name=FixtureTestTearDownErrorSuite TestStarted - locationHint=gotest://FixtureTestTearDownErrorSuite.TestA - name=FixtureTestTearDownErrorSuite.TestA TestStdOut - name=FixtureTestTearDownErrorSuite.TestA - out=\n TestFailed - actual=string = "Foo" - details=setups_test.go:33 - expected=string = "Bar" - message=c.Assert("Foo", Equals, "Bar") - name=FixtureTestTearDownErrorSuite.TestA - type=comparisonFailure TestFinished - duration=42 - name=FixtureTestTearDownErrorSuite.TestA TestStarted - locationHint=gotest://FixtureTestTearDownErrorSuite.TestB - name=FixtureTestTearDownErrorSuite.TestB TestIgnored - name=FixtureTestTearDownErrorSuite.TestB TestFinished - duration=42 - name=FixtureTestTearDownErrorSuite.TestB TestSuiteFinished - name=FixtureTestTearDownErrorSuite TestStdOut - name=SuiteTearDown - out=\nOOPS: 0 passed, 1 FAILED, 2 MISSED\n--- FAIL: Test (0.00s)\n ================================================ FILE: testData/testing/gocheck/testTearDownError.txt ================================================ === RUN Test START: setups_test.go:19: FixtureTestTearDownErrorSuite.SetUpSuite PASS: setups_test.go:19: FixtureTestTearDownErrorSuite.SetUpSuite 0.000s START: setups_test.go:36: FixtureTestTearDownErrorSuite.TestA START: setups_test.go:27: FixtureTestTearDownErrorSuite.SetUpTest PASS: setups_test.go:27: FixtureTestTearDownErrorSuite.SetUpTest 0.000s START: setups_test.go:31: FixtureTestTearDownErrorSuite.TearDownTest setups_test.go:33: c.Assert("Foo", Equals, "Bar") ... obtained string = "Foo" ... expected string = "Bar" FAIL: setups_test.go:31: FixtureTestTearDownErrorSuite.TearDownTest ... Panic: Fixture has panicked (see related PANIC) PANIC: setups_test.go:36: FixtureTestTearDownErrorSuite.TestA START: setups_test.go:40: FixtureTestTearDownErrorSuite.TestB MISS: setups_test.go:40: FixtureTestTearDownErrorSuite.TestB START: setups_test.go:23: FixtureTestTearDownErrorSuite.TearDownSuite PASS: setups_test.go:23: FixtureTestTearDownErrorSuite.TearDownSuite 0.000s OOPS: 0 passed, 1 FAILED, 2 MISSED --- FAIL: Test (0.00s) FAIL exit status 1 FAIL github.com/mailgun/sandbox/fixtureTestTearDownError 0.005s ================================================ FILE: testData/testing/gotest/multipleTestsFailed-expected.txt ================================================ TestStarted - locationHint=gotest://TestSqrt3 - name=TestSqrt3 TestFinished - duration=42 - name=TestSqrt3 TestStarted - locationHint=gotest://TestSqrt4 - name=TestSqrt4 TestStdOut - name=TestSqrt4 - out= test2_test.go:15: Sqrt(4) = 2, want 3\n TestFailed - message= - name=TestSqrt4 TestFinished - duration=42 - name=TestSqrt4 TestStarted - locationHint=gotest://TestSqrt - name=TestSqrt TestFinished - duration=42 - name=TestSqrt TestStarted - locationHint=gotest://TestSqrt2 - name=TestSqrt2 TestStdOut - name=TestSqrt2 - out= test_test.go:15: Sqrt(4) = 2, want 3\n TestFailed - message= - name=TestSqrt2 TestFinished - duration=42 - name=TestSqrt2 ================================================ FILE: testData/testing/gotest/multipleTestsFailed.txt ================================================ === RUN TestSqrt3 --- PASS: TestSqrt3 (0.00 seconds) === RUN TestSqrt4 --- FAIL: TestSqrt4 (0.00 seconds) test2_test.go:15: Sqrt(4) = 2, want 3 === RUN TestSqrt --- PASS: TestSqrt (0.00 seconds) === RUN TestSqrt2 --- FAIL: TestSqrt2 (0.00 seconds) test_test.go:15: Sqrt(4) = 2, want 3 FAIL exit status 1 FAIL _/Users/zolotov/IdeaProjects/untitled/go 0.013s ================================================ FILE: testData/testing/gotest/multipleTestsOk-expected.txt ================================================ TestStarted - locationHint=gotest://TestSqrt3 - name=TestSqrt3 TestFinished - duration=42 - name=TestSqrt3 TestStarted - locationHint=gotest://TestSqrt4 - name=TestSqrt4 TestFinished - duration=42 - name=TestSqrt4 TestStarted - locationHint=gotest://TestSqrt - name=TestSqrt TestFinished - duration=42 - name=TestSqrt TestStarted - locationHint=gotest://TestSqrt2 - name=TestSqrt2 TestFinished - duration=42 - name=TestSqrt2 ================================================ FILE: testData/testing/gotest/multipleTestsOk.txt ================================================ === RUN TestSqrt3 --- PASS: TestSqrt3 (0.00 seconds) === RUN TestSqrt4 --- PASS: TestSqrt4 (0.00 seconds) === RUN TestSqrt --- PASS: TestSqrt (0.00 seconds) === RUN TestSqrt2 --- PASS: TestSqrt2 (0.00 seconds) PASS ok _/Users/zolotov/IdeaProjects/untitled/go 0.012s ================================================ FILE: testData/testing/gotest/oneLineEvents-expected.txt ================================================ TestStarted - locationHint=gotest://Test_Sd - name=Test_Sd TestStdOut - name=Test_Sd - out=Test_Sd\n TestFinished - duration=42 - name=Test_Sd TestStarted - locationHint=gotest://Test_Sp - name=Test_Sp TestStdOut - name=Test_Sp - out= text1\n TestStdOut - name=Test_Sp - out=Test_Sp............end TestStdOut - name=Test_Sp - out= sputils_test.go:23: sad\n TestIgnored - message= - name=Test_Sp TestFinished - duration=42 - name=Test_Sp TestStarted - locationHint=gotest://Test_Sp2 - name=Test_Sp2 TestStdOut - name=Test_Sp2 - out= text2\n TestStdOut - name=Test_Sp2 - out=Test_Sp............end TestFinished - duration=42 - name=Test_Sp2 TestStarted - locationHint=gotest://Test_Sp3 - name=Test_Sp3 TestStdOut - name=Test_Sp3 - out= text3\n TestStdOut - name=Test_Sp3 - out=Test_Sp............end TestStdOut - name=Test_Sp3 - out= sputils_test.go:43: sad\n TestFailed - message= - name=Test_Sp3 TestFinished - duration=42 - name=Test_Sp3 ================================================ FILE: testData/testing/gotest/oneLineEvents.txt ================================================ === RUN Test_Sd Test_Sd --- PASS: Test_Sd (0.00 seconds) === RUN Test_Sp text1 Test_Sp............end--- SKIP: Test_Sp (0.00 seconds) sputils_test.go:23: sad === RUN Test_Sp2 text2 Test_Sp............end--- PASS: Test_Sp2 (0.00 seconds) === RUN Test_Sp3 text3 Test_Sp............end--- FAIL: Test_Sp3 (0.00 seconds) sputils_test.go:43: sad FAIL exit status 1 FAIL Spacer/src 0.008s ================================================ FILE: testData/testing/gotest/singleTestFailed-expected.txt ================================================ TestStarted - locationHint=gotest://TestSqrt2 - name=TestSqrt2 TestStdOut - name=TestSqrt2 - out= test_test.go:15: Sqrt(4) = 2, want 3\n TestFailed - message= - name=TestSqrt2 TestFinished - duration=42 - name=TestSqrt2 ================================================ FILE: testData/testing/gotest/singleTestFailed.txt ================================================ === RUN TestSqrt2 --- FAIL: TestSqrt2 (0.00 seconds) test_test.go:15: Sqrt(4) = 2, want 3 FAIL exit status 1 FAIL _/Users/zolotov/IdeaProjects/untitled/go 0.012s ================================================ FILE: testData/testing/gotest/singleTestLeadingSpaceOk-expected.txt ================================================ TestStarted - locationHint=gotest://TestFlagsGroups - name=TestFlagsGroups TestFinished - duration=42 - name=TestFlagsGroups ================================================ FILE: testData/testing/gotest/singleTestLeadingSpaceOk.txt ================================================ === RUN TestFlagsGroups --- PASS: TestFlagsGroups (0.00s) PASS ok some/package 0.118s ================================================ FILE: testData/testing/gotest/singleTestOk-expected.txt ================================================ TestStarted - locationHint=gotest://TestSqrt2 - name=TestSqrt2 TestFinished - duration=42 - name=TestSqrt2 ================================================ FILE: testData/testing/gotest/singleTestOk.txt ================================================ === RUN TestSqrt2 --- PASS: TestSqrt2 (0.00 seconds) PASS ok _/Users/zolotov/IdeaProjects/untitled/go 0.012s ================================================ FILE: testData/testing/gotest/skipTest-expected.txt ================================================ TestStarted - locationHint=gotest://TestRegistryGetOrRegister - name=TestRegistryGetOrRegister TestFinished - duration=42 - name=TestRegistryGetOrRegister TestStarted - locationHint=gotest://TestRuntimeMemStatsBlocking - name=TestRuntimeMemStatsBlocking TestStdOut - name=TestRuntimeMemStatsBlocking - out= runtime_test.go:20: skipping TestRuntimeMemStatsBlocking with GOMAXPROCS=1\n TestIgnored - message= - name=TestRuntimeMemStatsBlocking TestFinished - duration=42 - name=TestRuntimeMemStatsBlocking TestStarted - locationHint=gotest://TestExpDecaySample10 - name=TestExpDecaySample10 TestFinished - duration=42 - name=TestExpDecaySample10 ================================================ FILE: testData/testing/gotest/skipTest.txt ================================================ === RUN TestRegistryGetOrRegister --- PASS: TestRegistryGetOrRegister (0.00 seconds) === RUN TestRuntimeMemStatsBlocking --- SKIP: TestRuntimeMemStatsBlocking (0.00 seconds) runtime_test.go:20: skipping TestRuntimeMemStatsBlocking with GOMAXPROCS=1 === RUN TestExpDecaySample10 --- PASS: TestExpDecaySample10 (0.00 seconds) PASS ok github.com/dlsniper/go-metrics 0.069s ================================================ FILE: testData/testing/gotest/stdOut-expected.txt ================================================ TestStarted - locationHint=gotest://TestEWMA1 - name=TestEWMA1 TestStdOut - name=TestEWMA1 - out=hello\n TestStdOut - name=TestEWMA1 - out=hello\n TestStdOut - name=TestEWMA1 - out=\n TestFinished - duration=42 - name=TestEWMA1 TestStarted - locationHint=gotest://TestEWMA5 - name=TestEWMA5 TestStdOut - name=TestEWMA5 - out=hello2\n TestStdOut - name=TestEWMA5 - out=hello2\n TestStdOut - name=TestEWMA5 - out=\n TestStdOut - name=TestEWMA5 - out= ewma_test.go:122: 6 minute a.Rate(): 0.18071652714732128 != 0.18071652714732128\n TestFailed - message= - name=TestEWMA5 TestFinished - duration=42 - name=TestEWMA5 TestStarted - locationHint=gotest://TestEWMA15 - name=TestEWMA15 TestStdOut - name=TestEWMA15 - out=hello3\n TestStdOut - name=TestEWMA15 - out=hello3\n TestFinished - duration=42 - name=TestEWMA15 ================================================ FILE: testData/testing/gotest/stdOut.txt ================================================ === RUN TestEWMA1 hello hello --- PASS: TestEWMA1 (0.00 seconds) === RUN TestEWMA5 hello2 hello2 --- FAIL: TestEWMA5 (0.00 seconds) ewma_test.go:122: 6 minute a.Rate(): 0.18071652714732128 != 0.18071652714732128 === RUN TestEWMA15 hello3 hello3 --- PASS: TestEWMA15 (0.00 seconds) FAIL exit status 1 ================================================ FILE: testData/testing/gotest/subTests-expected.txt ================================================ TestStarted - locationHint=gotest://TestFoo - name=TestFoo TestStarted - locationHint=gotest://TestFoo/k[h]kjh_khk_jh - name=TestFoo/k[h]kjh_khk_jh TestStarted - locationHint=gotest://TestFoo/#00 - name=TestFoo/#00 TestStarted - locationHint=gotest://TestFoo/#00#01 - name=TestFoo/#00#01 TestStarted - locationHint=gotest://TestFoo/#01 - name=TestFoo/#01 TestStarted - locationHint=gotest://TestFoo/Bar - name=TestFoo/Bar TestStarted - locationHint=gotest://TestFoo/Bar/Buzz2 - name=TestFoo/Bar/Buzz2 TestStarted - locationHint=gotest://TestFoo/Bar/Buzz2#01 - name=TestFoo/Bar/Buzz2#01 TestStarted - locationHint=gotest://TestFoo/Bar#01 - name=TestFoo/Bar#01 TestStarted - locationHint=gotest://TestFoo/Bar#01/Buzz2 - name=TestFoo/Bar#01/Buzz2 TestStarted - locationHint=gotest://TestFoo/Bar#01/Buzz2#01 - name=TestFoo/Bar#01/Buzz2#01 TestFinished - duration=42 - name=TestFoo TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/k[h]kjh_khk_jh TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/#00 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/#00#01 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/#01 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar/Buzz2 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar/Buzz2#01 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar#01 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar#01/Buzz2 TestStdOut - name=TestFoo/Bar#01/Buzz2#01 - out= TestFinished - duration=42 - name=TestFoo/Bar#01/Buzz2#01 ================================================ FILE: testData/testing/gotest/subTests.txt ================================================ === RUN TestFoo === RUN TestFoo/k[h]kjh_khk_jh === RUN TestFoo/#00 === RUN TestFoo/#00#01 === RUN TestFoo/#01 === RUN TestFoo/Bar === RUN TestFoo/Bar/Buzz2 === RUN TestFoo/Bar/Buzz2#01 === RUN TestFoo/Bar#01 === RUN TestFoo/Bar#01/Buzz2 === RUN TestFoo/Bar#01/Buzz2#01 --- PASS: TestFoo (0.00s) --- PASS: TestFoo/k[h]kjh_khk_jh (0.00s) --- PASS: TestFoo/#00 (0.00s) --- PASS: TestFoo/#00#01 (0.00s) --- PASS: TestFoo/#01 (0.00s) --- PASS: TestFoo/Bar (0.00s) --- PASS: TestFoo/Bar/Buzz2 (0.00s) --- PASS: TestFoo/Bar/Buzz2#01 (0.00s) --- PASS: TestFoo/Bar#01 (0.00s) --- PASS: TestFoo/Bar#01/Buzz2 (0.00s) --- PASS: TestFoo/Bar#01/Buzz2#01 (0.00s) PASS ok foo 0.010s ================================================ FILE: testData/testing/gotest/unicodeTestName-expected.txt ================================================ TestStarted - locationHint=gotest://TestМойТест - name=TestМойТест TestFinished - duration=42 - name=TestМойТест ================================================ FILE: testData/testing/gotest/unicodeTestName.txt ================================================ === RUN TestМойТест --- PASS: TestМойТест (0.00 seconds) PASS ok _/Users/zolotov/IdeaProjects/untitled/go 0.012s ================================================ FILE: testData/testing/producer/benchmarkFunction_test.go ================================================ package main func BenchmarkName() { } ================================================ FILE: testData/testing/producer/benchmarkFunction_test.xml ================================================ ================================================ FILE: testData/testing/producer/directory.xml ================================================ ================================================ FILE: testData/testing/producer/exampleFunction_test.go ================================================ package main func ExampleName() { } ================================================ FILE: testData/testing/producer/exampleFunction_test.xml ================================================ ================================================ FILE: testData/testing/producer/fileWithBenchmarksOnly_test.go ================================================ package main func BenchmarkName() { } ================================================ FILE: testData/testing/producer/fileWithBenchmarksOnly_test.xml ================================================ ================================================ FILE: testData/testing/producer/fileWithGocheckTestsOnly_test.go ================================================ package hello_test import . "gopkg.in/check.v1" type MySuite struct{} var _ = Suite(&MySuite{}) func (s *MySuite) TestHelloWorld(c *C) { } ================================================ FILE: testData/testing/producer/fileWithGocheckTestsOnly_test.xml ================================================ ================================================ FILE: testData/testing/producer/fileWithTestsAndBenchmarks_test.go ================================================ package main func TestName() { } func BenchmarkName() { } ================================================ FILE: testData/testing/producer/fileWithTestsAndBenchmarks_test.xml ================================================ ================================================ FILE: testData/testing/producer/fileWithTestsOnly_test.go ================================================ package main func TestName() { } ================================================ FILE: testData/testing/producer/fileWithTestsOnly_test.xml ================================================ ================================================ FILE: testData/testing/producer/fileWithoutTest_test.go ================================================ package main func Hello() { } ================================================ FILE: testData/testing/producer/fileWithoutTest_test.xml ================================================ ================================================ FILE: testData/testing/producer/gocheckMethod_test.go ================================================ package hello_test import . "gopkg.in/check.v1" type MySuite struct{} var _ = Suite(&MySuite{}) func (s *MySuite) TestHelloWorld(c *C) { } ================================================ FILE: testData/testing/producer/gocheckMethod_test.xml ================================================ ================================================ FILE: testData/testing/producer/nonTestFile.go ================================================ package main func TestName() { } ================================================ FILE: testData/testing/producer/nonTestFile.xml ================================================ ================================================ FILE: testData/testing/producer/package_test.xml ================================================ ================================================ FILE: testData/testing/producer/simpleFunctionInFileWithTests_test.go ================================================ package main func NonTestName() { } func TestName() { } func BenchmarkName() { } ================================================ FILE: testData/testing/producer/simpleFunctionInFileWithTests_test.xml ================================================ ================================================ FILE: testData/testing/producer/simpleFunction_test.go ================================================ package main func NonTestName() { } ================================================ FILE: testData/testing/producer/simpleFunction_test.xml ================================================ ================================================ FILE: testData/testing/producer/testFunctionNonTestFile.go ================================================ package main func TestName() { } ================================================ FILE: testData/testing/producer/testFunctionNonTestFile.xml ================================================ ================================================ FILE: testData/testing/producer/testFunction_test.go ================================================ package main func TestName() { } ================================================ FILE: testData/testing/producer/testFunction_test.xml ================================================ ================================================ FILE: testData/usages/method.go ================================================ package main type MyType struct {} func _() { var s MyType = "asdf" println(s) } ================================================ FILE: testData/usages/type.go ================================================ package main type MyType struct {} type a struct { w MyType } ================================================ FILE: tests/com/goide/GoCodeInsightFixtureTestCase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.goide.sdk.GoSdkType; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.impl.DebugUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase; import com.intellij.util.ObjectUtils; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileContentImpl; import com.intellij.util.indexing.IndexingDataKeys; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.List; abstract public class GoCodeInsightFixtureTestCase extends LightPlatformCodeInsightFixtureTestCase { protected static String buildStubTreeText(@NotNull Project project, @NotNull VirtualFile file, @NotNull String fileContent, boolean checkErrors) throws IOException { String path = file.getPath(); PsiFile psi = PsiFileFactory.getInstance(project).createFileFromText(file.getName(), file.getFileType(), fileContent); if (checkErrors) { assertFalse(path + " contains error elements", DebugUtil.psiToString(psi, true).contains("PsiErrorElement")); } String full = DebugUtil.stubTreeToString(GoFileElementType.INSTANCE.getBuilder().buildStubTree(psi)); psi.putUserData(IndexingDataKeys.VIRTUAL_FILE, file); FileContentImpl content = new FileContentImpl(file, fileContent, file.getCharset()); PsiFile psiFile = content.getPsiFile(); String fast = DebugUtil.stubTreeToString(GoFileElementType.INSTANCE.getBuilder().buildStubTree(psiFile)); if (!Comparing.strEqual(full, fast)) { System.err.println(path); UsefulTestCase.assertSameLines(full, fast); } return fast; } @NotNull protected PsiElement findElementAtCaretOrInSelection() { SelectionModel selectionModel = myFixture.getEditor().getSelectionModel(); if (selectionModel.hasSelection()) { PsiElement left = myFixture.getFile().findElementAt(selectionModel.getSelectionStart()); PsiElement right = myFixture.getFile().findElementAt(selectionModel.getSelectionEnd() - 1); assertNotNull(left); assertNotNull(right); return ObjectUtils.assertNotNull(PsiTreeUtil.findCommonParent(left, right)); } else { return ObjectUtils.assertNotNull(myFixture.getFile().findElementAt(myFixture.getEditor().getCaretModel().getOffset())); } } @Override protected void setUp() throws Exception { super.setUp(); GoApplicationLibrariesService.getInstance().setLibraryRootUrls("temp:///"); GoModuleSettings.getInstance(myFixture.getModule()).setVendoringEnabled(ThreeState.YES); if (isSdkAware()) setUpProjectSdk(); } @Override protected void tearDown() throws Exception { try { GoApplicationLibrariesService.getInstance().setLibraryRootUrls(); GoModuleSettings.getInstance(myFixture.getModule()).setBuildTargetSettings(new GoBuildTargetSettings()); GoModuleSettings.getInstance(myFixture.getModule()).setVendoringEnabled(ThreeState.UNSURE); } finally { //noinspection ThrowFromFinallyBlock super.tearDown(); } } // todo[zolotov] remove after 2016.3 @Override protected boolean isWriteActionRequired() { return false; } @Override protected final String getTestDataPath() { return new File("testData/" + getBasePath()).getAbsolutePath(); } @NotNull private static DefaultLightProjectDescriptor createMockProjectDescriptor() { return new DefaultLightProjectDescriptor() { @NotNull @Override public Sdk getSdk() { return createMockSdk("1.1.2"); } @NotNull @Override public ModuleType getModuleType() { return GoModuleType.getInstance(); } }; } private void setUpProjectSdk() { ApplicationManager.getApplication().runWriteAction(() -> { Sdk sdk = getProjectDescriptor().getSdk(); ProjectJdkTable.getInstance().addJdk(sdk); ProjectRootManager.getInstance(myFixture.getProject()).setProjectSdk(sdk); }); } @NotNull private static Sdk createMockSdk(@NotNull String version) { String homePath = new File("testData/mockSdk-" + version + "/").getAbsolutePath(); GoSdkType sdkType = GoSdkType.getInstance(); ProjectJdkImpl sdk = new ProjectJdkImpl("Go " + version, sdkType, homePath, version); sdkType.setupSdkPaths(sdk); sdk.setVersionString(version); return sdk; } @NotNull protected static String loadText(@NotNull VirtualFile file) { try { return StringUtil.convertLineSeparators(VfsUtilCore.loadText(file)); } catch (IOException e) { throw new RuntimeException(e); } } protected void disableVendoring() { GoModuleSettings.getInstance(myFixture.getModule()).setVendoringEnabled(ThreeState.NO); } protected static String normalizeCode(@NotNull String codeBefore) { StringBuilder result = new StringBuilder("package main\nfunc main() {\n"); if ("\n".equals(codeBefore)) { result.append(codeBefore); } for (String line : StringUtil.splitByLines(codeBefore, false)) { result.append('\t').append(line).append('\n'); } result.append("}"); return result.toString(); } @Override protected LightProjectDescriptor getProjectDescriptor() { return isSdkAware() ? createMockProjectDescriptor() : null; } private boolean isSdkAware() {return annotatedWith(SdkAware.class);} protected void applySingleQuickFix(@NotNull String quickFixName) { List availableIntentions = myFixture.filterAvailableIntentions(quickFixName); IntentionAction action = ContainerUtil.getFirstItem(availableIntentions); assertNotNull(action); myFixture.launchAction(action); } } ================================================ FILE: tests/com/goide/GoDocumentationProviderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.List; @SdkAware public class GoDocumentationProviderTest extends GoCodeInsightFixtureTestCase { public void testPrintln() { doTest(); } public void testFprintln() { doTest(); } public void testMethod() { doTest(); } public void testVariable() { doTest(); } public void testVariableInSwitch() { doTest(); } public void testEscape() { doTest(); } public void testEscapeReturnValues() { doTest(); } public void testPackageWithDoc() { doTest(); } public void testPackage() { doTest(); } public void testPackageOnQualifier() { doTest(); } public void testPackageOnImportAlias() { doTest(); } public void testTypeResultDefinition() { doTest(); } public void testMultilineTypeListDefinition() { doTest(); } public void testMultilineVariable_1() { doTest(); } public void testMultilineVariable_2() { doTest(); } public void testMultilineVariable_3() { doTest(); } public void testMultilineVariable_4() { doTest(); } public void testMultilineVariable_5() { doTest(); } public void testFieldDeclaration() { doTest(); } public void testSignature() { doTest(); } public void testStruct() { doTest(); } public void testTypeSpec() { doTest(); } public void testTypeTopDefinition() { doTest(); } public void testTypeInnerDefinitionWithoutComment() { doTest(); } public void testConstants() { doTest(); } public void testVarShortDefinition() { doTest(); } public void testSpecType() { doTest(); } public void testPointer() { doTest(); } public void testFunctionType() { doTest(); } public void testParameter() { doTest(); } public void testResultParameter() { doTest(); } public void testReceiver() { doTest(); } public void testStructWithAnon() { doTest(); } public void testMultiBlockDoc() { doConverterTest(); } public void testIndentedBlock() { doConverterTest(); } public void testCommentEndsWithIndentedBlock() { doConverterTest(); } public void testQuotedStrings() { doConverterTest(); } public void testLinks() { doConverterTest(); } @NotNull @Override protected String getBasePath() { return "doc"; } private void doConverterTest() { try { List lines = FileUtil.loadLines(getTestDataPath() + "/" + getTestName(true) + "_source.txt"); assertSameLinesWithFile(getTestDataPath() + "/" + getTestName(true) + "_after.txt", new GoCommentsConverter().textToHtml(lines)); } catch (IOException e) { throw new RuntimeException(e); } } private void doTest() { myFixture.configureByFile(getTestName(true) + ".go"); Editor editor = myFixture.getEditor(); PsiFile file = myFixture.getFile(); PsiElement originalElement = file.findElementAt(editor.getCaretModel().getOffset()); assertNotNull(originalElement); PsiElement docElement = DocumentationManager.getInstance(getProject()).findTargetElement(editor, file); DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(originalElement); String actualDoc = StringUtil.notNullize(documentationProvider.generateDoc(docElement, originalElement)); String quickNavigateInfo = documentationProvider.getQuickNavigateInfo(docElement, originalElement); actualDoc += "\n=====\n" + StringUtil.notNullize(quickNavigateInfo, "No navigation info"); List urls = documentationProvider.getUrlFor(docElement, originalElement); actualDoc += "\n=====\n" + (urls != null ? StringUtil.join(urls, "\n") : "No urls"); String localUrl = GoDocumentationProvider.getLocalUrlToElement(docElement); actualDoc += "\n=====\n" + StringUtil.notNullize(localUrl, "No local urls"); assertSameLinesWithFile(getTestDataPath() + "/" + getTestName(true) + ".txt", actualDoc); if (localUrl != null) { PsiElement elementForLink = documentationProvider.getDocumentationElementForLink(myFixture.getPsiManager(), localUrl, originalElement); assertNotNull("Link '" + localUrl + "' wasn't resolved", elementForLink); assertEquals("Link was resolved to unexpected element.\nExpected: " + docElement.getText() + "\n" + "Actual: " + elementForLink.getText(), docElement, elementForLink); } } } ================================================ FILE: tests/com/goide/GoFindUsageTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.psi.GoStatement; import com.goide.sdk.GoSdkService; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.testFramework.exceptionCases.AssertionErrorCase; import com.intellij.usageView.UsageInfo; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import static com.intellij.util.containers.ContainerUtil.newArrayList; @SdkAware public class GoFindUsageTest extends GoCodeInsightFixtureTestCase { private static final String USAGE = "/*usage*/"; private void doTest(@NotNull String text) { List offsets = allOccurrences(StringUtil.replace(text, "", ""), USAGE); String replace = StringUtil.replace(text, USAGE, ""); myFixture.configureByText("a.go", replace); PsiElement atCaret = myFixture.getElementAtCaret(); List actual = ContainerUtil.map(myFixture.findUsages(atCaret), UsageInfo::getNavigationOffset); assertSameElements(actual, offsets); } @NotNull private static List allOccurrences(@NotNull String text, @NotNull String what) { List list = newArrayList(); int index = text.indexOf(what); while (index >= 0) { list.add(index - list.size() * what.length()); index = text.indexOf(what, index + 1); } return list; } public void testBuiltinHighlighting() { myFixture.configureByText("a.go", "package main; func bar() int {}"); assertSize(1, myFixture.findUsages(myFixture.getElementAtCaret())); } // #2301 public void testCheckImportInWholePackage() { myFixture.addFileToProject("bar/bar1.go", "package bar; func Bar() { b := bar{}; b.f.Method() }"); myFixture.addFileToProject("bar/bar.go", "package bar; import \"foo\"; type bar struct { f *foo.Foo }"); PsiFile file = myFixture.addFileToProject("foo/foo.go", "package foo; type Foo struct{}; func (*Foo) Method() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); Collection usages = myFixture.findUsages(myFixture.getElementAtCaret()); assertSize(1, usages); UsageInfo first = usages.iterator().next(); PsiElement e = first.getElement(); GoStatement statement = PsiTreeUtil.getParentOfType(e, GoStatement.class); assertNotNull(statement); assertEquals("b.f.Method()", statement.getText()); } public void testCheckImportInWholePackageWithRelativeImports() { myFixture.addFileToProject("bar/bar1.go", "package bar; func Bar() { b := bar{}; b.f.Method() }"); myFixture.addFileToProject("bar/bar.go", "package bar; import \"..\"; type bar struct { f *foo.Foo }"); myFixture.configureByText("foo.go", "package foo; type Foo struct{}; func (*Foo) Method() {}"); assertSize(1, myFixture.findUsages(myFixture.getElementAtCaret())); } public void testOverride() { doTest("package p\n" + "func test2() {\n" + " y := 1\n" + " {\n" + " y, _ := 10, 1\n" + " fmt.Println(/*usage*/y)\n" + " }\n" + "}\n"); } public void testOverride1() { doTest("package p\n" + "func test2() {\n" + " y := 1\n" + " /*usage*/y, _ := 10, 1\n" + " /*usage*/y, x := 10, 1\n" + " fmt.Println(/*usage*/y)\n" + "}\n"); } public void testOverride2() { doTest("package p\n" + "func test2() {\n" + " y := 1\n" + " {\n" + " y, _ := 10, 1\n" + " fmt.Println(y)\n" + " }\n" + "}\n"); } public void testFunctionParam() { doTest("package p\n" + "func aaa(a int) {\n" + " /*usage*/a\n" + " var a int\n" + " a := 1\n" + "}\n"); } public void testDeclaredInForRange() { doTest("package main\n" + "const key = iota\n" + "func main() {\n" + " key := 1\n" + " for key, val := range m {\n" + " y := /*usage*/key\n" + " }\n" + "}"); } public void testMethodWithTransitiveImport() { myFixture.addFileToProject("a.go", "package main; import `middle`; func main() { fmt.Println(middle.A.Method()) }"); myFixture.addFileToProject("middle/middle.go", "package middle; import `declaration`; var A *declaration.D = nil"); PsiFile file = myFixture.addFileToProject("declaration/declaration.go", "package declaration; type D struct {}; func (D) Method() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); Collection usages = myFixture.findUsages(myFixture.getElementAtCaret()); assertEquals(1, usages.size()); //noinspection ConstantConditions assertEquals("a.go", usages.iterator().next().getFile().getName()); } public void testDoNoLoadUnreachableVendorDirectory() { myFixture.addFileToProject("a.go", "package a; import `foo/vendor/foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/vendor/foo/foo.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); myFixture.findUsages(myFixture.getElementAtCaret()); } public void testDoNoLoadUnreachableInternalDirectory() { GoSdkService.setTestingSdkVersion("1.5", getTestRootDisposable()); myFixture.addFileToProject("a.go", "package a; import `foo/internal/foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/internal/foo/foo.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); myFixture.findUsages(myFixture.getElementAtCaret()); } public void testDoNoLoadNotImportedDirectory() { myFixture.addFileToProject("bar/bar.go", "package bar; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/foo.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); myFixture.findUsages(myFixture.getElementAtCaret()); } public void testDoNoLoadTestDirectoryFromTestFileWithDifferentPackage() { myFixture.addFileToProject("bar/bar_test.go", "package bar; import `foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/foo_test.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); myFixture.findUsages(myFixture.getElementAtCaret()); } public void testDoNoLoadTestDirectoryFromProductionFile() { myFixture.addFileToProject("bar/bar.go", "package bar; import `foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/foo_test.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); myFixture.findUsages(myFixture.getElementAtCaret()); } public void testLoadTestDirectoryFromTestFile() throws Throwable { myFixture.addFileToProject("foo/bar_test.go", "package foo_test; import `foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/foo_test.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); assertException(new AssertionErrorCase() { @Override public void tryClosure() { try { myFixture.findUsages(myFixture.getElementAtCaret()); } catch (AssertionError e) { String message = e.getMessage(); assertTrue(message.contains("Access to tree elements not allowed in tests")); assertTrue(message.contains("bar_test.go")); throw e; } } }); } public void testLoadSdkUsagesForSdkDeclarations() throws Throwable { myFixture.configureByText("bar.go", "package foo; import `io`; type ReaderWrapper interface{io.Reader}"); failOnFileLoading(); assertException(new AssertionErrorCase() { @Override public void tryClosure() { try { assertSize(5, myFixture.findUsages(myFixture.getElementAtCaret())); } catch (AssertionError e) { String message = e.getMessage(); assertTrue(message.contains("Access to tree elements not allowed in tests")); assertTrue(message.contains("io.go")); throw e; } } }); } public void testDoNotLoadSdkUsagesForProjectDeclarations() { myFixture.configureByText("foo.go", "package foo; func _() { Println() }"); myFixture.configureByText("bar.go", "package foo; func Println() {}"); failOnFileLoading(); assertSize(1, myFixture.findUsages(myFixture.getElementAtCaret())); } public void testLoadImportedDirectory() throws Throwable { myFixture.addFileToProject("bar/bar.go", "package bar; import `foo`; func _() { println(CONST_NAME) }"); PsiFile declarationFile = myFixture.addFileToProject("foo/foo.go", "package foo; const CONST_NAME = 1;"); myFixture.configureFromExistingVirtualFile(declarationFile.getVirtualFile()); failOnFileLoading(); assertException(new AssertionErrorCase() { @Override public void tryClosure() { try { assertSize(1, myFixture.findUsages(myFixture.getElementAtCaret())); } catch (AssertionError e) { String message = e.getMessage(); assertTrue(message.contains("Access to tree elements not allowed in tests")); assertTrue(message.contains("bar.go")); throw e; } } }); } public void testSdkTestDataDirectory() { myFixture.configureByText("a.go", "package a; import `doc/testdata`; func _() { println(pkg.ExportedConstant) } "); PsiReference reference = myFixture.getFile().findReferenceAt(myFixture.getCaretOffset()); PsiElement resolve = reference != null ? reference.resolve() : null; assertNotNull(resolve); assertEquals("pkg.go", resolve.getContainingFile().getName()); assertEmpty(myFixture.findUsages(resolve)); } private void failOnFileLoading() { ((PsiManagerImpl)myFixture.getPsiManager()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, getTestRootDisposable()); } private void doTestDoNotFind(@NotNull String text) { myFixture.configureByText("a.go", text); PsiElement atCaret = myFixture.getElementAtCaret(); try { myFixture.findUsages(atCaret); fail("Shouldn't be performed"); } catch (AssertionError e) { assertEquals("Cannot find handler for: IMPORT_SPEC", e.getMessage()); } } public void testDot() { doTestDoNotFind("package main; import . \"fmt\""); } public void testUnderscore() { doTestDoNotFind("package main; import _ \"fmt\""); } public void testNearImportString() { doTestDoNotFind("package main; import \"fmt\""); } } ================================================ FILE: tests/com/goide/GoParametrizedTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.testFramework.EdtTestUtil; import com.intellij.testFramework.TestRunnerUtil; import com.intellij.util.ThrowableRunnable; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public abstract class GoParametrizedTestBase extends GoCodeInsightFixtureTestCase { protected abstract void doTest(); @Test public void test() { safeEdt(this::doTest); } @SuppressWarnings("SetUpDoesntCallSuperSetUp") @Before @Override public void setUp() throws Exception { safeEdt(super::setUp); } @SuppressWarnings("TearDownDoesntCallSuperTearDown") @After @Override public void tearDown() { safeEdt(super::tearDown); } private void safeEdt(@NotNull ThrowableRunnable r) { if (runInDispatchThread()) { TestRunnerUtil.replaceIdeEventQueueSafely(); EdtTestUtil.runInEdtAndWait(r); } else { try { r.run(); } catch (Throwable t) { throw new RuntimeException(t); } } } } ================================================ FILE: tests/com/goide/GoPerformanceTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.categories.Performance; import com.goide.completion.GoCompletionUtil; import com.goide.inspections.GoUnusedImportInspection; import com.goide.inspections.unresolved.*; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.ex.InspectionManagerEx; import com.intellij.codeInspection.ex.InspectionToolRegistrar; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.testFramework.InspectionTestUtil; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import com.intellij.testFramework.fixtures.impl.GlobalInspectionContextForTests; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.experimental.categories.Category; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; @Category(Performance.class) public class GoPerformanceTest extends GoCodeInsightFixtureTestCase { @Override public void setUp() throws Exception { super.setUp(); GoBuildTargetSettings buildTargetSettings = new GoBuildTargetSettings(); buildTargetSettings.os = "darwin"; buildTargetSettings.arch = "amd64"; buildTargetSettings.goVersion = "1.5.1"; GoModuleSettings.getInstance(myFixture.getModule()).setBuildTargetSettings(buildTargetSettings); } public void testUnusedVariable() { doInspectionTest(new GoUnusedVariableInspection(), TimeUnit.SECONDS.toMillis(30)); } public void testUnusedGlobalVariable() { doInspectionTest(new GoUnusedGlobalVariableInspection(), TimeUnit.SECONDS.toMillis(30)); } public void _testUnresolvedReference() { doInspectionTest(new GoUnresolvedReferenceInspection(), TimeUnit.MINUTES.toMillis(4)); } public void testUnusedFunction() { doInspectionTest(new GoUnusedFunctionInspection(), TimeUnit.SECONDS.toMillis(15)); } public void testUnusedExportedFunction() { doInspectionTest(new GoUnusedExportedFunctionInspection(), TimeUnit.SECONDS.toMillis(30)); } public void testUnusedImport() { doInspectionTest(new GoUnusedImportInspection(), TimeUnit.SECONDS.toMillis(20)); } public void testPerformanceA() { doHighlightingTest(TimeUnit.SECONDS.toMillis(10)); } public void testPerformanceA2() { doHighlightingTest(TimeUnit.SECONDS.toMillis(10)); } public void testCompletionPerformance() { doCompletionTest("package main; func main() { }", 2, TimeUnit.SECONDS.toMillis(15)); } public void testCompletionWithPrefixPerformance() { doCompletionTest("package main; func main() { slee }", 1, TimeUnit.SECONDS.toMillis(5)); } public void testCompletionPerformanceWithoutTypes() { GoCompletionUtil.disableTypeInfoInLookup(getTestRootDisposable()); doCompletionTest("package main; func main() { }", 2, TimeUnit.SECONDS.toMillis(15)); } public void testCompletionWithPrefixPerformanceWithoutTypes() { GoCompletionUtil.disableTypeInfoInLookup(getTestRootDisposable()); doCompletionTest("package main; func main() { slee }", 1, TimeUnit.SECONDS.toMillis(5)); } private void doCompletionTest(@NotNull String source, int invocationCount, long expectation) { VirtualFile go = installTestData("go"); if (go == null) return; myFixture.configureByText(GoFileType.INSTANCE, source); PlatformTestUtil.startPerformanceTest(getTestName(true), (int)expectation, () -> myFixture.complete(CompletionType.BASIC, invocationCount)).cpuBound().usesAllCPUCores().assertTiming(); } private void doHighlightingTest(long expectation) { PlatformTestUtil.startPerformanceTest(getTestName(true), (int)expectation, () -> myFixture.testHighlighting(true, false, false, getTestName(true) + ".go")).cpuBound().usesAllCPUCores().assertTiming(); } private void doInspectionTest(@NotNull InspectionProfileEntry tool, long expected) { VirtualFile sourceDir = installTestData("docker"); if (sourceDir == null) return; //noinspection ConstantConditions AnalysisScope scope = new AnalysisScope(getPsiManager().findDirectory(sourceDir)); scope.invalidate(); InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(getProject()); InspectionToolWrapper wrapper = InspectionToolRegistrar.wrapTool(tool); GlobalInspectionContextForTests globalContext = CodeInsightTestFixtureImpl.createGlobalContextForTool(scope, getProject(), inspectionManager, wrapper); PlatformTestUtil.startPerformanceTest(getTestName(true), (int)expected, () -> InspectionTestUtil.runTool(wrapper, scope, globalContext)).cpuBound().usesAllCPUCores().assertTiming(); InspectionTestUtil.compareToolResults(globalContext, wrapper, false, new File(getTestDataPath(), wrapper.getShortName()).getPath()); } @Nullable private VirtualFile installTestData(@NotNull String testData) { if (!new File(myFixture.getTestDataPath(), testData).exists()) { System.err.println("For performance tests you need to have a docker project inside testData/" + getBasePath() + " directory"); return null; } return myFixture.copyDirectoryToProject(testData, testData); } public void testParserAndStubs() { File go = new File(getTestDataPath(), "go"); if (!go.exists()) { System.err.println( "For performance tests you need to have a go sources (https://storage.googleapis.com/golang/go1.4.2.src.tar.gz) inside testData/" + getBasePath() + " directory"); return; } PlatformTestUtil.startPerformanceTest(getTestName(true), (int)TimeUnit.MINUTES.toMillis(1), () -> { VirtualFile root = LocalFileSystem.getInstance().findFileByIoFile(go); assertNotNull(root); VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() { @NotNull @Override public Result visitFileEx(@NotNull VirtualFile file) { if (file.isDirectory() && "testdata".equals(file.getName())) return SKIP_CHILDREN; if (file.isDirectory() && "test".equals(file.getName()) && file.getParent().equals(root)) return SKIP_CHILDREN; if (file.getFileType() != GoFileType.INSTANCE) return CONTINUE; try { System.out.print("."); buildStubTreeText(getProject(), file, FileUtil.loadFile(new File(file.getPath()), "UTF-8", true).trim(), true); } catch (IOException ignored) { } return CONTINUE; } }); }).usesAllCPUCores().assertTiming(); } @NotNull @Override protected String getBasePath() { return "performance"; } } ================================================ FILE: tests/com/goide/GoSdkServiceTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.goide.sdk.GoSdkService; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class GoSdkServiceTest extends UsefulTestCase { public void testRegularSdkPath() { setIsWindows(false); setIsLinux(false); PlatformTestUtil.assertPathsEqual("/path/to/sdk/bin/go", executable("/path/to/sdk")); } public void testRegularSdkPathWithGorootName() { setIsWindows(false); setIsLinux(false); String sdkPath = createDir("goroot/").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/goroot/bin/go", executable(sdkPath + "/goroot")); } public void testSingletonAppEngineSdkPath() { setIsWindows(false); String sdkPath = createDir("goroot/", "goapp").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/goapp", executable(sdkPath + "/goroot")); } public void testGcloudAppEngineSdkPath() { setIsWindows(false); String sdkPath = createDir("platform/google_appengine/goroot/", "bin/goapp").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/bin/goapp", executable(sdkPath + "/platform/google_appengine/goroot")); } public void testRegularSdkPathWindows() { setIsWindows(true); setIsLinux(false); String sdkPath = createDir("platform/google_appengine/goroot/", "bin/goapp").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/bin/go.exe", executable(sdkPath)); } public void testSingletonAppEngineSdkPathWindows() { setIsWindows(true); String sdkPath = createDir("goroot/", "goapp.bat").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/goapp.bat", executable(sdkPath + "/goroot")); } public void testGcloudAppEngineSdkPathWindows() { setIsWindows(true); String sdkPath = createDir("platform/google_appengine/goroot/", "bin/goapp.cmd").getAbsolutePath(); PlatformTestUtil.assertPathsEqual(sdkPath + "/bin/goapp.cmd", executable(sdkPath + "/platform/google_appengine/goroot")); } private static String executable(@NotNull String sdkPath) { return GoSdkService.getGoExecutablePath(sdkPath); } private void setIsWindows(boolean value) { setIsWindows(value, SystemInfo.isWindows, "isWindows"); } private void setIsLinux(boolean value) { setIsWindows(value, SystemInfo.isLinux, "isLinux"); } private void setIsWindows(boolean value, boolean oldValue, @NotNull String fieldName) { try { Field field = SystemInfo.class.getField(fieldName); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, value); Disposer.register(getTestRootDisposable(), () -> { try { field.set(null, oldValue); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }); } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); } } private static File createDir(String... children) { try { File dir = FileUtil.createTempDirectory("goSdk", "test"); for (String child : children) { File file = new File(dir, child); FileUtil.createParentDirs(file); if (StringUtil.endsWithChar(child, '/')) { assertTrue(file.mkdir()); } else { assertTrue(file.createNewFile()); } } return dir; } catch (IOException e) { throw new RuntimeException(e); } } } ================================================ FILE: tests/com/goide/SdkAware.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface SdkAware { } ================================================ FILE: tests/com/goide/actions/GoCreateFileActionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.actions; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoFile; import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.ide.fileTemplates.impl.CustomFileTemplate; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class GoCreateFileActionTest extends GoCodeInsightFixtureTestCase { public void testPackageNameInEmptyDirectory() throws Exception { doTestInEmptyDirectory("empty-dir", "a", "empty_dir", "empty_dir"); } public void testPackageNameInEmptyDirectoryWithTestSuffix() throws Exception { doTestInEmptyDirectory("empty-dir-test", "a_test", "empty_dir_test", "empty_dir_test_test"); } public void testPackageNameInExistingPackage() { doTestWithExistingPackage("b", "a", "a"); } public void testTestPackageNameInExistingPackage() { doTestWithExistingPackage("a_test", "a", "a_test"); } public void testPackageNameInExistingPackageWithExtension() { doTestWithExistingPackage("b.go", "a", "a"); } public void testTestPackageNameInExistingPackageWithExtension() { doTestWithExistingPackage("a_test.go", "a", "a_test"); } private void doTestWithExistingPackage(@NotNull String fileName, @NotNull String expectedPackage, @NotNull String expectedPackageWithTestSuffix) { myFixture.configureByText("a.go", "package a"); doTest(myFixture.getFile().getContainingDirectory(), fileName, expectedPackage, expectedPackageWithTestSuffix); } private void doTestInEmptyDirectory(@NotNull String directoryName, @NotNull String newFileName, @NotNull String expectedPackage, @NotNull String expectedPackageWithTestSuffix) { try { PsiDirectory dir = myFixture.getPsiManager().findDirectory(myFixture.getTempDirFixture().findOrCreateDir(directoryName)); assertNotNull(dir); doTest(dir, newFileName, expectedPackage, expectedPackageWithTestSuffix); } catch (IOException e) { throw new RuntimeException(e); } } private static void doTest(@NotNull PsiDirectory dir, @NotNull String newFileName, @NotNull String expectedPackage, @NotNull String expectedPackageWithTestSuffix) { CustomFileTemplate template = new CustomFileTemplate("testTemplate", "go"); template.setText("package ${GO_PACKAGE_NAME}"); CustomFileTemplate templateWithSuffix = new CustomFileTemplate("testTemplate", "go"); templateWithSuffix.setText("package ${GO_PACKAGE_NAME_WITH_TEST_SUFFIX}"); doTemplateTest(dir, newFileName, expectedPackage, template); doTemplateTest(dir, newFileName, expectedPackageWithTestSuffix, templateWithSuffix); } private static void doTemplateTest(@NotNull PsiDirectory dir, @NotNull String newFileName, @NotNull String expectedPackage, @NotNull CustomFileTemplate template) { GoFile file = (GoFile)CreateFileFromTemplateAction.createFileFromTemplate(newFileName, template, dir, null, true); assertNotNull(file); assertEquals(expectedPackage, file.getPackageName()); WriteCommandAction.runWriteCommandAction(dir.getProject(), file::delete); } } ================================================ FILE: tests/com/goide/categories/Performance.java ================================================ package com.goide.categories; public interface Performance {} ================================================ FILE: tests/com/goide/codeInsight/imports/GoImportOptimizerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.SdkAware; import com.goide.inspections.GoUnusedImportInspection; import com.goide.quickfix.GoQuickFixTestBase; import com.intellij.codeInsight.actions.OptimizeImportsAction; import com.intellij.ide.DataManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.psi.PsiReference; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import org.jetbrains.annotations.NotNull; @SdkAware public class GoImportOptimizerTest extends GoQuickFixTestBase { public void testUnusedImports() { doTest(); } public void testUnusedImportsWithSemicolon() { doTest(); } public void testUnusedImplicitImports() { doTest(); } public void testUsedImplicitImports() { doTest(); } public void testUsedDuplicatedImports() { doTest(); } public void testDuplicatedImportsWithSameStringAndDifferentQuotes() { doTest(); } public void testDuplicatedImportsWithSameString() { doTest(); } public void testDuplicatedImportsWithDifferentString() { doTest(); } public void testUnusedDuplicatedImports() { doTest(); } public void testImportPackageWithMainFiles() { doTest(); } public void testImportDirectoryWithoutPackages() { doTest(); } public void testUnusedImportsWithBacktick() { doTest(); } public void testDoNotOptimizeSideEffectImports() { doTest(); } public void testRedundantImportQualifier() { doTest(); } public void testUnusedImportsQuickFix() { myFixture.configureByFile(getTestName(true) + ".go"); myFixture.checkHighlighting(); applySingleQuickFix("Optimize imports"); myFixture.checkResultByFile(getTestName(true) + "_after.go"); } public void testImportWithSameIdentifier() { myFixture.addFileToProject("foo/bar/buzz.go", "package bar; func Hello() {}"); doTest(); } public void testImportWithMultiplePackages() { myFixture.addFileToProject("pack/pack_test.go", "package pack_test; func Test() {}"); myFixture.addFileToProject("pack/pack.go", "package pack;"); doTest(); } private void doTest() { PsiFile file = myFixture.configureByFile(getTestName(true) + ".go"); resolveAllReferences(file); myFixture.checkHighlighting(); ApplicationManager.getApplication().runWriteAction( () -> OptimizeImportsAction.actionPerformedImpl(DataManager.getInstance().getDataContext(myFixture.getEditor().getContentComponent()))); myFixture.checkResultByFile(getTestName(true) + "_after.go"); } public static void resolveAllReferences(PsiFile file) { file.accept(new PsiRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement o) { for (PsiReference reference : o.getReferences()) { reference.resolve(); } super.visitElement(o); } }); } @Override public void setUp() throws Exception { super.setUp(); ((CodeInsightTestFixtureImpl)myFixture).canChangeDocumentDuringHighlighting(true); myFixture.enableInspections(GoUnusedImportInspection.class); } @NotNull @Override protected String getBasePath() { return "imports/optimize"; } } ================================================ FILE: tests/com/goide/codeInsight/imports/GoReferenceImporterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.imports; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiFile; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import java.util.List; @SdkAware public class GoReferenceImporterTest extends GoCodeInsightFixtureTestCase { private boolean defaultJavaOnTheFly; private boolean defaultJavaMemberOnTheFly; private boolean defaultGoOnTheFly; private static void updateSettings(boolean onTheFlyEnabled) { GoCodeInsightSettings.getInstance().setAddUnambiguousImportsOnTheFly(onTheFlyEnabled); } @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); ((CodeInsightTestFixtureImpl)myFixture).canChangeDocumentDuringHighlighting(true); CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance(); defaultJavaOnTheFly = codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY; defaultJavaMemberOnTheFly = codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY; defaultGoOnTheFly = GoCodeInsightSettings.getInstance().isAddUnambiguousImportsOnTheFly(); codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = true; codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY = true; } @Override protected void tearDown() throws Exception { try { updateSettings(defaultGoOnTheFly); CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance(); codeInsightSettings.ADD_MEMBER_IMPORTS_ON_THE_FLY = defaultJavaMemberOnTheFly; codeInsightSettings.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = defaultJavaOnTheFly; } finally { //noinspection ThrowFromFinallyBlock super.tearDown(); } } private void doTestAddOnTheFly(boolean goOnTheFlyEnabled) { DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true); updateSettings(goOnTheFlyEnabled); String initial = "package a; func a() {\n fmt.Println() \n}"; myFixture.configureByText("a.go", initial); myFixture.doHighlighting(); myFixture.doHighlighting(); String after = "package a;\n\nimport \"fmt\"\n\nfunc a() {\n fmt.Println() \n}"; String result = goOnTheFlyEnabled ? after : initial; myFixture.checkResult(result); } public void testUndo() { DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(true); updateSettings(true); myFixture.configureByText("a.go", "package main\n\nfunc main() { }"); myFixture.type("fmt."); myFixture.doHighlighting(); myFixture.doHighlighting(); myFixture.checkResult("package main\n\nimport \"fmt\"\n\nfunc main() { fmt. }"); FileEditor editor = FileEditorManager.getInstance(myFixture.getProject()).getSelectedEditor(myFixture.getFile().getVirtualFile()); UndoManager.getInstance(myFixture.getProject()).undo(editor); myFixture.checkResult("package main\n\nfunc main() { }"); } public void testOnTheFlyEnabled() { doTestAddOnTheFly(true); } public void testOnTheFlyDisabled() { doTestAddOnTheFly(false); } private void doTestImportOwnPath(String text, String testText, boolean shouldImport) { updateSettings(false); myFixture.addFileToProject(FileUtil.join("pack", "a.go"), text); PsiFile testFile = myFixture.addFileToProject(FileUtil.join("pack", "a_test.go"), testText); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); List actions = myFixture.filterAvailableIntentions("Import " + "pack" + "?"); assertTrue(shouldImport != actions.isEmpty()); } public void testOwnAddPathFromTest() { doTestImportOwnPath("package myPack; func Func() {}", "package myPack_test; func TestFunc() { myPack.Func() }", true); } public void testDoNotImportOwnPathFromDifferentPackage() { doTestImportOwnPath("package pack1; func Func() {}", "package pack2_test; func TestFunc() { pack1.Func() }", false); } public void testCompleteDifferentPackageFromTest() { myFixture.configureByText("a.go", "package foo; func a() { fmt.Print }"); assertNotEmpty(myFixture.getLookupElementStrings()); } public void testImportVendoringPackage() { myFixture.addFileToProject("vendor/a/b/c.go", "package b"); myFixture.configureByText("a.go", "package a; func a() { b.Println() }"); myFixture.launchAction(myFixture.findSingleIntention("Import a/b?")); myFixture.checkResult("package a;\n\nimport \"a/b\"\n\nfunc a() { b.Println() }"); } public void testImportVendoringPackageWithDisabledVendoring() { disableVendoring(); myFixture.addFileToProject("vendor/a/b/c.go", "package b"); myFixture.configureByText("a.go", "package a; func a() { b.Println() }"); myFixture.launchAction(myFixture.findSingleIntention("Import vendor/a/b?")); myFixture.checkResult("package a;\n\nimport \"vendor/a/b\"\n\nfunc a() { b.Println() }"); } public void testImportBuiltinPackage() { myFixture.configureByText("a.go", "package a; func a() { builtin.Println() }"); assertEmpty(myFixture.filterAvailableIntentions("Import builtin?")); } public void testImportSdkTestData() { myFixture.configureByText("a.go", "package a; func _() { println(pkg.ExportedConstant) } "); assertEmpty(myFixture.filterAvailableIntentions("Import doc/testdata?")); } public void testImportVendoredBuiltinPackage() { myFixture.addFileToProject("vendor/builtin/builtin.go", "package builtin"); myFixture.configureByText("a.go", "package a; func a() { builtin.Println() }"); myFixture.launchAction(myFixture.findSingleIntention("Import builtin?")); myFixture.checkResult("package a;\n\nimport \"builtin\"\n\nfunc a() { builtin.Println() }"); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoBracesUnwrapperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoBracesUnwrapperTest extends GoUnwrapTestCase { public void testNoActionFor() { assertOptions("for { \n}", "Unwrap for"); } public void testNoActionIf() { assertOptions("if true { \n}", "Unwrap if"); } public void testVoidBraces() { assertUnwrapped("{ \n}", "\n"); } public void testBracesWithOneStatement() { assertUnwrapped( "{ \n" + "var i int\n" + "}", "var i int\n" ); } public void testBracesWithThreeStatements() { assertUnwrapped( "{ \n" + "var i int\n" + "i = 2\n" + "i++\n" + "}", "var i int\n" + "i = 2\n" + "i++\n" ); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoElseRemoverTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoElseRemoverTest extends GoUnwrapTestCase { public void testNoAction() { assertUnwrapped( "if true { \n" + "}", "if true { \n" + "}" ); } public void testVoidElse() { assertUnwrapped("if true { } else { }", "if true { }"); } public void testVoidElseWithCaretReturn() { assertUnwrapped("if true {\n } else { \n}\n", "if true {\n }\n"); } public void testElse() { assertUnwrapped("if true {\n } else { \n var i int \n }\n", "if true {\n }\n"); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoElseUnwrapperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoElseUnwrapperTest extends GoUnwrapTestCase { public void testNoAction() { assertUnwrapped("if true { \n}", "if true { \n}", 1); } public void testVoidElse() { assertUnwrapped("if true {\n } else { \n}\n", "if true {\n }\n", 1); } public void testElse() { assertUnwrapped("if true {\n } else { \n var i int \n }\n", "if true {\n }\nvar i int\n", 1); } public void testElseWithTwoStatements() { assertUnwrapped("if true {\n } else { \nvar i int\n i = 23\n }\n", "if true {\n }\nvar i int\ni = 23\n", 1); } public void testElseIf() { assertUnwrapped("if true {\n } else if { \nvar i int\n i = 23\n }\n", "if true {\n }\nif {\n\tvar i int\n\ti = 23\n}\n", 1); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoForUnwrapperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoForUnwrapperTest extends GoUnwrapTestCase { public void testVoidFor() { assertUnwrapped("for { \n}", "\n"); } public void testForWithOneStatement() { assertUnwrapped( "for { \n" + "var i int\n" + "}", "var i int\n"); } public void testForWithThreeStatements() { assertUnwrapped( "for { \n" + "var a, b int\n" + "a = 2\n" + "b = 3\n" + "}", "var a, b int\n" + "a = 2\n" + "b = 3\n" ); } public void testForWithForClause() { assertUnwrapped( "for i := 1; i < 10; i++ { \n" + "var a int\n" + "a = i\n" + "}", "i := 1\n" + "var a int\n" + "a = i\n" ); } public void testForWithRangeClause() { assertUnwrapped( "for i := range \"asd\" { \n" + "var a string\n" + "a = i\n" + "}", "var a string\n" + "a = i\n" ); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoFunctionArgumentUnwrapperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoFunctionArgumentUnwrapperTest extends GoUnwrapTestCase { public void testNoAction() { assertUnwrapped("asd()", "asd()"); } public void testOneArg() { assertUnwrapped("asd(3)", "3"); } public void testThreeArgs() { assertUnwrapped("asd(f(), 3, f())", "f()"); } public void testInsertedCalls() { assertUnwrapped("f1(f2(4))", "f1(4)", 0); } public void testInsertedCallsUseSecodAction() { assertUnwrapped("f1(f2(4))", "f2(4)", 1); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoIfUnwrapperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; public class GoIfUnwrapperTest extends GoUnwrapTestCase { public void testNoAction() { assertUnwrapped( "if true { \n" + "} ", "if true { \n" + "} " ); } public void testVoidIf() { assertUnwrapped( "if true { \n" + "} else { }\n", "\n" ); } public void testIfWithOneStatement() { assertUnwrapped( "if true { \n" + "var i int\n" + "} else { }", "var i int" ); } public void testIfThreeStatements() { assertUnwrapped( "if true { \n" + "var a, b int\n" + "a = 2\n" + "b = 3\n" + "} else { }", "var a, b int\n" + "a = 2\n" + "b = 3\n" ); } public void testInsertedIndents() { assertUnwrapped( "if true { \n" + "\tif {\n" + "\t\tvar i int\n" + "\t}\n" + "}", "if {\n" + "\tvar i int\n" + "}\n" ); } } ================================================ FILE: tests/com/goide/codeInsight/unwrap/GoUnwrapTestCase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.codeInsight.unwrap; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.codeInsight.unwrap.UnwrapHandler; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.stream.Collectors; public abstract class GoUnwrapTestCase extends GoCodeInsightFixtureTestCase { protected void assertUnwrapped(@NotNull String codeBefore, @NotNull String codeAfter) { assertUnwrapped(codeBefore, codeAfter, 0); } protected void assertUnwrapped(@NotNull String codeBefore, @NotNull String codeAfter, int option) { myFixture.configureByText("a.go", normalizeCode(codeBefore)); UnwrapHandler h = new UnwrapHandler() { @Override protected void selectOption(List options, Editor editor, PsiFile file) { if (options.isEmpty()) return; options.get(option).actionPerformed(null); } }; h.invoke(getProject(), myFixture.getEditor(), myFixture.getFile()); myFixture.checkResult(normalizeCode(codeAfter)); } protected void assertOptions(@NotNull String code, String... expectedOptions) { myFixture.configureByText("a.go", normalizeCode(code)); List actualOptions = ContainerUtil.newArrayList(); UnwrapHandler h = new UnwrapHandler() { @Override protected void selectOption(List options, Editor editor, PsiFile file) { actualOptions.addAll(options.stream().map(each -> each.getTemplatePresentation().getText()).collect(Collectors.toList())); } }; h.invoke(getProject(), myFixture.getEditor(), myFixture.getFile()); assertOrderedEquals(actualOptions, expectedOptions); } } ================================================ FILE: tests/com/goide/completion/GoCompletionSdkAwareTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.SdkAware; import com.goide.sdk.GoSdkService; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.psi.PsiFile; import java.io.IOException; import java.util.List; @SdkAware public class GoCompletionSdkAwareTest extends GoCompletionTestBase { public void testFormatter() { doTestInclude("package main; import . \"fmt\"; type alias ", "Formatter"); } public void testDoNotCompleteBuiltinFunctions() { doCheckResult("package main; var a = fals", "package main; var a = false"); } public void testCamelHumpTypeCompletion() { doCheckResult("package main;\n" + "func test(){io.reWSC}", "package main;\n\n" + "import \"idea_io\"\n\n" + "func test(){idea_io.ReadWriteSeekerCustom()}", Lookup.NORMAL_SELECT_CHAR); } public void testCamelHumpFunctionCompletion() { doCheckResult("package main;\n" + "func test(){io.reALC}", "package main;\n\n" + "import \"idea_io\"\n\n" + "func test(){idea_io.ReadAtLeastCustom()}", Lookup.NORMAL_SELECT_CHAR); } public void testTypeAutoImport() { doCheckResult("package main; \n" + "func test(){Templat}", "package main;\n\n" + "import \"text/template\"\n\n" + "func test(){template.Template{}}", "template.Template"); } public void testTypeAutoImportOnQualifiedName() { doCheckResult("package main; \n" + "func test(){template.Templat}", "package main;\n\n" + "import \"text/template\"\n\n" + "func test(){template.Template{}}"); } public void testFunctionAutoImport() { doCheckResult("package main; \n" + "func test(){Fprintl}", "package main;\n\n" + "import \"fmt\"\n\n" + "func test(){fmt.Fprintln()}", "fmt.Fprintln"); } public void testVariableAutoImport() { doCheckResult("package main; \n" + "func test(){ErrNotSuppor}", "package main;\n\n" + "import \"net/http\"\n\n" + "func test(){http.ErrNotSupported}", "http.ErrNotSupported"); } public void testConstantAutoImport() { doCheckResult("package main; \n" + "func test(){O_RDO}", "package main;\n\n" + "import \"os\"\n\n" + "func test(){os.O_RDONLY}"); } public void testDuplicateAutoImport() { doCheckResult("package main; \n" + "func test(){Fprintl}", "package main;\n\n" + "import \"fmt\"\n\n" + "func test(){fmt.Fprintln()}", "fmt.Fprintln"); myFixture.type(");Fprintl"); myFixture.completeBasic(); selectLookupItem("fmt.Fprintln"); myFixture.checkResult("package main;\n\n" + "import \"fmt\"\n\n" + "func test(){fmt.Fprintln();fmt.Fprintln()}"); } public void testForceAutoImportBlankImports() { doCheckResult("package main; \n" + "import _ \"fmt\"\n" + "func test(){Fprintl}", "package main;\n\n" + "import (\n" + "\t_ \"fmt\"\n" + "\t\"fmt\"\n" + ")\n" + "func test(){fmt.Fprintln()}", "fmt.Fprintln"); } public void testAutoImportWithAlias() { doCheckResult("package main; \n" + "import alias `fmt`\n" + "func test(){Fprintl}", "package main; \n" + "import alias `fmt`\n" + "func test(){alias.Fprintln()}", "alias.Fprintln"); } public void testAutoImportWithDotAlias() { doCheckResult("package main; \n" + "import . `fmt`\n" + "func test(){Fprintl}", "package main; \n" + "import . `fmt`\n" + "func test(){Fprintln()}"); } public void testUseImportPathInsteadOfPackageNameForAutoImport() { doCheckResult("package main\n" + "\n" + "import (\n" + " \"fmt\"\n" + ")\n" + "\n" + "func main() {\n" + " fmt.Printf(FunctionInPackageThatDoesNotMatchDirectory);\n" + "}", "package main\n" + "\n" + "import (\n" + " \"fmt\"\n" + "\t\"dirName\"\n" + ")\n" + "\n" + "func main() {\n" + " fmt.Printf(otherPackage.FunctionInPackageThatDoesNotMatchDirectoryName());\n" + "}", "otherPackage.FunctionInPackageThatDoesNotMatchDirectoryName"); } public void testUsePackageNameInsteadOfImportPathIfPackageIsImported() { doCheckResult("package main\n" + "\n" + "import (\n" + " \"fmt\"\n" + " \"dirName\"\n" + ")\n" + "\n" + "func main() {\n" + " fmt.Printf(FunctionInPackageThatDoesNotMatchDirectory);\n" + "}", "package main\n" + "\n" + "import (\n" + " \"fmt\"\n" + " \"dirName\"\n" + ")\n" + "\n" + "func main() {\n" + " fmt.Printf(otherPackage.FunctionInPackageThatDoesNotMatchDirectoryName());\n" + "}", "otherPackage.FunctionInPackageThatDoesNotMatchDirectoryName"); } public void testDoNotImportLocallyImportedPackage() throws IOException { myFixture.addFileToProject("imported/imported.go", "package imported\n" + "func LocallyImported() {}"); doCheckResult("package main; \n" + "import `./imported`\n" + "func test(){LocallyImport}", "package main; \n" + "import `./imported`\n" + "func test(){imported.LocallyImported()}", "imported.LocallyImported"); } public void testImportedFunctionsPriority() { myFixture.configureByText("a.go", "package main; \n" + "import `io`\n" + "func test(){ReadA}"); failOnFileLoading(); myFixture.completeBasic(); myFixture.assertPreferredCompletionItems(0, "io.ReadAtLeast", "io.ReaderAt", "idea_io.ReadAtLeastCustom", "idea_io.ReaderAtCustom"); } public void testImportedTypesPriority() { myFixture.configureByText("a.go", "package main; \n" + "import `io`\n" + "func test(ReadWriteSeeke){}"); failOnFileLoading(); myFixture.completeBasic(); myFixture.assertPreferredCompletionItems(0, "io.ReadWriteSeeker", "idea_io.ReadWriteSeekerCustom"); } public void testDoNothingInsideSelector() { doTestVariants( "package main\n" + "import \"fmt\"\n" + "func test(){fmt.Sprintln().}", CompletionType.BASIC, 1, CheckType.EQUALS ); } public void testDoNotRunAutoImportCompletionAfterDot() { doTestCompletion(); } public void testDoNotRunAutoImportFunctionCompletionAfterUnaryAmpersand() { doCheckResult("package main;\n" + "func test(){println(&io.reALC)}", "package main;\n" + "func test(){println(&io.reALC\n" + "\t)}", Lookup.NORMAL_SELECT_CHAR); assertNull(myFixture.getLookup()); } public void testDoNotRunAutoImportCompletionAfterDotAndSpace() { doTestCompletion(); assertNull(myFixture.getLookup()); } public void testImports() { doTestInclude("package main; import \"", "fmt", "io"); } public void testCaseInsensitiveTypeConversion() { doCheckResult("package main; import \"fmt\"; func test(){fmt.form}", "package main; import \"fmt\"; func test(){fmt.Formatter()}"); } public void testCaseInsensitiveFunction() { doCheckResult("package main; import \"fmt\"; func test(){fmt.err}", "package main; import \"fmt\"; func test(){fmt.Errorf()}"); } public void testCaseInsensitiveType() { doCheckResult("package main; import \"fmt\"; func test(fmt.form}", "package main; import \"fmt\"; func test(fmt.Formatter}"); } public void testPrintlnBuiltin() { doTestInclude("package main; func test(){pr}", "print", "println"); } public void testNothingUnrelatedInsideSelector() { doTestEquals("package foo; type E struct {}; type B struct {E}; func (e E) foo() {}; func boo() {}" + "func main() {B{}.E..foo()}", "foo"); } public void testCompleteWithUnfinishedPackage() { doCheckResult("package main\n" + "func main() {\n" + " f.fprintl\n" + "}", "package main\n\n" + "import \"fmt\"\n\n" + "func main() {\n" + " fmt.Fprintln()\n" + "}"); } public void testDoNotCompleteTestFunctions() throws IOException { myFixture.addFileToProject("pack/pack_test.go", "package pack; func TestFoo() {}"); myFixture.configureByText("my_test.go", "package a; func main() { _ = TestF"); myFixture.completeBasic(); assertNull(myFixture.getLookup()); myFixture.checkResult("package a; func main() { _ = TestF"); } public void testDoNotCompleteBenchmarkFunctions() throws IOException { myFixture.addFileToProject("pack/pack_test.go", "package pack; func BenchmarkFoo() {}"); myFixture.configureByText("my_test.go", "package a; func main() { _ = BenchmarkF"); myFixture.completeBasic(); assertNull(myFixture.getLookup()); myFixture.checkResult("package a; func main() { _ = BenchmarkF"); } public void testDoNotCompleteExampleFunctions() throws IOException { myFixture.addFileToProject("pack/pack_test.go", "package pack; func ExampleFoo() {}"); myFixture.configureByText("my_test.go", "package a; func main() { _ = ExampleF"); assertNull(myFixture.getLookup()); myFixture.completeBasic(); } public void testCompleteTestBenchmarkExamplesFromNonTestFiles() throws IOException { myFixture.addFileToProject("pack/pack.go", "package pack; func TestFoo() {} func BenchmarkFoo() {} func ExampleFoo() {}"); myFixture.configureByText("my_test.go", "package a; func main() { _ = Foo"); myFixture.completeBasic(); //noinspection ConstantConditions assertContainsElements(myFixture.getLookupElementStrings(), "pack.TestFoo", "pack.BenchmarkFoo", "pack.ExampleFoo"); } public void testDoNotAutoImportWithTheSameImportPath() throws IOException { myFixture.addFileToProject("pack1/file2.go", "package pack1; func MyFunctionFromSamePath() {}"); myFixture.addFileToProject("pack2/file2.go", "package pack1; func MyFunctionFromOtherPath() {}"); PsiFile file = myFixture.addFileToProject("pack1/file1.go", "package pack1; func test() { pack1.MyFunc }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.completeBasic(); myFixture.checkResult("package pack1;\n\nimport \"pack2\"\n\nfunc test() { pack1.MyFunctionFromOtherPath() }"); } public void testAutoImportOwnImportPathFromTest() throws IOException { myFixture.addFileToProject("pack/a.go", "package myPack; func Func() {}"); PsiFile testFile = myFixture.addFileToProject("pack/a_test.go", "package myPack_test; func TestFunc() { myPack.Fun }"); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); myFixture.completeBasic(); myFixture.checkResult("package myPack_test;\n\nimport \"pack\"\n\nfunc TestFunc() { myPack.Func() }"); } public void testDoNotAutoImportDifferentPackageInSamePathFromTest() throws IOException { String text = "package foo_test; func TestFunc() { bar.Fun }"; myFixture.addFileToProject("pack/a.go", "package bar; func Func() {}"); PsiFile file = myFixture.addFileToProject("pack/a_test.go", text); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.completeBasic(); assertNull(myFixture.getLookup()); myFixture.checkResult(text); } public void testImportOwnPathFromTestFile() throws IOException { PsiFile testFile = myFixture.addFileToProject("fuzz/fuzy_test.go", "package fuzy_test; import \"\""); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); myFixture.completeBasic(); //noinspection ConstantConditions assertContainsElements(myFixture.getLookupElementStrings(), "fuzz"); } public void testDoNotImportOwnPathFromNonTestPackage() throws IOException { PsiFile testFile = myFixture.addFileToProject("fuzz/fuzy_test.go", "package fuzy; import \"\""); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); myFixture.completeBasic(); List strings = myFixture.getLookupElementStrings(); assertTrue(strings != null && !strings.contains("fuzz")); } public void testDoNotCompleteBuiltinImport() { doCheckResult("package a; import \"built\"", "package a; import \"built\""); assertNull(myFixture.getLookup()); } public void testCompleteVendoredBuiltinImport() { myFixture.addFileToProject("vendor/builtin/builtin.go", "package builtin; func Hello() {}"); doCheckResult("package a; import \"built\"", "package a; import \"builtin\""); } public void testAutoImportVendorPackage() { myFixture.addFileToProject("vendor/vendorPackage/foo.go", "package vendorPackage; func Bar() {}"); doCheckResult("package src; func _() { ven.Ba }", "package src;\n" + "\n" + "import \"vendorPackage\"\n" + "\n" + "func _() { vendorPackage.Bar() }"); } public void testAutoImportVendorPackageWithDisabledVendoring() { disableVendoring(); myFixture.addFileToProject("vendor/vendorPackage/foo.go", "package vendorPackage; func Bar() {}"); doCheckResult("package src; func _() { ven.Ba }", "package src;\n" + "\n" + "import \"vendor/vendorPackage\"\n" + "\n" + "func _() { vendorPackage.Bar() }"); } public void testDoNotCompleteSymbolsFromUnreachableVendoredPackages() { myFixture.addFileToProject("vendor/foo/foo.go", "package foo; func VendoredFunction() {}"); myFixture.addFileToProject("vendor/foo/vendor/bar/bar.go", "package bar; func VendoredFunction() {}"); myFixture.configureByText("a.go", "package src; func _() { VendorF }"); myFixture.completeBasic(); //noinspection ConstantConditions assertSameElements(myFixture.getLookupElementStrings(), "foo.VendoredFunction"); } public void testDoNotCompleteSymbolsFromShadowedPackages() { myFixture.addFileToProject("foo/foo.go", "package foo; func ShadowedFunction() {}"); myFixture.addFileToProject("vendor/foo/foo.go", "package bar; func ShadowedFunction() {}"); myFixture.configureByText("a.go", "package src; func _() { ShadowF }"); myFixture.completeBasic(); //noinspection ConstantConditions assertSameElements(myFixture.getLookupElementStrings(), "bar.ShadowedFunction"); } public void testDoNotCompleteSymbolsFromShadowedVendoredPackages() { myFixture.addFileToProject("vendor/foo/foo.go", "package bar; func ShadowedFunction() {}"); myFixture.addFileToProject("vendor/foo/vendor/foo/foo.go", "package bar; func ShadowedFunction() {}"); PsiFile file = myFixture.addFileToProject("vendor/foo/main.go", "package foo; func _() { ShadowF }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.completeBasic(); //noinspection ConstantConditions assertSameElements(myFixture.getLookupElementStrings(), "bar.ShadowedFunction"); } public void testDoNotCompletePackagesShadowedBySdkDirectories() { myFixture.addFileToProject("fmt/subdir/fmt.go", "package subdir; func Println() {}"); myFixture.addFileToProject("fmt/fmt.go", "package shadowed; func Println() {}"); myFixture.configureByText("a.go", "package src; import `fmt`"); myFixture.completeBasic(); //noinspection ConstantConditions assertSameElements(myFixture.getLookupElementStrings(), "fmt", "fmt/subdir"); } public void testDoNotCompleteFunctionsFromPackagesShadowedBySdkDirectories() { myFixture.addFileToProject("fmt/subdir/fmt.go", "package subdir; func Println() {}"); myFixture.addFileToProject("fmt/fmt.go", "package shadowed; func Println() {}"); myFixture.configureByText("a.go", "package src; func _() { Printl }"); myFixture.completeBasic(); List elementStrings = myFixture.getLookupElementStrings(); assertNotNull(elementStrings); assertContainsElements(elementStrings, "subdir.Println"); assertDoesntContain(elementStrings, "shadowed.Println"); } public void testCompleteInternalPackageOn1_2_SDK() { myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); myFixture.configureByText("a.go", "package a; import `inte`"); myFixture.completeBasic(); List elementStrings = myFixture.getLookupElementStrings(); assertNotNull(elementStrings); assertContainsElements(elementStrings, "internal", "sub/internal", "net/internal"); } public void testCompleteInternalPackageOn1_4_SDK() { GoSdkService.setTestingSdkVersion("1.4", getTestRootDisposable()); myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); myFixture.configureByText("a.go", "package a; import `inte`"); myFixture.completeBasic(); List elementStrings = myFixture.getLookupElementStrings(); assertNotNull(elementStrings); assertContainsElements(elementStrings, "internal", "sub/internal"); assertDoesntContain(elementStrings, "net/internal"); } public void testCompleteInternalPackageOn1_5_SDK() { GoSdkService.setTestingSdkVersion("1.5", getTestRootDisposable()); myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); doCheckResult("package a; import `inte`", "package a; import `internal`"); } public void testIntArray() { doTestInclude("package a; var x = []", "int"); } public void testMapIntInt() { doTestInclude("package a; var x = map[int]", "int"); } public void testStruct() { doTestInclude("package a; var x = ", "struct"); } } ================================================ FILE: tests/com/goide/completion/GoCompletionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementPresentation; import com.intellij.psi.PsiFile; import com.intellij.testFramework.TreePrintCondition; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import java.util.List; public class GoCompletionTest extends GoCompletionTestBase { public void testPackageWithoutAlias() { doTestInclude("package foo; import `fmt`; func main(){}", "fmt"); } public void testLocalFunction() { doTestInclude("package foo; func foo() {}; func main() {}", "foo", "main"); } public void testLocalType() { doTestInclude("package foo; type (T struct {}; T2 struct{}); func main(){var i }", "T", "T2"); } public void testLocalFunctionInDifferentFiles() { myFixture.copyFileToProject(getTestName(true) + "_context.go", "importPath/context.go"); myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject(getTestName(true) + ".go", "importPath/main.go")); myFixture.completeBasic(); myFixture.checkResultByFile(getTestName(true) + "_after.go"); } public void testImportVendoringPackages() { myFixture.addFileToProject("vendor/pack1/pack2/test.go", "package foo"); doCheckResult("package foo; import `pa`", "package foo; import `pack1/pack2`"); } public void testImportVendoringPackagesWithDisabledVendoring() { disableVendoring(); myFixture.addFileToProject("vendor/pack1/pack2/test.go", "package foo"); doCheckResult("package foo; import `pa`", "package foo; import `vendor/pack1/pack2`", Lookup.NORMAL_SELECT_CHAR); } public void testImportPackages() { myFixture.addFileToProject("package1/pack/test.go", "package foo"); myFixture.addFileToProject("package2/pack/test.go", "package bar"); myFixture.configureByText("test.go", "package foo; import `pack`"); myFixture.completeBasic(); List lookupElementStrings = myFixture.getLookupElementStrings(); assertNotNull(lookupElementStrings); assertSameElements(lookupElementStrings, "package1/pack", "package2/pack"); } public void testImportPackagesWithoutClosingQuote() { myFixture.addFileToProject("package1/pack/test.go", "package foo"); myFixture.addFileToProject("package2/pack/test.go", "package bar"); myFixture.configureByText("test.go", "package foo; import `pack"); myFixture.completeBasic(); List lookupElementStrings = myFixture.getLookupElementStrings(); assertNotNull(lookupElementStrings); assertSameElements(lookupElementStrings, "package1/pack", "package2/pack"); } public void testImportRelativePackages() { myFixture.addFileToProject("package1/pack/test.go", "package foo"); myFixture.addFileToProject("package2/pack/test.go", "package bar"); myFixture.configureByText("test.go", "package foo; import `./pack`"); myFixture.completeBasic(); List lookupElementStrings = myFixture.getLookupElementStrings(); assertNotNull(lookupElementStrings); assertSameElements(lookupElementStrings, "package1", "package2"); } public void testDoNotCompleteFullPackagesForRelativeImports() { myFixture.addFileToProject("package1/pack/test.go", "package foo"); myFixture.addFileToProject("package2/pack/test.go", "package bar"); myFixture.configureByText("test.go", "package foo; import `./pack`"); myFixture.completeBasic(); List lookupElementStrings = myFixture.getLookupElementStrings(); assertNotNull(lookupElementStrings); assertSameElements(lookupElementStrings, "package1", "package2"); } public void testDoNotCompleteOwnImportPath() { myFixture.addFileToProject("package/long/long/path/test.go", "package pack"); PsiFile testFile = myFixture.addFileToProject("package/very/long/path/but/same/package/test.go", "package pack; import `package/`"); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); myFixture.completeBasic(); myFixture.checkResult("package pack; import `package/long/long/path`"); } public void testImportsPriority() { myFixture.addFileToProject("package/long/but/similar/path/test.go", "package pack"); myFixture.addFileToProject("package/very/long/path/test.go", "package pack"); myFixture.addFileToProject("package/middle/path/test.go", "package pack"); myFixture.addFileToProject("package/short/test.go", "package pack"); PsiFile testFile = myFixture.addFileToProject("package/long/but/similar/test.go", "package pack; import `package/`"); myFixture.configureFromExistingVirtualFile(testFile.getVirtualFile()); myFixture.completeBasic(); myFixture.assertPreferredCompletionItems(0, "package/long/but/similar/path", "package/short", "package/middle/path", "package/very/long/path"); } public void testDoNotHidePopupOnSlash() { myFixture.addFileToProject("package1/pack/test.go", "package foo"); myFixture.addFileToProject("package2/pack/test.go", "package bar"); myFixture.configureByText("test.go", "package foo; import ``"); myFixture.completeBasic(); myFixture.type("package1/\n"); myFixture.checkResult("package foo; import `package1/pack`"); } public void testLocalVar() { doTestInclude("package foo; func main(){var i, j int; }", "i", "j"); } public void testPackageLocalVar() { doTestInclude("package foo; var i, j int; func main(){}", "i", "j"); } public void testLocalVarExclude() { doTestExclude("package foo; func main(){{var i, j int;}; }", "i", "j"); } public void testParams() { doTestInclude("package foo; func main(i, j int){}", "i", "j"); } public void testConsts() { doTestInclude("package foo; const i, j; func main(){}", "i", "j"); } public void testNoCompletionInsideStrings() { doTestEquals("package foo; func main(){\"\"}"); } public void testNoKeywordCompletionInsideTypeDeclarationList() { doTestEquals("package foo; type (\n\t\n)"); } public void testNoKeywordCompletionInsideConstDeclarationList() { doTestEquals("package foo; const (\n\t\n)"); } public void testNoKeywordCompletionInsideVarDeclarationList() { doTestEquals("package foo; var (\n\t\n)"); } public void testKeywordCompletionInsideVarDeclarationListAfterEquals() { doTestInclude("package foo; var (\n\ta = \n)", "map", "func", "struct"); } public void testNoCompletionInsideComments() { doTestEquals("package foo; func main(){/**/}"); } public void testStructTypes() { doTestEquals("package foo; type AA struct {N AA}; func foo(a AA) {a.}", "N"); } public void testStructTypes2() { doTestEquals("package foo; type AA struct {N AA}; func foo(a *AA) {a.}", "N"); } public void testStructKeyword() { doCheckResult("package main; func main() { d := struct { name str }; _ = d }", "package main; func main() { d := struct { name struct{} }; _ = d }"); } public void testStructKeyword2() { doTestInclude("package main; func main() { d := struct { name }; _ = d }", "struct"); } public void testStructKeyword3() { doCheckResult("package main; func main() { d := str; _ = d }", "package main; func main() { d := struct {\n" + "\t\n" + "}{}; _ = d }"); } public void testImports() { doCheckResult("package foo; import imp \"\"; func foo(a im) {}", "package foo; import imp \"\"; func foo(a imp.) {}"); } public void testImportsForRefs() { doCheckResult("package foo; import imp \"\"; func foo() {im.foo}", "package foo; import imp \"\"; func foo() {imp.foo}"); } public void testCompleteFieldWithoutColon() { doCheckResult("package main;func main(){a:=struct{Demo int}{Demo:1};println(a.D)}", "package main;func main(){a:=struct{Demo int}{Demo:1};println(a.Demo)}"); } public void testCompleteFieldWithoutColonAfterKey() { doCheckResult("package main; type Test struct { ID string }; func t() { var n Test; _ = &Test{ID: n.I} }", "package main; type Test struct { ID string }; func t() { var n Test; _ = &Test{ID: n.ID} }"); } public void testTopLevelKeywords() { myFixture.testCompletionVariants(getTestName(true) + ".go", "const", "func", "import", "type", "var"); } public void testTopLevelKeywords_2() { myFixture.testCompletionVariants(getTestName(true) + ".go", "const", "func", "type", "var"); } public void testBlockKeywords() { myFixture.testCompletionVariants(getTestName(true) + ".go", "for", "const", "var", "return", "if", "switch", "go", "defer", "select", "fallthrough", "goto", "main", "struct", "map", "type"); } public void testBlockKeywordsInsideOneLineFunction() { myFixture.testCompletionVariants(getTestName(true) + ".go", "for", "const", "var", "return", "if", "switch", "go", "defer", "select", "fallthrough", "goto", "main", "struct", "map", "type"); } public void testBlockKeywordsInsideCaseStatement() { myFixture.testCompletionVariants(getTestName(true) + ".go", "break", "for", "const", "var", "return", "if", "switch", "go", "defer", "select", "fallthrough", "goto", "main", "struct", "map", "case", "default", "type"); } public void testAddSpaceAfterKeyword() { doTestCompletion(); } public void testTypeKeywords() { myFixture.testCompletionVariants(getTestName(true) + ".go", "struct", "interface", "chan", "map"); } public void testExpressionKeywords() { myFixture.testCompletionVariants(getTestName(true) + ".go", "struct", "map", "main", "func"); } public void testTypeKeywordsInsideParentheses() { myFixture.testCompletionVariants(getTestName(true) + ".go", "chan", "map", "interface", "struct"); } public void testSelectKeywordInsertHandler() { doTestCompletion(); } public void testTypeKeywordInsertBraces() { doTestCompletion(); } public void testTypeKeywordDoNotInsertBraces() { doTestCompletion(); } public void testInterfaceKeywordAsFunctionParameter() { doTestCompletion(); } public void testStructKeywordAsFunctionParameter() { doTestCompletion(); } public void testForStatementKeywords() { myFixture.testCompletionVariants(getTestName(true) + ".go", "bar", "break", "const", "continue", "defer", "for", "go", "if", "return", "fallthrough", "goto", "select", "switch", "var", "struct", "map", "type"); } public void testForStatementKeywordsInsideFuncLit() { myFixture.testCompletionVariants(getTestName(true) + ".go", "bar", "const", "defer", "for", "go", "if", "return", "fallthrough", "goto", "select", "switch", "var", "struct", "map", "type"); } public void testDoNotCompleteKeywordsInsideConstSpec() { myFixture.testCompletionVariants(getTestName(true) + ".go", "a"); } public void testDoNotCompleteKeywordsInsideSelectorExpression() { myFixture.testCompletionVariants(getTestName(true) + ".go", "FuncA", "FuncB"); } public void testRangeKeyword_1() { doTestCompletion(); } public void testRangeKeyword_2() { doTestCompletion(); } public void testRangeKeyword_3() { doTestCompletion(); } public void testChanKeyword() { doTestCompletion(); } public void testChanKeyword_2() { doTestCompletion(); } public void testChanKeyword_3() { doTestCompletion(); } public void testMapKeyword() { doTestCompletion(); } public void testMapKeyword_2() { doTestCompletion(); } public void testMapKeywordInsertHandler() { doTestCompletion(); } public void testMapKeywordInsertHandlerDoNotInsertBrackets() { doTestCompletion(); } public void testElseKeyword() { doTestCompletion(); } public void testElseKeywordRegression() { doTestEmptyCompletion(); } public void testIfKeywordAfterElse() { doTestCompletion(); } public void testForStatementKeywordsDoNotInsertSpace() { doTestCompletion(); } public void testFunctionInDefer() { doTestCompletion(); } public void testFunctionAsFunctionArgument() { doTestCompletion(); } public void testFunctionAsVariableValue() { doTestCompletion(); } public void testFunctionInGo() { doTestCompletion(); } public void testPackageKeyword() { doTestCompletion(); } public void testPackageKeywordInEmptyFile() { doTestCompletion(); } public void testExpressionCaseKeywordCompletion() { doTestCompletion(); } public void testExpressionDefaultKeywordCompletion() { doTestCompletion(); } public void testTypeCaseKeywordCompletion() { doTestCompletion(); } public void testTypeDefaultKeywordCompletion() { doTestCompletion(); } public void testMethods() { doTestEquals("package foo; type T interface{}; func (t T) f() {t.}", "f"); } public void testPreventStackOverflow() { doTestEquals("package foo; type E struct {*E}; func (e E) foo() {}; func main() {e := E{}; e.}", "foo", "E"); } public void testNestedStructures() { doTestEquals("package foo; type E struct {}; type B struct {E}; func (e E) foo() {}; func (b B) bar(){}" + "func main() {b := B{}; b.}", "foo", "bar", "E"); } public void testNestedStructures2() { doTestEquals("package foo; type E struct {}; type B struct {E}; func (e E) foo() {}; " + "func main() {b := B{}; b.E.}", "foo"); } public void testNestedStructures3() { doTestEquals("package foo; type E struct {}; type B struct {E}; func (e E) foo() {}; " + "func main() {B{}.E.}", "foo"); } public void testInterfaceTypes() { doTestInclude("package foo; type E interface {}; type B interface {}", "E"); } public void testReceiverCompletion() { doTestInclude("package foo; type E interface {}; func (e ", "E"); } public void testInterfaceTypesNoStruct() { doTestExclude("package foo; type E struct {}; type B interface {}", "E"); } public void testOnlyTypesInParameters() { doTestExclude("package foo; const a int = 1; var b = 2; func main() {}", "a", "b", "main"); } public void testInnerTypes() { doTestInclude("package foo; func foo() {type innerType struct {}; var i }", "innerType"); } public void testChannelType() { doTestInclude("package foo; func foo() {type T struct {cn *T}; var i T; i.}", "cn"); } public void testInterfaceType() { doTestInclude("package foo; func foo(i interface {Boo() int}) {i.}", "Boo"); } public void testInterfaceType2() { doTestInclude("package foo; type I interface {Boo() int}; func foo(i I) {i.}", "Boo"); } public void testLabel() { doTestInclude("package foo; func main() { goto ; Label1: 1}", "Label1"); } public void testNoKeywordsInReceiver() { doTestExclude("package foo; func (a ) main() { }", "map", "chan", "struct", "interface"); } public void testOnlyLocalTypesInReceiver() { doTestEquals("package foo; type ( t int; s int; ); func (c )", "s", "t"); } public void testNestedBlocks() { doTestInclude("package main; func main() {def := 1; abc := 0; {}}", "abc", "def"); } public void testNoMainAnymore() { doTestEquals("package foo; func ma { }"); } public void testNoChanOrMap() { doTestEquals("package foo; func ma(f int.) { }"); } public void testOnTopLevel() { doTestEquals("package foo; func ma() { }\n", "var", "const", "func", "type"); } public void testPackageBeforeDot() { doCheckResult("package foo; import imp \"\"; func foo(a im.SomeType) {}", "package foo; import imp \"\"; func foo(a imp.SomeType) {}"); } public void testNoUnderscore() { String theSame = "package foo; func foo() {_ := 1; }"; doCheckResult(theSame, theSame); } public void testVarFuncTypeZeroParam() { doCheckResult("package foo; var abc = func() {}; func main() {ab}", "package foo; var abc = func() {}; func main() {abc()}"); } public void testVarFuncTypeOneParam() { doCheckResult("package foo; var abc = func(o int) {}; func main() {ab}", "package foo; var abc = func(o int) {}; func main() {abc()}"); } public void testCaseInsensitiveVariable() { doCheckResult("package main; func test(BBA int){b}", "package main; func test(BBA int){BBA}"); } public void testArrayType() { doCheckResult("package main; type custom []string; func main() { _ = custom }", "package main; type custom []string; func main() { _ = custom{} }"); } public void testMapType() { doCheckResult("package main; type custom map[string]string; func main() { _ = custom }", "package main; type custom map[string]string; func main() { _ = custom{} }"); } public void testRanges() { doTestInclude("package foo; func foo(a int) {for k := range }", "a"); } public void testNoDuplicates() { doTestInclude("package foo; type a struct {", "a"); List stringList = myFixture.getLookupElementStrings(); assertNotNull(stringList); assertSize(1, ContainerUtil.filter(stringList, new TreePrintCondition.Include("a"))); } public void testTypeCastAsVar() { doTestInclude("package main\n" + "var fooVar int = 1\n" + "func main() {\n" + " for _, v := range (*) {\n" + " }\n" + "}", "fooVar"); } private static final String TYPE = "package main;\n" + "type WaitGroup struct {\n" + " counter int32\n" + " waiters int32\n" + " sema *uint32\n" + "}\n"; public void testStructField() { myFixture.configureByText("a.go", TYPE + "func main() {WaitGroup{}};"); myFixture.completeBasic(); myFixture.assertPreferredCompletionItems(0, "counter", "sema", "waiters"); } public void testAnonymousStructField() { myFixture.configureByText("a.go", TYPE + "var baz = []*WaitGroup{{}}"); myFixture.completeBasic(); myFixture.assertPreferredCompletionItems(0, "counter", "sema", "waiters"); } public void testStructField2() { doTestInclude(TYPE + "func main() {WaitGroup{foo:bar, }};", "counter", "waiters", "sema"); } public void testStructFieldReplace() { doCheckResult(TYPE + "func main() { WaitGroup{semabc} }", TYPE + "func main() { WaitGroup{sema:} }", Lookup.REPLACE_SELECT_CHAR); } public void testStructFieldFromOtherStruct() { doCheckResult("package main; type Example struct { ID string }; func main() { a := Example{ID: \"a\"}; _ = []string{a.} }", "package main; type Example struct { ID string }; func main() { a := Example{ID: \"a\"}; _ = []string{a.ID} }", Lookup.NORMAL_SELECT_CHAR); } public void testNoStructFieldAfterColon() { doTestExclude(TYPE + "func main() {WaitGroup{sema:}};", "counter", "waiters", "sema"); } public void testStructConstructions() { doCheckResult("package main; func main() {WaitGr}; type WaitGroup struct {sema *uint32}", "package main; func main() {WaitGroup{}}; type WaitGroup struct {sema *uint32}"); } public void testIntConversion() { doCheckResult("package main; func main() {int}; type int int", "package main; func main() {int()}; type int int"); } public void testPreventSOE() { doTestInclude("package rubex; const ( IGNORECASE = 1; EXTEND = (IGNORECASE << 1); MULTILINE = (EXTEND << 1)); func m() {}", "EXTEND"); } public void testPreventSOE2() { doTestInclude("package main; import \"fmt\"; var fmt = &fmt."); } @SuppressWarnings("ConstantConditions") public void testPackageNames() { myFixture.configureByText("test_test.go", "package myFromTest_test"); myFixture.configureByText("test_file.go", "package myFromFile"); myFixture.configureByText("test.go", "package m"); myFixture.completeBasic(); assertSameElements(myFixture.getLookupElementStrings(), "myFromTest", "myFromFile", "main"); } @SuppressWarnings("ConstantConditions") public void testPackageNamesInTestFile() { myFixture.configureByText("foo.go", "package foo"); myFixture.configureByText("foo_test.go", "package "); myFixture.completeBasic(); assertSameElements(myFixture.getLookupElementStrings(), "foo", "foo_test", "main"); } public void testPointerSpecType() { myFixture.configureByText("foo.go", "package main; type a struct{};" + "func main() {q1, q2:=&a{};q}"); myFixture.completeBasic(); LookupElement first = ArrayUtil.getFirstElement(myFixture.getLookupElements()); assertNotNull(first); LookupElementPresentation presentation = new LookupElementPresentation(); first.renderElement(presentation); assertEquals("*main.a", presentation.getTypeText()); } public void testPackageNamesInEmptyDirectory() { PsiFile file = myFixture.addFileToProject("my-directory-name/test.go", "package m"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.completeBasic(); List strings = myFixture.getLookupElementStrings(); assertNotNull(strings); assertSameElements(strings, "my_directory_name", "main"); } public void testCompleteFromTestsDefinedInCurrentPackage() { myFixture.addFileToProject("my_test.go", "package mytest; func MyFunction() {}"); myFixture.configureByText("current_test.go", "package mytest; func TestSomething() { MyFunc }"); myFixture.completeBasic(); myFixture.checkResult("package mytest; func TestSomething() { MyFunction() }"); } public void testFieldNamesInEmptyStructLiteral() { String source = "package test; " + "type A struct { field_in_a string }; " + "type B struct { A; field_in_b string }; " + "func Test() B { a := A{}; s := \"\"; return B{}; }"; doTestInclude(source, "a", "A", "field_in_b"); } public void testFieldNamesInStructLiteralWithNameValueInitializers() { String source = "package test; " + "type A struct { field_in_a string }; " + "type B struct { A; field_in_b string }; " + "func Test() B { a := A{}; s := \"\"; return B{ A: A{}, }; }"; doTestEquals(source, "field_in_b"); } public void testNoFieldNamesInStructLiteralWithValueInitializers() { String source = "package test; " + "type A struct { field_in_a string }; " + "type B struct { A; field_in_b string }; " + "func Test() B { a := A{}; s := \"\"; return B{ A{}, }; }"; myFixture.configureByText("test.go", source); myFixture.completeBasic(); List variants = myFixture.getLookupElementStrings(); assertNotNull(variants); assertContainsElements(variants, "s"); assertDoesntContain(variants, "field_in_b"); } public void testStructFieldValueCompletion() { String source = "package test; " + "type A struct { field1 string; field2 string }; " + "func Test() A { s := \"\"; return A{field1: \"\", field2: }; }"; doTestInclude(source, "s"); } public void testDoNotCompleteVariableTwice() { doCheckResult("package t; func _() {\n err := 1; for { err := 1; return er } }", "package t; func _() {\n err := 1; for { err := 1; return err } }"); } private void doTestEmptyCompletion() { myFixture.testCompletionVariants(getTestName(true) + ".go"); } } ================================================ FILE: tests/com/goide/completion/GoCompletionTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.testFramework.UsefulTestCase; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; public abstract class GoCompletionTestBase extends GoCodeInsightFixtureTestCase { @NotNull @Override protected String getBasePath() { return "completion"; } protected void doTestCompletion() { myFixture.testCompletion(getTestName(true) + ".go", getTestName(true) + "_after.go"); } protected enum CheckType {EQUALS, INCLUDES, EXCLUDES, ORDERED_EQUALS} private void doTestVariantsInner(@NotNull CompletionType type, int count, CheckType checkType, String... variants) { myFixture.complete(type, count); List stringList = myFixture.getLookupElementStrings(); assertNotNull("\nPossibly the single variant has been completed.\nFile after:\n" + myFixture.getFile().getText(), stringList); Collection varList = ContainerUtil.newArrayList(variants); if (checkType == CheckType.ORDERED_EQUALS) { UsefulTestCase.assertOrderedEquals(stringList, variants); } else if (checkType == CheckType.EQUALS) { UsefulTestCase.assertSameElements(stringList, variants); } else if (checkType == CheckType.INCLUDES) { varList.removeAll(stringList); assertTrue("Missing variants: " + varList, varList.isEmpty()); } else if (checkType == CheckType.EXCLUDES) { varList.retainAll(stringList); assertTrue("Unexpected variants: " + varList, varList.isEmpty()); } } protected void doTestVariants(@NotNull String txt, @NotNull CompletionType type, int count, CheckType checkType, String... variants) { myFixture.configureByText(getDefaultFileName(), txt); failOnFileLoading(); doTestVariantsInner(type, count, checkType, variants); } protected void doTestInclude(@NotNull String txt, String... variants) { doTestVariants(txt, CompletionType.BASIC, 1, CheckType.INCLUDES, variants); } protected void doTestExclude(@NotNull String txt, String... variants) { doTestVariants(txt, CompletionType.BASIC, 1, CheckType.EXCLUDES, variants); } protected void doTestEquals(@NotNull String txt, String... variants) { doTestVariants(txt, CompletionType.BASIC, 1, CheckType.EQUALS, variants); } protected void doCheckResult(@NotNull String before, @NotNull String after) { doCheckResult(before, after, (Character)null); } protected void doCheckResult(@NotNull String before, @NotNull String after, @Nullable Character c) { myFixture.configureByText(getDefaultFileName(), before); failOnFileLoading(); myFixture.completeBasic(); if (c != null) myFixture.type(c); myFixture.checkResult(after); } protected void doCheckResult(@NotNull String before, @NotNull String after, @NotNull String selectItem) { myFixture.configureByText(getDefaultFileName(), before); failOnFileLoading(); myFixture.completeBasic(); selectLookupItem(selectItem); myFixture.checkResult(after); } protected void selectLookupItem(@NotNull String selectItem) { LookupElement[] lookupElements = myFixture.getLookupElements(); assertNotNull("Lookup is empty", lookupElements); LookupElement toSelect = null; for (LookupElement lookupElement : lookupElements) { if (selectItem.equals(lookupElement.getLookupString())) { toSelect = lookupElement; break; } } assertNotNull(selectItem + " not found in lookup", toSelect); myFixture.getLookup().setCurrentItem(toSelect); myFixture.type(Lookup.NORMAL_SELECT_CHAR); } protected void failOnFileLoading() { //((PsiManagerImpl)myFixture.getPsiManager()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, getTestRootDisposable()); } protected String getDefaultFileName() { return "a.go"; } } ================================================ FILE: tests/com/goide/completion/GoExcludedPackagesTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.goide.SdkAware; import com.goide.project.GoExcludedPathsSettings; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; @SdkAware public class GoExcludedPackagesTest extends GoCompletionTestBase { @Override protected void tearDown() throws Exception { GoExcludedPathsSettings.getInstance(getProject()).setExcludedPackages(ArrayUtil.EMPTY_STRING_ARRAY); super.tearDown(); } private void doTestExcluded(@NotNull String initial, @NotNull String after, String... excludedPaths) { GoExcludedPathsSettings.getInstance(getProject()).setExcludedPackages(excludedPaths); myFixture.configureByText("a.go", initial); myFixture.completeBasic(); myFixture.checkResult(after); } public void testExcludedPathCompletion() { String initial = "package a; func b() {\n fmt.Printl \n}"; doTestExcluded(initial, initial, "fmt"); } public void testExcludedPathSameBeginning() { String initial = "package a; func b() {\n fmt.Printl \n}"; String after = "package a;\n\nimport \"fmt\"\n\nfunc b() {\n fmt.Println() \n}"; doTestExcluded(initial, after, "fm"); } } ================================================ FILE: tests/com/goide/completion/GoTestNameCompletionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.completion; import com.intellij.codeInsight.completion.CompletionType; public class GoTestNameCompletionTest extends GoCompletionTestBase { public void testShowFromSimilarFileFirst() { myFixture.addFileToProject("foo.go", "package main; func FooPublic() {}"); myFixture.addFileToProject("a.go", "package main; func BarPublic() {}"); doTestVariants("package main; func ", CompletionType.BASIC, 1, CheckType.ORDERED_EQUALS, "BenchmarkBarPublic", "ExampleBarPublic", "TestBarPublic", "BenchmarkFooPublic", "ExampleFooPublic", "TestFooPublic"); } public void testForFunctions() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doTestEquals("package main; func ", "BenchmarkPublic", "ExamplePublic", "TestPublic"); } public void testForMethods() { myFixture.addFileToProject("foo.go", "package main; type Foo struct {}; func (Foo) Public() {}; func (Foo) private() {}; func (Foo) _() {}"); doTestEquals("package main; func ", "BenchmarkFoo_Public", "ExampleFoo_Public", "TestFoo_Public"); } public void testAlreadyImplementTests() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); myFixture.addFileToProject("foo_test.go", "package main; func TestPublic() {}; func ExampleFunc() {}"); doTestEquals("package main; func ", "BenchmarkPublic", "ExamplePublic", "TestPublic2"); } public void testWithoutSignature() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithoutSignatureWithBlock() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP{}", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithInvalidSignatureWithoutParameters() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP(){}", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithInvalidSignature() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP(foo Bar){}", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(foo Bar) {\n" + "\t\n" + "}"); } public void testWithoutBody() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP()", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithIncompleteBody() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP() {", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithEmptyBody() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP(){}", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithoutStatements() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP() {\n}", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testWithStatements() { myFixture.addFileToProject("foo.go", "package main; func Public() {}; func private() {}; func _() {}"); doCheckResult("package main; func TestP() { println(); println(); }", "package main;\n" + "\n" + "import \"testing\"\n" + "\n" + "func TestPublic(t *testing.T) { println(); println(); }"); } public void testCrossTestPackage() { myFixture.addFileToProject("foo.go", "package foo; func Public() {}; func private() {}; func _() {}"); doCheckResult("package foo_test; func TestP() { }", "package foo_test;\n\n" + "import \"testing\"\n\n" + "func TestPublic(t *testing.T) {\n" + "\t\n" + "}"); } public void testDoNotSuggestDuplicatedFunction() { myFixture.addFileToProject("foo.go", "package foo\n\nfunc Public() {} func private() {}; func _() {}"); doCheckResult("package foo; func TestPublic() {}\n\nfunc TestP() { }", "package foo;\n\n" + "import \"testing\"\n\n" + "func TestPublic() {}\n\n" + "func TestPublic2(t *testing.T) {\n" + "\t\n" + "}"); } public void testDoNotSuggestDuplicatedFunctionForTestPackages() { myFixture.addFileToProject("foo.go", "package foo\n\nfunc Public() {} func private() {}; func _() {}"); doCheckResult("package foo_test; func TestPublic() {}\n\nfunc TestP() { }", "package foo_test;\n\n" + "import \"testing\"\n\n" + "func TestPublic() {}\n\n" + "func TestPublic2(t *testing.T) {\n" + "\t\n" + "}"); } @Override protected String getDefaultFileName() { return "a_test.go"; } } ================================================ FILE: tests/com/goide/coverage/GoCoverageCalculationTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.coverage; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.runconfig.testing.coverage.GoCoverageAnnotator; import com.goide.runconfig.testing.coverage.GoCoverageProjectData; import com.goide.runconfig.testing.coverage.GoCoverageRunner; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class GoCoverageCalculationTest extends GoCodeInsightFixtureTestCase { public void testCoverage() throws IOException { assertEquals("75% statements", annotate().getFileCoverageInformationString(myFixture.findFileInTempDir(file()))); } public void testCoverage2() throws IOException { assertEquals("83.3% statements", annotate().getFileCoverageInformationString(myFixture.findFileInTempDir(file()))); } public void testWithoutHits() throws IOException { assertEquals("0% statements", annotate().getFileCoverageInformationString(myFixture.findFileInTempDir(file()))); } public void testWithoutAnything() throws IOException { assertNull(annotate().getFileCoverageInformationString(myFixture.findFileInTempDir(file()))); } public void testDirectory() throws IOException { GoCoverageAnnotator annotator = annotate("coverage.go", "coverage2.go", "withoutHits.go"); VirtualFile firstFile = myFixture.findFileInTempDir("coverage.go"); VirtualFile secondFile = myFixture.findFileInTempDir("coverage2.go"); VirtualFile thirdFile = myFixture.findFileInTempDir("withoutHits.go"); assertEquals("75% statements", annotator.getFileCoverageInformationString(firstFile)); assertEquals("83.3% statements", annotator.getFileCoverageInformationString(secondFile)); assertEquals("0% statements", annotator.getFileCoverageInformationString(thirdFile)); assertEquals("66.7% files, 72.7% statements", annotator.getDirCoverageInformationString(firstFile.getParent())); } public void testMerging() throws IOException { VirtualFile file = myFixture.getTempDirFixture().createFile(file()); GoCoverageProjectData firstData = parseData("coverage.out"); GoCoverageProjectData secondData = parseData("coverage_for_merge.out"); GoCoverageAnnotator firstAnnotator = annotate(firstData); GoCoverageAnnotator secondAnnotator = annotate(secondData); firstData.merge(secondData); GoCoverageAnnotator mergeAnnotator = annotate(firstData); assertEquals("75% statements", firstAnnotator.getFileCoverageInformationString(file)); assertEquals("33.3% statements", secondAnnotator.getFileCoverageInformationString(file)); assertEquals("80% statements", mergeAnnotator.getFileCoverageInformationString(file)); } private GoCoverageAnnotator annotate() throws IOException { return annotate(file()); } @NotNull private GoCoverageAnnotator annotate(@NotNull String fileName, @NotNull String... fileNames) throws IOException { myFixture.getTempDirFixture().createFile(fileName); for (String name : fileNames) { myFixture.getTempDirFixture().createFile(name); } return annotate(parseData("coverage.out")); } @NotNull private GoCoverageAnnotator annotate(@NotNull GoCoverageProjectData data) { GoCoverageAnnotator annotator = new GoCoverageAnnotator(myFixture.getProject()); annotator.annotateAllFiles(data, getRoot()); return annotator; } @NotNull private GoCoverageProjectData parseData(@NotNull String coverageSource) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(getTestDataPath(), coverageSource)))) { GoCoverageProjectData data = GoCoverageRunner.parseCoverage(reader, myFixture.getProject(), myModule); assertNotNull(data); return data; } } @NotNull private String file() { return getTestName(true) + ".go"; } @Override @NotNull protected String getBasePath() { return "coverage"; } @NotNull private VirtualFile getRoot() { VirtualFile root = myFixture.getTempDirFixture().getFile(""); assertNotNull(root); return root; } } ================================================ FILE: tests/com/goide/editor/GoBraceMatcherTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.GoFileType; public class GoBraceMatcherTest extends GoCodeInsightFixtureTestCase { public void testCloseParenBeforeOpeningBrace() { myFixture.configureByText(GoFileType.INSTANCE, "package foo; func name{}"); myFixture.type('('); myFixture.checkResult("package foo; func name(){}"); } } ================================================ FILE: tests/com/goide/editor/GoExitPointsHighlightingTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.intellij.codeInsight.highlighting.HighlightUsagesHandler; import com.intellij.codeInsight.highlighting.HighlightUsagesHandlerBase; import com.intellij.psi.PsiElement; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; @SdkAware public class GoExitPointsHighlightingTest extends GoCodeInsightFixtureTestCase { public void testBasicExitPoints() { String text = "package main;\n" + "func bar(x int) int {\n" + " if (x < 10) {\n" + " return -1" + " }" + " return x\n" + "}"; doTest(text, "func", "return -1", "return x"); } public void testCaretOnFuncWithReturnAndPanic() { String text = "package main;\n" + "func bar(x int) int {\n" + " if (9 < 10) {\n" + " return -1" + " }" + " panic(x)\n" + "}"; doTest(text, "func", "return -1", "panic(x)"); } public void testCaretOnFuncWithNoExitPoints() { String text = "package main\n" + "import \"fmt\"\n" + "func main() {\n" + " fmt.Println(\"Hello, world!\"\n" + "}"; doTest(text, "func"); } public void testCaretOnFuncOnType() { String text = "package main\n" + "\n" + "type Demo struct {}\n" + "\n" + "func (a Demo) demo() int {\n" + " return -1\n" + "}"; doTest(text, "func", "return -1"); } public void testBreakSwitch() { String text = "package main\n" + "import \"fmt\"\n" + "\n" + "type Demo struct {}\n" + "\n" + "\n" + "func (a Demo) demo() int {\n" + " i := 2\n" + " n := 10\n" + " var j int\n" + " var m int = 10\n" + " var a [][]int\n" + " var item = 10\n" + " for i = 0; i < n; i++ {\n" + " for j = 0; j < m; j++ {\n" + " switch a[i][j] {\n" + " case nil:\n" + " fmt.Println()\n" + " break\n" + " case item:\n" + " fmt.Println()\n" + " break\n" + " }\n" + " }\n" + " }\n" + " return -1\n" + "}"; doTest(text, "break", "break", "switch"); } public void testBreakFor() { String text = "package main\n" + "import \"fmt\"\n" + "\n" + "type Demo struct {}\n" + "\n" + "\n" + "func (a Demo) demo() int {\n" + " i := 2\n" + " n := 10\n" + " var j int\n" + " var m int = 10\n" + " for i = 0; i < n; i++ {\n" + " for j = 0; j < m; j++ {\n" + " if j < 10 {\n" + " break\n" + " }\n" + " }\n" + " }\n" + " return -1\n" + "}"; doTest(text, "for", "break"); } public void testBreakSelect() { String text = "package main\n" + "\n" + "import \"fmt\"\n" + "\n" + "func main() {\n" + " fmt.Println(\"FOO\")\n" + " c1 := make(chan string)\n" + " c2 := make(chan string)\n" + " for i := 0; i < 2; i++ {\n" + " select {\n" + " case msg1 := <-c1:\n" + " fmt.Println(\"received\", msg1)\n" + " break\n" + " case msg2 := <-c2:\n" + " fmt.Println(\"received\", msg2)\n" + " }\n" + " }\n" + "}\n"; doTest(text, "select", "break"); } public void testBreakWithLabel() { String text = "package main\n" + "\n" + "func main() {\n" + "\n" + " L:\n" + " for i := 0; i < 2; i++ {\n" + " switch i {\n" + " case 2:\n" + " break\n" + " case 1:\n" + " break L\n" + " default:\n" + " break L\n" + " }\n" + " }\n" + "}\n"; doTest(text, "L", "break L", "break L"); } private void doTest(@NotNull String text, String... usages) { myFixture.configureByText("foo.go", text); @SuppressWarnings("unchecked") HighlightUsagesHandlerBase handler = HighlightUsagesHandler.createCustomHandler(myFixture.getEditor(), myFixture.getFile()); assertNotNull(handler); List targets = handler.getTargets(); assertEquals(1, targets.size()); handler.computeUsages(targets); List textUsages = ContainerUtil.map(handler.getReadUsages(), range -> range.substring(myFixture.getFile().getText())); assertSameElements(textUsages, usages); } } ================================================ FILE: tests/com/goide/editor/GoFoldingBuilderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import org.jetbrains.annotations.NotNull; public class GoFoldingBuilderTest extends GoCodeInsightFixtureTestCase { @NotNull @Override protected String getBasePath() { return "folding"; } private void doTest() { myFixture.testFolding(getTestDataPath() + "/" + getTestName(true) + ".go"); } public void testSimple() { doTest(); } public void testImportList() { doTest(); } public void testImportListWithJustSingleImportKeyword() { doTest(); } public void testImportListWithoutSpaceBetweenKeywordAndString() { doTest(); } public void testImportListWithoutSpaceBetweenKeywordAndParen() { doTest(); } public void testEmptyImportList() { doTest(); } public void testImportListWithNewLineAfterKeyword() { doTest(); } public void testImportListWithOnlyThreeSymbolsToFold() { doTest(); } public void testVarDeclaration() { doTest(); } public void testConstDeclaration() { doTest(); } public void testTypeDeclaration() { doTest(); } public void testCompositeLiteral() { doTest(); } public void testIfStatement() { doTest(); } public void testForStatement() { doTest(); } public void testSwitchSelectCaseStatement() { doTest(); } public void testTypeSwitchStatement() { doTest(); } } ================================================ FILE: tests/com/goide/editor/GoHighlightingAnnotatorTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.intellij.testFramework.TestDataPath; import org.jetbrains.annotations.NotNull; @SdkAware @TestDataPath("$PROJECT_ROOT/testData/colorHighlighting") public class GoHighlightingAnnotatorTest extends GoCodeInsightFixtureTestCase { public void testSimple() { doTest(); } public void testLabel() { doTest(); } public void testReceiver() { doTest(); } public void testFuncAndMethod() { doTest(); } public void testOctAndHex() { doTest(); } public void testTypes() { doTest(); } public void testStructFields() { doTest(); } public void testBuiltinFunctions() { doTest(); } private void doTest() { myFixture.testHighlighting(false, true, false, getTestName(true) + ".go"); } @NotNull @Override protected String getBasePath() { return "colorHighlighting"; } } ================================================ FILE: tests/com/goide/editor/GoLiveTemplateTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; public class GoLiveTemplateTest extends GoCodeInsightFixtureTestCase { public void testErrOnStatementBeginning() { myFixture.configureByText("a.go", "package main; func main() { }"); myFixture.type("err\t"); myFixture.checkResult("package main; func main() {\n" + "\tif err != nil {\n" + "\t\t\n" + "\t} }"); } public void testErrAfterIf() { myFixture.configureByText("a.go", "package main; func main() { if }"); myFixture.type("err\t"); myFixture.checkResult("package main; func main() { if err\t }"); } public void testJsonInTag() { myFixture.configureByText("a.go", "package main; type foo struct { MyFieldDeclaration int }"); myFixture.type("json\t"); myFixture.checkResult("package main; type foo struct { MyFieldDeclaration int `json:\"my_field_declaration\"` }"); } public void testJsonInTagAfterComplexType() { myFixture.configureByText("a.go", "package main; type foo struct { a []int }"); myFixture.type("json\t"); myFixture.checkResult("package main; type foo struct { a []int `json:\"a\"` }"); } public void testXmlInTagOfAnonymousField() { myFixture.configureByText("a.go", "package main; type foo struct { int }"); myFixture.type("xml\t"); myFixture.checkResult("package main; type foo struct { int `xml:\"\"` }"); } public void testXmlInTagLiteral() { myFixture.configureByText("a.go", "package main; type foo struct { a int `` }"); myFixture.type("xml\t"); myFixture.checkResult("package main; type foo struct { a int `xml:\"a\"` }"); } public void testJsonNotInTag() { myFixture.configureByText("a.go", "package main; func main() { }"); myFixture.type("json\t"); myFixture.checkResult("package main; func main() { json\t }"); } public void testJsonNotInTag_2() { myFixture.configureByText("a.go", "package main; type foo struct { int \n }"); myFixture.type("json\t"); myFixture.checkResult("package main; type foo struct { int \njson\t }"); } public void testForInSignature() { myFixture.configureByText("a.go", "package main; func "); myFixture.type("for\t"); myFixture.checkResult("package main; func for\t"); } public void testForInBlock() { myFixture.configureByText("a.go", "package main; func main() { }"); myFixture.type("for\t"); myFixture.checkResult("package main; func main() {\n" + "\tfor ; ; {\n" + "\t\t\n" + "\t} }"); } public void testVarDeclarationInBlock() { myFixture.configureByText("a.go", "package main; func main() { }"); myFixture.type(":\t"); myFixture.checkResult("package main; func main() {\n\tname := }"); } public void testVarDeclarationInLabel() { myFixture.configureByText("a.go", "package main; func main() { name }"); myFixture.type(":\t"); myFixture.checkResult("package main; func main() { name :\t }"); } public void testMainAfterPackageClause() { myFixture.configureByText("a.go", "package mai"); myFixture.type("n\t"); myFixture.checkResult("package main\t"); } } ================================================ FILE: tests/com/goide/editor/GoParameterInfoHandlerTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoArgumentList; import com.intellij.codeInsight.hint.ParameterInfoComponent; import com.intellij.lang.parameterInfo.CreateParameterInfoContext; import com.intellij.lang.parameterInfo.ParameterInfoUIContextEx; import com.intellij.testFramework.utils.parameterInfo.MockCreateParameterInfoContext; import com.intellij.testFramework.utils.parameterInfo.MockUpdateParameterInfoContext; import org.jetbrains.annotations.NotNull; public class GoParameterInfoHandlerTest extends GoCodeInsightFixtureTestCase { private GoParameterInfoHandler myParameterInfoHandler; @Override protected void setUp() throws Exception { super.setUp(); myParameterInfoHandler = new GoParameterInfoHandler(); } // @formatter:off public void testUnnamedParameters() { doTest("string, interface{}"); } public void testUnnamedAndNamedParameters() { doTest("a string, interface{}"); } public void testFuncParamNone() { doTest("<no parameters>"); } public void testChainedCall() { doTest("param1 string, param2 int"); } public void testMethParamNone() { doTest("<no parameters>"); } public void testFieldMethCall() { doTest("a int, b int"); } public void testFuncTypes() { doTest("string"); } public void testFunctionTypeByRef() { doTest("intParam int"); } public void testFuncParam() { doTest(1, "num int, text string"); } public void testFuncParamMulti() { doTest(4, "a int, b int, c int, d string, e string, f string"); } public void testFuncParamEllipsis() { doTest(5, "num int, text string, more ...int"); } public void testFuncEmbedInner() { doTest(1, "num int, text string"); } public void testFuncEmbedOuter() { doTest(2, "a int, b int, c int, d int"); } public void testMethParam() { doTest(1, "num int, text string"); } public void testMethParamEllipsis() { doTest(5, "num int, text string, more ...int"); } public void testClosure() { doTest(1, "param1 string, param2 string"); } private void doTest(@NotNull String expectedPresentation) { doTest(0, expectedPresentation); } // @formatter:on private void doTest(int expectedParamIdx, @NotNull String expectedPresentation) { // Given myFixture.configureByFile(getTestName(true) + ".go"); // When Object[] itemsToShow = getItemsToShow(); int paramIdx = getHighlightedItem(); String presentation = getPresentation(itemsToShow, paramIdx); // Then assertEquals(1, itemsToShow.length); assertEquals(expectedParamIdx, paramIdx); assertEquals(expectedPresentation, presentation); } private Object[] getItemsToShow() { CreateParameterInfoContext createCtx = new MockCreateParameterInfoContext(myFixture.getEditor(), myFixture.getFile()); GoArgumentList psiElement = myParameterInfoHandler.findElementForParameterInfo(createCtx); assertNotNull(psiElement); myParameterInfoHandler.showParameterInfo(psiElement, createCtx); return createCtx.getItemsToShow(); } private int getHighlightedItem() { MockUpdateParameterInfoContext updateCtx = new MockUpdateParameterInfoContext(myFixture.getEditor(), myFixture.getFile()); GoArgumentList psiElement = myParameterInfoHandler.findElementForUpdatingParameterInfo(updateCtx); assertNotNull(psiElement); myParameterInfoHandler.updateParameterInfo(psiElement, updateCtx); return updateCtx.getCurrentParameter(); } private String getPresentation(Object[] itemsToShow, int paramIdx) { ParameterInfoUIContextEx uiCtx = ParameterInfoComponent.createContext(itemsToShow, myFixture.getEditor(), myParameterInfoHandler, paramIdx); return GoParameterInfoHandler.updatePresentation(itemsToShow[0], uiCtx); } @NotNull @Override protected String getBasePath() { return "parameterInfo"; } } ================================================ FILE: tests/com/goide/editor/GoQuoteHandlerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; public class GoQuoteHandlerTest extends GoCodeInsightFixtureTestCase { public void testNewlineInStringLiteral() { myFixture.configureByText("t.go", "package t; const c = \"constvalue\""); myFixture.type('\n'); myFixture.checkResult("package t; const c = \"const\" +\n\t\"value\""); } public void testRemoveSingleQuote() { myFixture.configureByText("t.go", "package main; const _ = '\\n'''"); myFixture.type('\b'); myFixture.checkResult("package main; const _ = '\\n'"); } public void testAddSingleQuote() { myFixture.configureByText("t.go", "package main; const _ = '\\n'"); myFixture.type('\''); myFixture.checkResult("package main; const _ = '\\n'''"); } public void testTypeSingleQuote() { doTypeQuoteTest('\''); } public void testTypeDoubleQuote() { doTypeQuoteTest('\"'); } public void testTypeBacktick() { doTypeQuoteTest('`'); } private void doTypeQuoteTest(char q) { myFixture.configureByText("t.go", "package t; const c = "); myFixture.type(q); myFixture.checkResult("package t; const c = " + q + "" + q); } } ================================================ FILE: tests/com/goide/editor/GoSelectWordTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.testFramework.fixtures.CodeInsightTestUtil; import org.jetbrains.annotations.NotNull; public class GoSelectWordTest extends GoCodeInsightFixtureTestCase { public void testImportString() { doTest(); } public void testMultipleImportString() { doTest(); } public void testStringLiteral() { doTest(); } public void testBlock() { doTest(); } public void testArguments() { doTest(); } public void testParameters() { doTest(); } public void testResultParameters() { doTest(); } public void testFunctionName() { doTest(); } private void doTest() { CodeInsightTestUtil.doWordSelectionTestOnDirectory(myFixture, getTestName(true), "go"); } @NotNull @Override protected String getBasePath() { return "selectWord"; } } ================================================ FILE: tests/com/goide/editor/GoSmartEnterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.openapi.actionSystem.IdeActions; public class GoSmartEnterTest extends GoCodeInsightFixtureTestCase { public void testGoStatement() { doTest(); } public void testDeferStatement() { doTest(); } public void testGoStatementOnNonFunctionType() { doTest(); } public void testDeferStatementOnNonFunctionType() { doTest(); } public void testFunction() { doTest(); } public void testFunctionLiteral() { doTest(); } public void testFunctionWithBlock() { doTest(); } public void testFunctionLiteralWithBlock() { doTest(); } public void testIf() { doTest(); } public void testIfWithBlock() { doTest(); } public void testFor() { doTest(); } public void testForWithBlock() { doTest(); } private void doTest() { myFixture.configureByFile(getTestName(true) + ".go"); myFixture.performEditorAction(IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT); myFixture.checkResultByFile(getTestName(true) + "-after.go"); } @Override protected String getBasePath() { return "smartEnter"; } } ================================================ FILE: tests/com/goide/editor/GoStatementMoverTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.openapi.actionSystem.IdeActions; import org.jetbrains.annotations.NotNull; public class GoStatementMoverTest extends GoCodeInsightFixtureTestCase { public void testSimpleStatement() { doTest(false); doTest(true); } public void testStatementInEndOfBlock() { doTest(true); doTest(false); } public void testInsertedStatement() { doTest(false); } public void testInsertedStatementDown() { doTest(true); } public void testFunctionDeclaration() { doTest(true); doTest(false); } public void testFunctionDeclarationWithFewTopLevelDeclarations() { doTest(false); } public void testFunctionDeclarationWithFewTopLevelDeclarationsDown() { doTest(true); } public void testImport() { doTest(false); } public void testImportWithCaretAtLastImport() { doTest(false); } public void testImportWithCaretAtImportString() { doTest(false); doTest(true); } public void testImportDown() { doTest(true); } public void testPackage() { doTest(true); } public void testTwoFunc() { doTest(true); doTest(false); } public void testTwoStatements() { doTest(false); } public void testTwoStatementsDown() { doTest(true); } public void testVarSpecTopLevelDeclaration() { doTest(true); } public void testAnonymousFunction() { doTest(false); doTest(true); } public void testAnonymousFunctionAtAssignment() { doTest(false); doTest(true); } private void doTest(boolean down) { String testName = getTestName(true); myFixture.configureByFile(testName + ".go"); if (down) { myFixture.performEditorAction(IdeActions.ACTION_MOVE_STATEMENT_DOWN_ACTION); myFixture.checkResultByFile(testName + "-afterDown.go", true); } else { myFixture.performEditorAction(IdeActions.ACTION_MOVE_STATEMENT_UP_ACTION); myFixture.checkResultByFile(testName + "-afterUp.go", true); } } @NotNull @Override protected String getBasePath() { return "editor/statement-mover"; } } ================================================ FILE: tests/com/goide/editor/surround/GoSurrounderTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import java.util.List; @SdkAware public abstract class GoSurrounderTestBase extends GoCodeInsightFixtureTestCase { protected void doTest(@NotNull String codeBefore, @NotNull String expectedCodeAfter, @NotNull String surrounderDescription, boolean apply) { PsiFile file = myFixture.configureByText("a.go", normalizeCode(codeBefore)); List applicable = SurroundWithHandler.buildSurroundActions(myFixture.getProject(), myFixture.getEditor(), file, null); if (applicable == null) { assertFalse(apply); return; } String suffix = ". " + surrounderDescription; for (AnAction action : applicable) { String actionPresentation = action.getTemplatePresentation().getText(); if (actionPresentation != null && StringUtil.endsWith(actionPresentation, suffix)) { assertTrue(apply); myFixture.testAction(action); return; } } if (apply) { myFixture.checkResult(normalizeCode(expectedCodeAfter), true); } } } ================================================ FILE: tests/com/goide/editor/surround/GoWithBlockSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithBlockSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithBlockSurrounder().getTemplateDescription(); public void testWithOneStatement() { doTest("var b bool", "{\n\tvar b bool\n}\n", SURROUNDER_DESCRIPTION, true); } public void testWithThreeStatements() { doTest("var b int = 1\nb = true\ntype Type int", "{\n\tvar b int = 1\n\tb = true\n\ttype Type int\n}\n", SURROUNDER_DESCRIPTION, true); } public void testNoBlock() { doTest("var b, c bool = true, false", "var b, c bool = true, false", SURROUNDER_DESCRIPTION, false); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithForSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithForSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithForSurrounder().getTemplateDescription(); public void testWithOneStatement() { doTest("var b bool", "for {\n\tvar b bool\n}\n", SURROUNDER_DESCRIPTION, true); } public void testWithThreeStatements() { doTest("var b int = 1\nb = true\ntype Type int", "for {\n\tvar b int = 1\n\tb = true\n\ttype Type int\n}\n", SURROUNDER_DESCRIPTION, true); } public void testNoFor() { doTest("var b, c bool = true, false", "var b, c bool = true, false", SURROUNDER_DESCRIPTION, false); } public void testWithCaretAtMultilineStatement() { doTest("for {\n\n}", "for {\n\tfor {\n\n\t}\n}\n", SURROUNDER_DESCRIPTION, true); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithIfElseExpressionSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithIfElseExpressionSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithIfElseExpressionSurrounder().getTemplateDescription(); public void testWithOneBoolVariable() { doTest("var b bool\nb", "var b bool\nif b {\n\n} else {\n\n}", SURROUNDER_DESCRIPTION, true); } public void testWithNotBoolExpressions() { doTest("var b int = 1\nb", "var b int = 1\nb", SURROUNDER_DESCRIPTION, false); } public void testWithTwoBoolExpressions() { doTest("var b, c bool = true, false\nb c", "var b, c bool = true, false\nif b {\n\n} else {\n\n}\nc", SURROUNDER_DESCRIPTION, true); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithIfElseSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithIfElseSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithIfElseSurrounder().getTemplateDescription(); public void testWithOneStatement() { doTest("var b bool", "if {\n\tvar b bool\n} else {\n\n}\n", SURROUNDER_DESCRIPTION, true); } public void testWithThreeStatements() { doTest("var b int = 1\nb = true\ntype Type int", "if {\n\tvar b int = 1\n\tb = true\n\ttype Type int\n} else {\n\n}\n", SURROUNDER_DESCRIPTION, true); } public void testNoIf() { doTest("var b, c bool = true, false", "", SURROUNDER_DESCRIPTION, false); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithIfExpressionSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithIfExpressionSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithIfExpressionSurrounder().getTemplateDescription(); public void testWithOneBoolVariable() { doTest("var b bool\nb", "var b bool\nif b {\n\n}", SURROUNDER_DESCRIPTION, true); } public void testWithNotBoolExpressions() { doTest("var b int = 1\nb", "var b int = 1\nb", SURROUNDER_DESCRIPTION, false); } public void testWithTwoBoolExpressions() { doTest("var b, c bool = true, false\nb c", "var b, c bool = true, false\nif b {\n\n}\nc", SURROUNDER_DESCRIPTION, true); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithIfSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithIfSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithIfSurrounder().getTemplateDescription(); public void testWithOneStatement() { doTest("var b bool", "if {\n\tvar b bool\n}\n", SURROUNDER_DESCRIPTION, true); } public void testWithThreeStatements() { doTest("var b int = 1\nb = true\ntype Type int", "if {\n\tvar b int = 1\n\tb = true\n\ttype Type int\n}\n", SURROUNDER_DESCRIPTION, true); } public void testNoIf() { doTest("var b, c bool = true, false", "var b, c bool = true, false", SURROUNDER_DESCRIPTION, false); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithNotExpressionSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithNotExpressionSurrounderTest extends GoSurrounderTestBase { private static final String SURROUNDER_DESCRIPTION = new GoWithNotExpressionSurrounder().getTemplateDescription(); public void testWithOneBoolVariable() { doTest("var b bool\nb", "var b bool\n!(b)", SURROUNDER_DESCRIPTION, true); } public void testWithNotBoolExpressions() { doTest("var b int = 1\nb", "var b int = 1\nb", SURROUNDER_DESCRIPTION, false); } public void testInAssignment() { doTest("var b, c bool = true, false\nc = b", "var b, c bool = true, false\nc = !(b)", SURROUNDER_DESCRIPTION, true); } } ================================================ FILE: tests/com/goide/editor/surround/GoWithParenthesisSurrounderTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.editor.surround; public class GoWithParenthesisSurrounderTest extends GoSurrounderTestBase { private static final String PARENTHESIS_SURROUNDER = new GoWithParenthesisSurrounder().getTemplateDescription(); public void testParenthesis() { doTest("a := 1 + 2", "a := (1 + 2)\n", PARENTHESIS_SURROUNDER, true); } public void testNoParenthesis() { doTest("a := 1 + 2}", "a := 1 + 2", PARENTHESIS_SURROUNDER, false); } } ================================================ FILE: tests/com/goide/formatter/GoFormatterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.formatter; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.psi.codeStyle.CodeStyleManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoFormatterTest extends GoCodeInsightFixtureTestCase { @NotNull @Override protected String getBasePath() { return "formatting"; } public void testSimple() { doTest(); } public void testCaseE() { doTest('e'); } public void testCaseEnter() { doTestEnter(); } public void testCase2Enter() { doTestEnter(); } public void testSwitchEnter() { doTestEnter(); } public void testTypeEnter() { doTestEnter(); } public void testSpacesInArithmeticExpressions() { doTest(); } public void testConstDeclaration() { doTest(); } public void testVarDeclaration() { doTest(); } public void testBreakLines() { doTest(); } public void testCommentIndentation() { doTest(); } public void testElseStatement() { doTest(); } public void testEmptyStatementInForClause() { doTest(); } public void testExpressionsContinuationIndent() { doTest(); } private void doTest() { doTest(null); } private void doTestEnter() { doTest('\n'); } private void doTest(@Nullable Character c) { String testName = getTestName(true); myFixture.configureByFile(testName + ".go"); String after = doTest(c, testName); myFixture.checkResultByFile(after); } private String doTest(@Nullable Character c, String testName) { if (c == null) { WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile()); }); } else { myFixture.type(c); } return String.format("%s-after.go", testName); } } ================================================ FILE: tests/com/goide/generate/GoGenerateTestActionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.generate; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.runconfig.testing.GoTestFunctionType; import com.goide.runconfig.testing.frameworks.gotest.GotestGenerateAction; import org.jetbrains.annotations.NotNull; public class GoGenerateTestActionTest extends GoCodeInsightFixtureTestCase { public void testTest() { doTest(GoTestFunctionType.TEST, "package test\n", "package test\n" + "\n" + "import \"testing\"\n" + "func Test(t *testing.T) {\n" + "\t\n" + "}"); } public void testBenchmark() { doTest(GoTestFunctionType.BENCHMARK, "package test\n", "package test\n" + "\n" + "import \"testing\"\n" + "func Benchmark(b *testing.B) {\n" + "\t\n" + "}"); } public void testExample() { doTest(GoTestFunctionType.EXAMPLE, "package test\n", "package test\n" + "func Example() {\n" + "\t\n" + "}"); } public void testImportedTestingPackage() { doTest(GoTestFunctionType.TEST, "package test\n" + "import `testing`\n" + "", "package test\n" + "import `testing`\n" + "func Test(t *testing.T) {\n" + "\t\n" + "}"); } public void testImportedTestingPackageWithDifferentAlias() { doTest(GoTestFunctionType.TEST, "package test\n" + "import my_alias `testing`\n" + "", "package test\n" + "import my_alias `testing`\n" + "func Test(t *my_alias.T) {\n" + "\t\n" + "}"); } public void testImportedTestingPackageWithDot() { doTest(GoTestFunctionType.TEST, "package test\n" + "import . `testing`\n" + "", "package test\n" + "import . `testing`\n" + "func Test(t *T) {\n" + "\t\n" + "}"); } public void testImportedTestingPackageWithForSideEffects() { doTest(GoTestFunctionType.TEST, "package test\n" + "import _ `testing`\n" + "", "package test\n" + "\n" + "import (\n" + "\t_ \"testing\"\n" + "\t\"testing\"\n" + ")\n" + "func Test(t *testing.T) {\n" + "\t\n" + "}"); } public void testImportedPackageWithTestingAlias() { doTest(GoTestFunctionType.TEST, "package test\n" + "import testing `some_other_package`\n" + "", "package test\n" + "\n" + "import (\n" + "\ttesting \"some_other_package\"\n" + "\ttesting2 \"testing\"\n" + ")\n" + "func Test(t *testing2.T) {\n" + "\t\n" + "}"); } private void doTest(@NotNull GoTestFunctionType type, @NotNull String beforeText, @NotNull String afterText) { myFixture.configureByText("test_test.go", beforeText); myFixture.testAction(new GotestGenerateAction(type)); myFixture.checkResult(afterText); } } ================================================ FILE: tests/com/goide/highlighting/GoColorsAndFontsPageTest.java ================================================ package com.goide.highlighting; import junit.framework.TestCase; import org.junit.Assert; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GoColorsAndFontsPageTest extends TestCase { public void testDemoText() { GoColorsAndFontsPage testee = new GoColorsAndFontsPage(); String demoText = testee.getDemoText(); Set knownElements = testee.getAdditionalHighlightingTagToDescriptorMap().keySet(); Matcher m = Pattern.compile("").matcher(demoText); while (m.find()) { String name = m.group(1); if (!knownElements.contains(name)) { Assert.fail("Unknown element \"" + m.group() + "\"."); } } } } ================================================ FILE: tests/com/goide/inspections/GoAnonymousFieldDefinitionTypeInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.quickfix.GoCreateWrapperTypeQuickFix; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; public class GoAnonymousFieldDefinitionTypeInspectionTest extends GoQuickFixTestBase{ @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoAnonymousFieldDefinitionTypeInspection.class); } public void testSimple() { doTest(); } private void doTest() { doTest(GoCreateWrapperTypeQuickFix.QUICKFIX_NAME, true); } @NotNull @Override protected String getBasePath() { return "inspections/anon-field"; } } ================================================ FILE: tests/com/goide/inspections/GoAssignmentToReceiverInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoCodeInsightFixtureTestCase; public class GoAssignmentToReceiverInspectionTest extends GoCodeInsightFixtureTestCase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoAssignmentToReceiverInspection.class); } public void testDoesNotPropagateToOtherCallsForNonPointerReceiver() { doTest("func (r MyType) foo() { r = 0 }"); } public void testDoesNotPropagateToOtherCallsForPointerReceiver() { doTest("func (r *MyType) foo() { r = 0 }"); } public void testNoFixForDereferencedPointerReceiver() { doTest("func (r *MyType) foo() { *r = 0 }"); } private void doTest(String code) { myFixture.configureByText("a.go", "package main; type MyType int; " + code); myFixture.checkHighlighting(); } } ================================================ FILE: tests/com/goide/inspections/GoDeferGoInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.SdkAware; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; @SdkAware public class GoDeferGoInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoDeferGoInspection.class); } public void testParens() { doTest(GoDeferGoInspection.UNWRAP_PARENTHESES_QUICK_FIX_NAME, true); } public void testTwiceParens() { doTest(GoDeferGoInspection.UNWRAP_PARENTHESES_QUICK_FIX_NAME, true); } public void testParensFunctionType() { doTest(GoDeferGoInspection.ADD_CALL_QUICK_FIX_NAME, true); } public void testLiteral() { doTestNoFix(GoDeferGoInspection.ADD_CALL_QUICK_FIX_NAME, true); } public void testFuncLiteral() { doTest(GoDeferGoInspection.ADD_CALL_QUICK_FIX_NAME, true); } public void testConversions() { myFixture.testHighlighting(getTestName(true) + ".go"); } public void testValid() { myFixture.testHighlighting(getTestName(true) + ".go"); } public void testDeferRecover() { doTest(GoDeferGoInspection.REPLACE_WITH_CORRECT_DEFER_RECOVER, true); } @NotNull @Override protected String getBasePath() { return "inspections/go-defer-function-call"; } } ================================================ FILE: tests/com/goide/inspections/GoEmptyDeclarationInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; public class GoEmptyDeclarationInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoEmptyDeclarationInspection.class); } public void testConstVoidDeclaration() { doTest(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testVarVoidDeclarationWithInnerComment() { doTestNoFix(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testNotVoidImportDeclaration() { doTestNoFix(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testImportVoidDeclarationWithUpperComment() { doTestNoFix(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testTypeVoidDeclaration() { doTest(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testTwoVoidImportsWithOneComment() { doTest(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testVarVoidDeclarationInFunction() { doTestNoFix(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } public void testVarVoidDeclarationNotInFunction() { doTest(GoEmptyDeclarationInspection.QUICK_FIX_NAME, true); } @NotNull @Override protected String getBasePath() { return "inspections/go-empty-declaration"; } } ================================================ FILE: tests/com/goide/inspections/GoHighlightingTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.goide.codeInsight.imports.GoImportOptimizerTest; import com.goide.inspections.unresolved.*; import com.goide.project.GoModuleLibrariesService; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import org.jetbrains.annotations.NotNull; import java.io.IOException; @SdkAware public class GoHighlightingTest extends GoCodeInsightFixtureTestCase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections( GoUnresolvedReferenceInspection.class, GoDuplicateFieldsOrMethodsInspection.class, GoUnusedImportInspection.class, GoUnusedVariableInspection.class, GoUnusedConstInspection.class, GoUnusedGlobalVariableInspection.class, GoUnusedFunctionInspection.class, GoUnusedExportedFunctionInspection.class, GoAssignmentToConstantInspection.class, GoDuplicateFunctionOrMethodInspection.class, GoDuplicateArgumentInspection.class, GoDuplicateReturnArgumentInspection.class, GoFunctionVariadicParameterInspection.class, GoVarDeclarationInspection.class, GoNoNewVariablesInspection.class, GoMissingReturnInspection.class, GoFunctionCallInspection.class, GoDeferGoInspection.class, GoReservedWordUsedAsNameInspection.class, GoImportUsedAsNameInspection.class, GoMultiplePackagesInspection.class, GoCgoInTestInspection.class, GoTestSignaturesInspection.class, GoAssignmentNilWithoutExplicitTypeInspection.class, GoRedeclareImportAsFunctionInspection.class, GoStructTagInspection.class, GoUsedAsValueInCondition.class, GoDeferInLoopInspection.class, GoCommentStartInspection.class, GoPlaceholderCountInspection.class, GoEmbeddedInterfacePointerInspection.class, GoUnderscoreUsedAsValueInspection.class, GoRangeIterationOnIllegalTypeInspection.class, GoUnusedParameterInspection.class, GoDirectAssignToStructFieldInMapInspection.class, GoInfiniteForInspection.class, GoAssignmentToReceiverInspection.class, GoInvalidStringOrCharInspection.class, GoMixedNamedUnnamedParametersInspection.class, GoAnonymousFieldDefinitionTypeInspection.class, GoStringAndByteTypeMismatchInspection.class ); } private void doTest() { myFixture.testHighlighting(true, false, false, getTestName(true) + ".go"); } @NotNull @Override protected String getBasePath() { return "highlighting"; } @Override protected boolean isWriteActionRequired() { return false; } public void testSimple() { doTest(); } public void testLabels() { doTest(); } public void testStruct() { doTest(); } public void testBoxes() { doTest(); } public void testRanges() { doTest(); } public void testSelector() { doTest(); } public void testComposite() { doTest(); } public void testVars() { doTest(); } public void testRecv() { doTest(); } public void testPointers() { doTest(); } public void testSlices() { doTest(); } public void testShortVars() { doTest(); } public void testReturns() { doTest(); } public void testRequest() { doTest(); } public void testStop() { doTest(); } public void testVarBlocks() { doTest(); } public void testBlankImport() { doTest(); } public void testVariadic() { doTest(); } public void testCheck() { doTest(); } public void testCheck_test() { doTest(); } public void testFuncCall() { doTest(); } public void testBuiltinFuncCalls() { doTest(); } public void testBackticks() { doTest(); } public void testConsts() { doTest(); } public void testFields() { doTest(); } public void testBlankFields() { doTest(); } public void testFuncLiteral() { doTest(); } public void testTypeLiterals() { doTest(); } public void testFuncType() { doTest(); } public void testTemplates() { doTest(); } public void testInterfaces() { doTest(); } public void testReceiverType() { doTest(); } public void testForRange() { doTest(); } public void testMismatch() { doTest(); } public void testStubParams() { doTest(); } public void testNil() { doTest(); } public void testAssignUsages() { doTest(); } public void testMethodExpr() { doTest(); } public void testVarToImport() { doTest(); } public void testCgotest() { doTest(); } public void testRedeclaredImportAsFunction(){ doTest(); } public void testStructTags() { doTest(); } public void testContinue() { doTest(); } public void testBreak() { doTest(); } public void testEqualinif() { doTest(); } public void testSpecTypes() { doTest(); } public void testFunctionTypes() { doTest(); } public void testGithubIssue2099() { doTest(); } public void testCyclicDefinition() { doTest(); } public void testEmbeddedInterfacePointer() { doTest(); } public void testPlaceholderCount() { doTest(); } public void testPlaceholderCountVet() { doTest(); } public void testTypeConversion() { doTest(); } public void testInit() { doTest(); } public void testMainWithWrongSignature() { doTest(); } public void testChan() { doTest(); } public void testIota() { doTest(); } public void testIota2() { doTest(); } public void testUnaryPointer() { doTest(); } public void testUnaryMinus() { doTest(); } public void testFileRead() { doTest(); } public void testLiteralValues() { doTest(); } public void testUnderscoreUsedAsValue() { doTest(); } public void testUnusedParameter() { doTest(); } public void testUnusedParameter_test() { doTest(); } public void testVoidFunctionUsedAsValue() { doTest(); } public void testIndexedStringAssign() { doTest(); } public void testStringSliceWithThirdIndex() { doTest(); } public void testSliceWithThirdIndex() { doTest(); } public void testAssignToStructFieldInMap() { doTest(); } public void testInfiniteFor() { doTest(); } public void testGh2147() { doTest(); } public void testAssignmentToReceiver() { doTest(); } public void testReservedWordUsedAsName() { doTest(); } public void testImportUsedAsName() { doTest(); } public void testMixedNamedUnnamedParameters() { doTest(); } public void testStringInStructSliceWithThirdIndex() { doTest(); } public void testAnonymousFieldDefinition() { doTest(); } public void testStringIndexIsByte() { doTest(); } public void testCodedImportString() { myFixture.addFileToProject("a/a.go", "package a\n const A = 3"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b\n import \"\\u0061\" \n" + "const my = a.A"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testDoNotResolveReceiverTypeToFunction() { myFixture.addFileToProject("pack1/a.go", "package foo; func functionInCurrentPackage() {}"); PsiFile file = myFixture.addFileToProject("pack1/b.go", "package foo; func (functionInCurrentPackage) method() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testAvoidDuplicatedUnusedImportReports() { myFixture.addFileToProject("pack1/a.go", "package foo;"); myFixture.addFileToProject("pack1/b.go", "package foo_test;"); myFixture.addFileToProject("pack2/a.go", "package foo;"); myFixture.addFileToProject("pack3/a.go", "package foo; func Hi() {}"); doTest(); } public void testCheckSamePackage_test() { myFixture.configureByText("a_test.go", "package check; func TestStringer(t *testing.T) {}"); doTest(); } public void testRelativeImportIgnoringDirectories() throws IOException { myFixture.getTempDirFixture().findOrCreateDir("to_import/testdata"); myFixture.getTempDirFixture().findOrCreateDir("to_import/.name"); myFixture.getTempDirFixture().findOrCreateDir("to_import/_name"); doTest(); } public void testImportWithSlashAtTheEnd() { myFixture.addFileToProject("a/pack/pack.go", "package pack; func Foo() {}"); PsiFile file = myFixture.addFileToProject("pack2/pack2.go", "package main; import \"a/pack/\"; import \"../a/pack/\"; func main() { pack.Foo() }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } @SuppressWarnings("ConstantConditions") public void testDoNotReportNonLastMultiResolvedImport() { myFixture.addFileToProject("root1/src/to_import/unique/foo.go", "package unique; func Foo() {}"); myFixture.addFileToProject("root1/src/to_import/shared/a.go", "package shared"); myFixture.addFileToProject("root2/src/to_import/shared/a.go", "package shared"); GoModuleLibrariesService.getInstance(myFixture.getModule()).setLibraryRootUrls(myFixture.findFileInTempDir("root1").getUrl(), myFixture.findFileInTempDir("root2").getUrl()); doTest(); PsiReference reference = myFixture.getFile().findReferenceAt(myFixture.getCaretOffset()); PsiElement resolve = reference.resolve(); assertInstanceOf(resolve, PsiDirectory.class); assertTrue(((PsiDirectory)resolve).getVirtualFile().getPath().endsWith("root1/src/to_import/shared")); GoModuleLibrariesService.getInstance(myFixture.getModule()).setLibraryRootUrls(myFixture.findFileInTempDir("root2").getUrl(), myFixture.findFileInTempDir("root1").getUrl()); reference = myFixture.getFile().findReferenceAt(myFixture.getCaretOffset()); resolve = reference.resolve(); assertInstanceOf(resolve, PsiDirectory.class); assertTrue(((PsiDirectory)resolve).getVirtualFile().getPath().endsWith("root2/src/to_import/shared")); } public void testLocalScope() { myFixture.configureByText("a.go", "package foo; func bar() {}"); myFixture.configureByText("b.go", "package foo; func init(){bar()}"); myFixture.checkHighlighting(); } public void testInnerTypesFromOtherPackage() { myFixture.configureByText("main.go", "package main; import \"io\"; type Outer struct { *io.LimitedReader };" + "func main() { _ = &Outer{LimitedReader: &io.LimitedReader{}, } }"); myFixture.checkHighlighting(); } public void testNoLocalResolveForTest() { myFixture.configureByText("a.go", "package i; type P struct { v1 int }"); myFixture .configureByText("b_test.go", "package i_test; import ( \".\" ); func f() { print(i.P{}.v1) }"); myFixture.checkHighlighting(); } public void testDuplicateFunctionsInOnePackage() { myFixture.configureByText("a.go", "package foo; func init() {bar()}; func bar() {};"); myFixture.configureByText("b.go", "//+build appengine\n\npackage foo; func init() {buzz()}; func buzz() {}"); myFixture.configureByText("c.go", "package foo; func init() {bar(); buzz();}; func bar() {}; func buzz() {}"); myFixture.checkHighlighting(); } public void testDuplicateFunctionsInDifferentPackages() { myFixture.configureByText("a.go", "package foo; func init() {bar()}; func bar() {};"); myFixture.configureByText("b_test.go", "package foo_test; func init() {bar(); buzz();}; func bar() {}; func buzz() {}"); myFixture.checkHighlighting(); } public void testDoNotSearchFunctionDuplicatesForNotTargetMatchingFiles() { myFixture.configureByText("a.go", "//+build appengine\n\npackage foo; func init() {buzz()}; func buzz() {}"); myFixture.configureByText("b.go", "package foo; func init() {buzz()}; func buzz() {}"); myFixture.checkHighlighting(); } public void testDuplicateMethodsInOnePackage() { myFixture.configureByText("a.go", "package main; type Foo int; func (f Foo) bar(a, b string) {}"); myFixture.configureByText("b.go", "//+build appengine\n\npackage main; func (a *Foo) bar() {};func (a *Foo) buzz() {}"); myFixture.configureByText("c.go", "package main; func (a *Foo) bar() {};func (a *Foo) buzz() {}"); myFixture.checkHighlighting(); } public void testDoNotSearchMethodDuplicatesForNotTargetMatchingFiles() { myFixture.configureByText("b.go", "//+build appengine\n\npackage main; func (a *Foo) bar() {}"); myFixture.configureByText("a.go", "package main; type Foo int; func (f Foo) bar(_, _ string) {}"); myFixture.checkHighlighting(); } public void testNoDuplicateMethodsInOnePackage() { myFixture.configureByText("a.go", "package main; type Foo int; func (f Foo) bar() {}"); myFixture.configureByText("b.go", "package main; type Baz int; func (f Baz) bar() {}"); myFixture.checkHighlighting(); } public void testInitInOnePackage() { myFixture.configureByText("a.go", "package foo; func init() {bar()}; func bar() {}"); myFixture.configureByText("b.go", "package foo; func init() {bar()}; func bar() {}; func init() {}"); myFixture.checkHighlighting(); } public void testMainInFooPackage() { myFixture.configureByText("a.go", "package foo; func main() {bar()}; func bar() {}"); myFixture.configureByText("b.go", "package foo; func main() {bar()}; func bar() {}"); myFixture.checkHighlighting(); } public void testMainInMainPackage() { myFixture.configureByText("a.go", "package main; func main() {bar()}; func bar() {}"); myFixture.configureByText("b.go", "package main; func main() {bar()}; func bar() {}"); myFixture.checkHighlighting(); } public void testUseNilWithoutExplicitType() { myFixture.configureByText("a.go", "package main; func main() { var x string = nil; _ = x; var y = nil; _ = y}"); myFixture.checkHighlighting(); } public void testPackageWithTestPrefix() { myFixture.addFileToProject("pack1/pack1_test.go", "package pack1_test; func Test() {}"); PsiFile file = myFixture.addFileToProject("pack2/pack2_test.go", "package pack2_test; import \"testing\"; func TestTest(*testing.T) {pack1_test.Test()}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testMethodOnNonLocalType() { VirtualFile file = myFixture.copyFileToProject(getTestName(true) + ".go", "method/nonlocaltype.go"); myFixture.configureFromExistingVirtualFile(file); GoImportOptimizerTest.resolveAllReferences(myFixture.getFile()); myFixture.checkHighlighting(); } public void testMethodOnNonLocalTypeInTheSameDirectory() { myFixture.addFileToProject("method/foo.go", "package a; type H struct {}"); PsiFile psiFile = myFixture.addFileToProject("method/foo_test.go", "package a_test;\n" + "func (H) Hello() {}"); myFixture.configureFromExistingVirtualFile(psiFile.getVirtualFile()); myFixture.checkHighlighting(); } public void testPackageWithTestPrefixNotInsideTestFile() { myFixture.addFileToProject("pack1/pack1.go", "package pack1_test; func Test() {}"); PsiFile file = myFixture.addFileToProject("pack2/pack2_test.go", "package pack2_test; import `pack1`; import \"testing\"; func TestTest(*testing.T) {pack1_test.Test()}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testBlankPackage() { myFixture.configureByText("a.go", "package _"); myFixture.checkHighlighting(); } public void testMultiplePackages() { myFixture.addFileToProject("a.go", "package a"); myFixture.configureByText("b.go", "package b"); myFixture.checkHighlighting(); } public void testMultiplePackagesWithIgnoredFile() { myFixture.addFileToProject("a.go", "// +build ignored\n\npackage a"); myFixture.addFileToProject(".c.go", "// package a"); myFixture.addFileToProject("_c.go", "// package a"); // Should be OK to have package b because package a has a non-matching // build tag. myFixture.configureByText("b.go", "package b"); myFixture.checkHighlighting(); } public void testMultiplePackagesWithDocumentationPackage() { myFixture.addFileToProject("a.go", "package documentation"); myFixture.configureByText("b.go", "package b"); myFixture.checkHighlighting(); } public void testDocumentationPackage() { myFixture.addFileToProject("a.go", "package a"); myFixture.configureByText("docs.go", "package documentation"); myFixture.checkHighlighting(); } public void testTestPackage() { myFixture.addFileToProject("a.go", "package a"); myFixture.configureByText("a_test.go", "package a_test"); myFixture.checkHighlighting(); } public void testCGOImportInTestFile() { myFixture.configureByText("a_test.go", "package a; import\"C\"; import\"C\";"); myFixture.checkHighlighting(); } public void testDeferInLoop() { doWeakTest(); } public void testDeferGo() { doWeakTest(); } public void testCommentStart() { doWeakTest(); } private long doWeakTest() {return myFixture.testHighlighting(true, false, true, getTestName(true) + ".go");} public void testDoNotHighlightCommentOfMainPackage() { myFixture.configureByText("a.go", "// Some comment\npackage main; func main() {}"); myFixture.checkHighlighting(true, false, true); } public void testCGOImportInNonTestFile() { myFixture.configureByText("a.go", "package a; import \"C\""); myFixture.checkHighlighting(); } public void testVendoringImportPaths() { myFixture.addFileToProject("vendor/vendoringPackage/v.go", "package vendoringPackage; func Hello() {}"); myFixture.addFileToProject("subPackage/vendor/subVendoringPackage/v.go", "package subVendoringPackage; func Hello() {}"); doTest(); } public void testVendoredBuiltinImport() { myFixture.addFileToProject("vendor/builtin/builtin.go", "package builtin; func Hello() {}"); myFixture.configureByText("a.go", "package a; import _ `builtin`"); myFixture.checkHighlighting(); } public void testDuplicatePackageAlias() { myFixture.addFileToProject("pack1/pack1.go", "package pack1; func Foo() {}"); myFixture.addFileToProject("pack2/pack2.go", "package pack2"); PsiFile file = myFixture.addFileToProject("pack3/pack3.go", "package main; import p \"pack1\"; import p \"pack2\"; func main() { p.Foo() }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testDuplicatePackageImport() { myFixture.addFileToProject("pack/pack1.go", "package pack; func Foo() {}"); PsiFile file = myFixture.addFileToProject("pack3/pack3.go", "package main; import \"pack\"; import \"pack\"; func main() { pack.Foo() }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testDuplicateFinalPackageComponent() { myFixture.addFileToProject("a/pack/pack1.go", "package pack; func Foo() {}"); myFixture.addFileToProject("b/pack/pack2.go", "package pack"); PsiFile file = myFixture.addFileToProject("pack3/pack3.go", "package main; import \"a/pack\"\n" + "import \"b/pack\"\n" + "func main() { pack.Foo() }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testIgnoredBuildTag() { myFixture.addFileToProject("a/pack1.go", "package a; func Foo() {}"); myFixture.addFileToProject("a/pack2.go", "// +build ignored\n\npackage main"); myFixture.addFileToProject("b/pack1.go", "package b; func Bar() {}"); myFixture.addFileToProject("b/pack2.go", "// +build ignored\n\npackage main"); // There should be no errors: package main exists in the a/ and b/ // directories, but it is not imported as it has a non-matching build tag. // For more details see https://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues/1858#issuecomment-139794391. PsiFile file = myFixture.addFileToProject("c/pack1.go", "package main; import \"a\"; import \"b\"; func main() { a.Foo(); b.Bar(); }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testImportUnderscore() { myFixture.addFileToProject("a/pack/pack1.go", "package pack; func Foo() {}"); myFixture.addFileToProject("b/pack/pack2.go", "package pack"); myFixture.addFileToProject("c/pack/pack3.go", "package whatever; func Bar() {}"); myFixture.addFileToProject("d/pack/pack4.go", "package another; func Baz() {}"); PsiFile file = myFixture.addFileToProject("pack3/pack3.go", "package main; import _ \"a/pack\"; import _ \"b/pack\"; import . \"c/pack\"; import . \"d/pack\"; func main() { Bar(); Baz() }"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } } ================================================ FILE: tests/com/goide/inspections/GoInspectionUtilTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoBuiltinCallExpr; import com.goide.psi.GoCallExpr; import com.goide.psi.GoExpression; import com.goide.psi.GoStringLiteral; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoInspectionUtilTest extends GoCodeInsightFixtureTestCase { private void doTest(@NotNull String text, @NotNull Class aClass, int expected) { myFixture.configureByText("a.go", text); PsiElement element = myFixture.getFile().findElementAt(myFixture.getEditor().getCaretModel().getOffset()); T callExpr = PsiTreeUtil.getParentOfType(element, aClass); assertEquals(expected, GoInspectionUtil.getExpressionResultCount(callExpr)); } public void testBuiltinCallResultCount() { String text = "package a; func b() {\n b := make(int, 10); _ = b }"; doTest(text, GoBuiltinCallExpr.class, 1); } public void testMultipleResultCount() { String text = "package a; func vals() (int, int) {\n return 42, 0}; func b() {\n vals()}"; doTest(text, GoCallExpr.class, 2); } public void testLiteralResultCount() { String text = "package a; func b() {\n a := \"hello world\"}"; doTest(text, GoStringLiteral.class, 1); } } ================================================ FILE: tests/com/goide/inspections/GoInvalidPackageImportInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.SdkAware; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.quickfix.GoQuickFixTestBase; import com.goide.sdk.GoSdkService; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.psi.PsiFile; import com.intellij.util.containers.ContainerUtil; import java.util.Collection; @SdkAware public class GoInvalidPackageImportInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoInvalidPackageImportInspection.class); } public void testImportBuiltinPackage() { myFixture.addFileToProject("builtin/hello.go", "package builtin"); myFixture.configureByText("a.go", "package pack; import `builtin`"); myFixture.checkHighlighting(); } public void testImportBuiltinSubPackage() { myFixture.addFileToProject("builtin/hello.go", "package builtin"); myFixture.addFileToProject("builtin/sub/hello.go", "package builtin"); myFixture.configureByText("a.go", "package pack; import `builtin/sub`"); myFixture.checkHighlighting(); } public void testImportVendoredBuiltin() { myFixture.addFileToProject("vendor/builtin/hello.go", "package builtin"); myFixture.configureByText("a.go", "package pack; import `builtin`"); myFixture.checkHighlighting(); } public void testImportUnreachableVendoredPackage() { myFixture.addFileToProject("pack/vendor/foo/a.go", "package foo"); myFixture.configureByText("a.go", "package bar\n" + "import _ `pack/vendor/unresolved`\n" + "import _ `pack/vendor/foo`"); myFixture.checkHighlighting(); assertContainsElements(getIntentionNames(), "Disable vendoring experiment support in module 'light_idea_test_case'", "Delete import"); assertDoesntContain(getIntentionNames(), "Replace with `foo`"); } public void testReplaceImportWithVendoredPath() { myFixture.addFileToProject("vendor/foo/a.go", "package foo"); myFixture.configureByText("a.go", "package pack\n" + "import _ `pack/vendor/unresolved`\n" + "import _ `vendor/foo`"); myFixture.checkHighlighting(); assertContainsElements(getIntentionNames(), "Disable vendoring experiment support in module 'light_idea_test_case'", "Delete import"); myFixture.launchAction(myFixture.findSingleIntention("Replace with 'foo'")); myFixture.checkResult("package pack\n" + "import _ `pack/vendor/unresolved`\n" + "import _ `foo`"); } public void testDoNoSuggestDisablingVendoringOnGo1_7() { GoSdkService.setTestingSdkVersion("1.7", getTestRootDisposable()); myFixture.addFileToProject("vendor/foo/a.go", "package foo"); myFixture.configureByText("a.go", "package pack\n" + "import _ `pack/vendor/unresolved`\n" + "import _ `vendor/foo`"); myFixture.checkHighlighting(); assertDoesntContain(getIntentionNames(), "Disable vendoring experiment support in module 'light_idea_test_case'"); } public void testWithDisabledVendoring() { disableVendoring(); myFixture.addFileToProject("pack/vendor/foo/a.go", "package foo"); myFixture.addFileToProject("vendor/foo/a.go", "package foo"); myFixture.configureByText("a.go", "package pack\n" + "import _ `pack/vendor/unresolved`\n" + "import _ `pack/vendor/foo/a`\n" + "import _ `vendor/foo/a`"); myFixture.checkHighlighting(); } public void testVendorInsideVendorShouldBeUnreachable() { myFixture.addFileToProject("vendor/foo/a.go", "package foo"); myFixture.addFileToProject("vendor/foo/vendor/bar/a.go", "package bar"); myFixture.configureByText("a.go", "package bar\n" + "import _ `foo`\n" + "import _ `foo/vendor/bar`"); myFixture.checkHighlighting(); } public void testImportMainPackage() { myFixture.addFileToProject("foo/main/main.go", "package main"); myFixture.addFileToProject("bar/main/main_test.go", "package main_test"); myFixture.addFileToProject("buzz/main/other_main_test.go", "package main"); myFixture.addFileToProject("not_program/main/other_main.go", "package main_test"); myFixture.addFileToProject("foo/not_main/main.go", "package main"); myFixture.addFileToProject("bar/not_main/main_test.go", "package main_test"); myFixture.addFileToProject("buzz/not_main/other_main_test.go", "package main"); myFixture.addFileToProject("not_program/not_main/other_main.go", "package main_test"); myFixture.configureByText("a.go", "package a\n" + "import `foo/main`\n" + "import `bar/main`\n" + "import `buzz/main`\n" + "import `not_program/main`\n" + "import `foo/not_main`\n" + "import `bar/not_main`\n" + "import `buzz/not_main`\n" + "import `not_program/not_main`"); myFixture.checkHighlighting(); } public void testImportMainPackageInTest() { myFixture.addFileToProject("foo/main/main.go", "package main"); myFixture.configureByText("a_test.go", "package a\nimport `foo/main`"); myFixture.checkHighlighting(); } public void testInternalPackageOn1_2_SDK() { myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); myFixture.configureByText("a.go", "package src\n" + "import (\n" + " `internal`\n" + " `sub/internal`\n" + " `net/internal`\n" + ")"); myFixture.checkHighlighting(); } public void testInternalPackageOn1_4_SDK() { GoSdkService.setTestingSdkVersion("1.4", getTestRootDisposable()); myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); myFixture.configureByText("a.go", "package src\n" + "import (\n" + " `internal`\n" + " `sub/internal`\n" + " `net/internal`\n" + ")"); myFixture.checkHighlighting(); } public void testInternalPackageOn1_5_SDK() { GoSdkService.setTestingSdkVersion("1.5", getTestRootDisposable()); myFixture.addFileToProject("internal/internal.go", "package internalPackage; func InternalFunction() {}"); myFixture.addFileToProject("sub/internal/internal.go", "package subInternalPackage; func InternalFunction() {}"); myFixture.configureByText("a.go", "package src\n" + "import (\n" + " `internal`\n" + " `sub/internal`\n" + " `net/internal`\n" + ")"); myFixture.checkHighlighting(); } public void testImportPackageWithoutBuildableSource() { PsiFile file = myFixture.addFileToProject("withSources/a.go", "package withSources"); myFixture.addFileToProject("withIgnoredFiles/a.go", "package documentation"); myFixture.addFileToProject("withIgnoredFiles/.b.go", "package withIgnoredFiles"); myFixture.addFileToProject("withIgnoredFiles/_b.go", "package withIgnoredFiles"); WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { //noinspection ConstantConditions file.getParent().getParent().createSubdirectory("withoutSources"); }); myFixture.configureByText("a.go", "package pack\n" + "import `withSources`\n" + "import `withIgnoredFiles`\n" + "import `withoutSources`\n" + "import _ `withoutSources`\n" + "import `unresolved`\n"); myFixture.checkHighlighting(); applySingleQuickFix(GoDeleteImportQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package pack\n" + "import `withSources`\n" + "import `withIgnoredFiles`\n" + "import `withoutSources`\n" + "import `unresolved`\n"); } public void testImportAbsolutePath() { myFixture.configureByText("a.go", "package a; import `/fmt`"); myFixture.checkHighlighting(); assertEmpty(myFixture.filterAvailableIntentions("go get")); applySingleQuickFix(GoDeleteImportQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package a; "); } public void testImportTestDataDirectory() { myFixture.addFileToProject("pack/testdata/pack/foo.go", "package test"); myFixture.configureByText("a.go", "package a\n" + "import `pack/testdata/pack`\n" + "import `doc/testdata`"); myFixture.checkHighlighting(); applySingleQuickFix(GoDeleteImportQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package a\nimport `pack/testdata/pack`\n"); } public void testImportCWithAlias() { myFixture.configureByText("a.go", "package t; import `C`; import alias `C`;"); myFixture.checkHighlighting(); applySingleQuickFix(GoInvalidPackageImportInspection.DELETE_ALIAS_QUICK_FIX_NAME); myFixture.checkResult("package t; import `C`; import `C`;"); } public void testImportCWithDot() { myFixture.configureByText("a.go", "package t; import `C`; import . `C`;"); myFixture.checkHighlighting(); applySingleQuickFix(GoInvalidPackageImportInspection.DELETE_ALIAS_QUICK_FIX_NAME); myFixture.checkResult("package t; import `C`; import `C`;"); } private Collection getIntentionNames() { return ContainerUtil.map(myFixture.getAvailableIntentions(), IntentionAction::getText); } } ================================================ FILE: tests/com/goide/inspections/GoReceiverNamesInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoCodeInsightFixtureTestCase; public class GoReceiverNamesInspectionTest extends GoCodeInsightFixtureTestCase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoReceiverNamesInspection.class); } public void testThis() { doTest("func (this MyType) asd() {}"); } public void testNoFix() { doTest("func (myType MyType) asd() {}"); } private void doTest(String code) { myFixture.configureByText("a.go", "package main; type MyType int; " + code); myFixture.checkHighlighting(); } } ================================================ FILE: tests/com/goide/inspections/GoRedundantBlankArgInRangeInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; public class GoRedundantBlankArgInRangeInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoRedundantBlankArgInRangeInspection.class); } // Tests ranges public void testRangeSimplifyWithOneBlankArg() { doTest(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithOneArg() { doTestNoFix(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithTwoBlankArgs() { doTest(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithTwoArgs() { doTestNoFix(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithOneBlankAndOneNotBlankArgs() { doTestNoFix(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithOneNotBlankAndOneBlankArgs() { doTest(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } public void testRangeSimplifyWithVarAssign() { doTest(GoRedundantBlankArgInRangeInspection.DELETE_BLANK_ARGUMENT_QUICK_FIX_NAME, true); } @NotNull @Override protected String getBasePath() { return "inspections/go-simplify"; } } ================================================ FILE: tests/com/goide/inspections/GoRedundantSecondIndexInSlicesInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.SdkAware; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; @SdkAware public class GoRedundantSecondIndexInSlicesInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoRedundantSecondIndexInSlicesInspection.class); } public void testSlice() { doTest(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } public void testSliceWithLenAnotherArray() { doTestNoFix(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } public void testSliceWithOnlySecondIndex() { doTest(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } public void testSliceWithStructIndex() { doTestNoFix(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } public void testSliceWithThreeIndexes() { doTestNoFix(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } public void testSliceWithRedeclaredLen() { doTestNoFix(GoRedundantSecondIndexInSlicesInspection.DELETE_REDUNDANT_INDEX_QUICK_FIX_NAME, true); } @NotNull @Override protected String getBasePath() { return "inspections/go-simplify"; } } ================================================ FILE: tests/com/goide/inspections/GoRedundantTypeDeclInCompositeLitTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; public class GoRedundantTypeDeclInCompositeLitTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoRedundantTypeDeclInCompositeLit.class); } @Override protected boolean isWriteActionRequired() { return false; } //Test Composite literals public void testCompositeLitWithOneSimpleRedundantTypeDecl() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithKeysAndSimpleRedundantTypeDecl() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithInterface() { doTestNoFix(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithArrays() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithArraysInBrackets() { doTestNoFix(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithMap() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } /*public void testCompositeLitWithInsertedArrays () { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithStruct() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithMapOfStruct() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithTwoDimensionalArray() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); }*/ //Test Composite literals with pointers *T == &T public void testCompositeLitWithPointers() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithPointersNoFix() { doTestNoFix(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } /*public void testCompositeLitWithPointerAndStructAndInsertedElement() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); } public void testCompositeLitWithMapWithPointerAndStruct() { doTest(GoRedundantTypeDeclInCompositeLit.DELETE_TYPE_DECLARATION_QUICK_FIX_NAME, true); }*/ @NotNull @Override protected String getBasePath() { return "inspections/go-simplify"; } } ================================================ FILE: tests/com/goide/inspections/GoSelfImportInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.quickfix.GoDeleteImportQuickFix; import com.goide.quickfix.GoQuickFixTestBase; import com.intellij.psi.PsiFile; public class GoSelfImportInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoSelfImportInspection.class); } public void testRemoveSelfImport() { PsiFile file = myFixture.addFileToProject("path/a.go", "package pack;" + "import \"path\""); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); applySingleQuickFix(GoDeleteImportQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package pack;"); } public void testRemoveRelativeSelfImport() { myFixture.configureByText("a.go", "package pack;import \".\""); myFixture.checkHighlighting(); applySingleQuickFix(GoDeleteImportQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package pack;"); } public void testDoNotConsiderImportFromTestPackageAsSelfImport() { PsiFile file = myFixture.addFileToProject("path/a_test.go", "package pack_test; import \"path\""); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } public void testVendoringSelfImport() { PsiFile file = myFixture.addFileToProject("vendor/vendorPackage/a.go", "package vendorPackage;" + "import \"vendorPackage\""); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); myFixture.checkHighlighting(); } } ================================================ FILE: tests/com/goide/inspections/GoSpellcheckingTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.spellchecker.inspections.SpellCheckingInspection; import org.jetbrains.annotations.NotNull; public class GoSpellcheckingTest extends GoCodeInsightFixtureTestCase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(new SpellCheckingInspection()); } public void testVariableName() throws Exception { doTest(); } public void testFunctionName() throws Exception { doTest(); } public void testSuppressed() throws Exception { doTest(); } private void doTest() { myFixture.testHighlighting(false, false, true, getTestName(true) + ".go"); } @NotNull @Override protected String getBasePath() { return "spellchecker"; } } ================================================ FILE: tests/com/goide/inspections/GoStructInitializationInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.SdkAware; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; @SdkAware public class GoStructInitializationInspectionTest extends GoQuickFixTestBase { private GoStructInitializationInspection myInspectionTool = new GoStructInitializationInspection(); private boolean myDefaultReportLocalStructs; @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(myInspectionTool); myDefaultReportLocalStructs = myInspectionTool.reportLocalStructs; } @Override protected void tearDown() throws Exception { myInspectionTool.reportLocalStructs = myDefaultReportLocalStructs; super.tearDown(); } public void testUninitializedStructWithLocal() { doTest(true); } public void testUninitializedStructImportedOnly() { doTest(false); } public void testQuickFix() { doTest(GoStructInitializationInspection.REPLACE_WITH_NAMED_STRUCT_FIELD_FIX_NAME, true); } private long doTest(boolean allowLocalStructs) { myInspectionTool.reportLocalStructs = allowLocalStructs; return myFixture.testHighlighting(true, false, true, getTestName(true) + ".go"); } @NotNull @Override protected String getBasePath() { return "inspections/go-struct-initialization"; } } ================================================ FILE: tests/com/goide/inspections/GoTestSignaturesInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.SdkAware; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; @SdkAware public class GoTestSignaturesInspectionTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoTestSignaturesInspection.class); } @NotNull @Override protected String getBasePath() { return "inspections/test-signatures"; } private void doTest() { String testName = getTestName(true); myFixture.configureByFile(testName + "_test.go"); myFixture.checkHighlighting(); applySingleQuickFix("Fix signature"); myFixture.checkResultByFile(testName + "_test-after.go"); } public void testExampleNonEmptySignature() { doTest(); } public void testTestNoTestingImport() { doTest(); } public void testTestWrongTestingAlias() { doTest(); } public void testTestLocalTestingImport() { doTest(); } public void testTestMain() { doTest(); } public void testBenchmark() { doTest(); } public void testExampleWithReturnValue() { doTest(); } public void testTestWithReturnValue() { doTest(); } } ================================================ FILE: tests/com/goide/inspections/GoUnusedLabelInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections; import com.goide.inspections.unresolved.GoUnusedLabelInspection; import com.goide.quickfix.GoQuickFixTestBase; import com.goide.quickfix.GoRenameToBlankQuickFix; public class GoUnusedLabelInspectionTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedLabelInspection.class); } public void testSimple() { myFixture.testHighlighting(getTestName(true) + ".go"); } public void testDeleteLabelFix() { doTest("Delete label 'UnusedLabel'", true); } public void testRenameToBlankFix() { doTest(GoRenameToBlankQuickFix.NAME, true); } @Override protected String getBasePath() { return "inspections/unused-label"; } } ================================================ FILE: tests/com/goide/inspections/suppression/GoSuppressionFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.inspections.suppression; import com.goide.inspections.GoMultiplePackagesInspection; import com.goide.inspections.GoUnusedImportInspection; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import com.goide.inspections.unresolved.GoUnusedGlobalVariableInspection; import com.goide.inspections.unresolved.GoUnusedVariableInspection; import com.goide.quickfix.GoQuickFixTestBase; import org.jetbrains.annotations.NotNull; public class GoSuppressionFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedImportInspection.class); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); myFixture.enableInspections(GoUnusedGlobalVariableInspection.class); myFixture.enableInspections(GoUnusedVariableInspection.class); myFixture.enableInspections(GoMultiplePackagesInspection.class); } public void testImportStatement() { doTest("Suppress for import"); } public void testFirstImportStatement() { doTest("Suppress for import"); } public void testFunctionSuppressionFix() { doTest("Suppress for function"); } public void testFunctionSuppressionFixWithExistingComment() { doTest("Suppress for function"); } public void testStatementSuppressionFix() { doTest("Suppress for statement"); } public void testStatementSuppressionFixWithExistingComment() { doTest("Suppress for statement"); } public void testSwitchCaseSuppressionFix() { doTest("Suppress all inspections for case"); } public void testSwitchCaseSuppressionFixWithExistingComment() { doTest("Suppress all inspections for case"); } public void testSelectCaseSuppressionFix() { doTest("Suppress all inspections for case"); } public void testSelectCaseSuppressionFixWithExistingComment() { doTest("Suppress all inspections for case"); } public void testVariableDeclarationSuppressionFix() { doTest("Suppress for variable"); } public void testVariableDeclarationSuppressionFixWithExistingComment() { doTest("Suppress for variable"); } public void testFunctionAllSuppressionFix() { doTest("Suppress all inspections for function"); } public void testFunctionAllSuppressionFixWithExistingComment() { doTest("Suppress all inspections for function"); } public void testStatementAllSuppressionFix() { doTest("Suppress all inspections for statement"); } public void testStatementAllSuppressionFixWithExistingComment() { doTest("Suppress all inspections for statement"); } public void testSwitchCaseAllSuppressionFix() { doTest("Suppress all inspections for case"); } public void testSwitchCaseAllSuppressionFixWithExistingComment() { doTest("Suppress all inspections for case"); } public void testSelectCaseAllSuppressionFix() { doTest("Suppress all inspections for case"); } public void testSelectCaseAllSuppressionFixWithExistingComment() { doTest("Suppress all inspections for case"); } public void testVariableDeclarationAllSuppressionFix() { doTest("Suppress all inspections for variable"); } public void testVariableDeclarationAllSuppressionFixWithExistingComment() { doTest("Suppress all inspections for variable"); } public void testInnerVariableDeclarationSuppressionFix() { doTestNoFix("Suppress for variable"); } public void testInnerVariableDeclarationSuppressionFix2() { doTest("Suppress for statement"); } public void testInnerVariableDeclarationSuppressionFix3() { doTest("Suppress for function"); } public void testCommClauseStatementSuppressionFix() { doTest("Suppress all inspections for statement"); } public void testPackageClause() { myFixture.configureByText("a.go", "package somePackage"); doTest("Suppress for package statement"); } public void testPackageClauseSuppressAll() { myFixture.configureByText("a.go", "package somePackage"); doTest("Suppress all inspections for package statement"); } public void testSuppressedNestedSelect() { myFixture.testHighlighting(getTestName(true) + ".go"); } @NotNull @Override protected String getBasePath() { return "inspections/suppression/fix"; } @Override protected void doTest(@NotNull String quickFixName) { super.doTest(quickFixName); myFixture.testHighlighting(String.format("%s-after-highlighting.go", getTestName(true))); } } ================================================ FILE: tests/com/goide/intentions/GoAddFunctionBlockIntentionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.intentions; import com.goide.quickfix.GoQuickFixTestBase; public class GoAddFunctionBlockIntentionTest extends GoQuickFixTestBase { public void testSimple() { doTest(GoAddFunctionBlockIntention.NAME, true); } @Override protected String getBasePath() { return "intentions/add-missing-body"; } } ================================================ FILE: tests/com/goide/lexer/GoLexerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.lexer; import com.intellij.lexer.Lexer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.testFramework.LexerTestCase; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; public class GoLexerTest extends LexerTestCase { private static final String PATH = "testData/lexer"; public void testBasicTypes() { doTest(); } public void testConstants() { doTest(); } public void testFor() { doTest(); } public void testFunctionArguments() { doTest(); } public void testHelloWorld() { doTest(); } public void testIf() { doTest(); } public void testImports() { doTest(); } public void testMultipleResult() { doTest(); } public void testNamedResult() { doTest(); } public void testPointers() { doTest(); } public void testRangeFor() { doTest(); } public void testSlices() { doTest(); } public void testStructs() { doTest(); } public void testVariables() { doTest(); } public void testEscapedQuote() { doTest(); } public void testUtf16() { doTest(); } public void testCouldNotMatch() { doTest(); } private void doTest() { try { String text = FileUtil.loadFile(new File("./" + PATH + "/" + getTestName(true) + ".go"), CharsetToolkit.UTF8); String actual = printTokens(StringUtil.convertLineSeparators(text.trim()), 0); assertSameLinesWithFile(new File(PATH + "/" + getTestName(true) + ".txt").getAbsolutePath(), actual); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull @Override protected Lexer createLexer() { return new GoLexer(); } @NotNull @Override protected String getDirPath() { return "../" + PATH; } } ================================================ FILE: tests/com/goide/marker/GoRecursiveMethodCallMarkerInfoTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.marker; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.icons.AllIcons; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoRecursiveMethodCallMarkerInfoTest extends GoCodeInsightFixtureTestCase { public void testRecursive() { doTest(); } public void testGo() { doTest(); } @NotNull @Override protected String getBasePath() { return "marker"; } private void doTest() { myFixture.configureByFile(getTestName(false) + ".go"); List textList = ContainerUtil.newArrayList(); for (GutterMark gutter : myFixture.findGuttersAtCaret()) { String text = gutter.getTooltipText(); textList.add(text); if ("Recursive call".equals(text) && AllIcons.Gutter.RecursiveMethod.equals(gutter.getIcon())) return; } fail("Not found gutter mark: " + "Recursive call" + " " + AllIcons.Gutter.RecursiveMethod + "\nin\n" + StringUtil.join(textList, "\n")); } } ================================================ FILE: tests/com/goide/parser/GoParseAndConsumeTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.parser; import com.goide.GoParserDefinition; import com.intellij.util.indexing.IndexingDataKeys; public class GoParseAndConsumeTest extends GoParserTestBase { public GoParseAndConsumeTest() { super("parser", "go", new GoParserDefinition()); } public void testTypeInBlock() throws Exception { doTest(); } protected void doTest() throws Exception { String name = getTestName(); String text = loadFile(name + "." + myFileExt); myFile = createPsiFile(name, text); myFile.putUserData(IndexingDataKeys.VIRTUAL_FILE, myFile.getVirtualFile()); ensureParsed(myFile); checkResult(name, myFile); } } ================================================ FILE: tests/com/goide/parser/GoParserTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.parser; import com.goide.GoParserDefinition; public class GoParserTest extends GoParserTestBase { public GoParserTest() { super("parser", "go", new GoParserDefinition()); } public void testError() { doTest(true); } public void testWriter() { doTest(true); } public void testPrimer() { doTest(true); } public void testTypes() { doTest(true); } public void testStr2Num() { doTest(true); } public void testCars() { doTest(true); } public void testIfWithNew() { doTest(true); } public void testRanges() { doTest(true); } public void testIncompleteRanges() { doTest(false); } public void testTorture() { doTest(true); } public void testLiteralValues() { doTest(true); } public void testLiteralValuesElse() { doTest(true); } public void testIfComposite() { doTest(true); } public void testArrayTypes() { doTest(true); } public void testArrayTypesInRanges() { doTest(true); } public void testIf() { doTest(false); } public void testSimple() { doTest(false); } public void testRecover() { doTest(false); } public void testRecover2() { doTest(false); } public void testRecover3() { doTest(false); } public void testMethodExpr() { doTest(false); } public void testLabels() { doTest(false); } public void testBlockRecover() { doTest(false); } public void testMethodWithoutReceiverIdentifier() { doTest(false); } public void testExpressionPerformance() { doTest(false); } public void testElementRecover() { doTest(false); } public void testChanRecover() { doTest(false); } public void testMapLiteralRecover() { doTest(false); } public void testPlusPlusRecover() { doTest(false); } public void testTypeComma() { doTest(false); } public void testIncDec() { doTest(false); } public void testIncompleteTypeDeclaration() { doTest(false); } public void testIncompleteVarDeclaration() { doTest(false); } } ================================================ FILE: tests/com/goide/parser/GoParserTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.parser; import com.intellij.core.CoreApplicationEnvironment; import com.intellij.lang.LanguageExtensionPoint; import com.intellij.lang.ParserDefinition; import com.intellij.openapi.extensions.Extensions; import com.intellij.testFramework.ParsingTestCase; import org.jetbrains.annotations.NotNull; public abstract class GoParserTestBase extends ParsingTestCase { public GoParserTestBase(String dataPath, String fileExt, ParserDefinition... definitions) {super(dataPath, fileExt, definitions);} @NotNull @Override protected String getTestDataPath() { return "testData"; } @Override protected boolean skipSpaces() { return true; } @Override protected void doTest(boolean checkErrors) { super.doTest(true); if (checkErrors) { assertFalse( "PsiFile contains error elements", toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement") ); } } @Override protected void setUp() throws Exception { super.setUp(); CoreApplicationEnvironment.registerExtensionPoint( Extensions.getRootArea(), "com.intellij.lang.braceMatcher", LanguageExtensionPoint.class); } } ================================================ FILE: tests/com/goide/psi/GoFileTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoCodeInsightFixtureTestCase; public class GoFileTest extends GoCodeInsightFixtureTestCase { public void testRetrieveBuildFlags() { myFixture.configureByText("a.go", "// Copyright 2009 The Go Authors. All rights reserved.\n" + "// Use of this source code is governed by a BSD-style\n" + "// license that can be found in the LICENSE file.\n" + "\n" + "// +build darwin dragonfly\n" + "\n" + "package net\n"); assertEquals("darwin dragonfly", ((GoFile)myFixture.getFile()).getBuildFlags()); } public void testRetrieveMultipleBuildFlags() { myFixture.configureByText("a.go", "// +build openbsd windows\n" + "// +build linux\n" + "\n" + "package net\n"); assertEquals("openbsd windows|linux", ((GoFile)myFixture.getFile()).getBuildFlags()); } public void testRetrieveBuildFlagsWithoutNewLineAfter() { myFixture.configureByText("a.go", "// Copyright 2009 The Go Authors. All rights reserved.\n" + "// Use of this source code is governed by a BSD-style\n" + "// license that can be found in the LICENSE file.\n" + "\n" + "// +build freebsd linux\n" + "package net\n"); assertNull(((GoFile)myFixture.getFile()).getBuildFlags()); } public void testPackageNameOfTestFile() { myFixture.configureByText("foo_test.go", "package foo_test"); assertEquals("foo_test", ((GoFile)myFixture.getFile()).getPackageName()); } public void testPackageNameOfNonTestPackageInTestFile() { myFixture.configureByText("foo_test.go", "package fooa"); assertEquals("fooa",((GoFile)myFixture.getFile()).getPackageName()); } public void testPackageNameOfTestPackageInNonTestFile() { myFixture.configureByText("foo.go", "package foo_test"); assertEquals("foo_test", ((GoFile)myFixture.getFile()).getPackageName()); } } ================================================ FILE: tests/com/goide/psi/GoImportListTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.openapi.command.WriteCommandAction; import org.jetbrains.annotations.NotNull; public class GoImportListTest extends GoCodeInsightFixtureTestCase { public void testAddImportToEmptyList() { doAddImportTest(); } public void testAddImportToListWithMultiSpecDeclaration() { doAddImportTest(); } public void testAddImportToListWithSingleSpecDeclaration() { doAddImportTest(); } public void testAddImportToListWithSingleSpecDeclarationWithParens() { doAddImportTest(); } public void testAddImportToEmptyListBeforeFunction() { doAddImportTest(); } public void testAddImportBeforeFunction() { doAddImportTest(); } public void testDoNotModifyCImport_1() { doAddImportTest(); } public void testDoNotModifyCImport_2() { doAddImportTest(); } public void testInvalidImport() { doAddImportTest(); } public void testInvalidImport2() { doAddImportTest(); } private void doAddImportTest() { myFixture.configureByFile(getTestName(true) + ".go"); WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> { ((GoFile)myFixture.getFile()).addImport("package/path", null); }); myFixture.checkResultByFile(getTestName(true) + "_after.go"); } @NotNull @Override protected String getBasePath() { return "psi/importDeclaration"; } } ================================================ FILE: tests/com/goide/psi/GoReadWriteAccessTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import static com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access.*; public class GoReadWriteAccessTest extends GoCodeInsightFixtureTestCase { public void testAssignment() { doTest("foo = 1", Write); } public void testSimpleStatement() { doTest("foo", Read); } public void testIncDec() { doTest("foo++", Write); } public void testPlusAssign() { doTest("foo += 1", ReadWrite); } public void testParenthesisExpression() { doTest("(foo) = 2", Write); } public void testPointer() { doTest("(*foo) = 2", Write); } public void testLeftPartOfSelectorExpressionInAssignment() { doTest("foo.bar.baz = 1", Read); } public void testLeftPartOfSelectorExpressionInAssignment_1() { doTest("foo.bar.baz = 1", Read); } public void testRightPartOfSelectorExpressionInAssignment() { doTest("foo.bar.baz = 1", Write); } public void testRangeLeftExpression() { doTest("for foo = range bar {\n}", Write); } public void testRangeLeftExpression_1() { doTest("for (*foo) = range bar {\n}", Write); } public void testRangeRightExpression() { doTest("for foo = range bar {\n}", Read); } public void testRangeRightExpression_1() { doTest("for foo := range bar {\n}", Read); } public void testRangeRightExpression_2() { doTest("for foo = range (*bar) {\n}", Read); } public void testSendRead() { doTest("a := <- channel", Read); } public void testSendWrite() { doTest("channel <- a", Write); } public void testCallExpression() { doTest("fmt.Println(a)", Read); } public void testRecvStatementWrite() { doTest("select {\n\tcase foo = bar:\n}", Write); } public void testRecvStatementRead() { doTest("select {\n\tcase foo = bar:\n}", Read); } public void testSendStatementInCaseWrite() { doTest("select {\n\tcase (*foo) <- bar:\n}", ReadWrite); } public void testSendStatementInCaseRead() { doTest("select {\n\tcase foo <- (*bar):\n}", Read); } public void testFieldInInitializer() { myFixture.configureByText("a.go", "package main\n" + "type aStruct struct {\n" + "\taField string\n" + "}\n" + "func newStruct() aStruct {\n" + "\treturn aStruct{\n" + "\t\taField: \"a value\",\n" + "\t}\n" + "}"); PsiElement element = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); GoFieldName goFieldName = PsiTreeUtil.getNonStrictParentOfType(element, GoFieldName.class); assertNotNull(goFieldName); //noinspection ConstantConditions assertEquals(Write, ReadWriteAccessDetector.findDetector(goFieldName.getReference().resolve()).getExpressionAccess(goFieldName)); } private void doTest(@NotNull String expressionText, @NotNull ReadWriteAccessDetector.Access expectedAccess) { myFixture.configureByText("a.go", "package main; func _() {\n" + expressionText + "\n}"); PsiElement element = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); GoReferenceExpression expression = PsiTreeUtil.getNonStrictParentOfType(element, GoReferenceExpression.class); assertNotNull(expression); assertEquals(expectedAccess, expression.getReadWriteAccess()); } } ================================================ FILE: tests/com/goide/psi/impl/GoNamedElementTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoVarDefinition; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoNamedElementTest extends GoCodeInsightFixtureTestCase{ private void doTestGetUseScope(@NotNull String text, @NotNull Class scope) { myFixture.configureByText("a.go", text); PsiFile file = myFixture.getFile(); GoVarDefinition var = PsiTreeUtil.findChildOfType(file, GoVarDefinition.class); assertNotNull(var); assertTrue(scope.isInstance(var.getUseScope())); } public void testGlobalVarScope() { doTestGetUseScope("package a; var b = 1", GlobalSearchScope.class); } public void testLocalVarScope() { doTestGetUseScope("package a; func a() {\n var b = 1 }", LocalSearchScope.class); } } ================================================ FILE: tests/com/goide/psi/impl/GoPsiImplUtilTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.impl; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.*; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; public class GoPsiImplUtilTest extends GoCodeInsightFixtureTestCase { public void testGetLocalPackageNameDash() { assertEquals("test_directory", GoPsiImplUtil.getLocalPackageName("test-directory")); } public void testGetLocalPackageNameDigitAtBeginning() { assertEquals("_23abc", GoPsiImplUtil.getLocalPackageName("123abc")); } public void testGetLocalPackageNameUnderscore() { assertEquals("_", GoPsiImplUtil.getLocalPackageName("_")); } public void testGetLocalPackageNameForPath() { assertEquals("test_directory", GoPsiImplUtil.getLocalPackageName("path/test-directory")); } public void testAddVarSpec() { myFixture.configureByText("a.go", "package main\n\nvar (\n" + " foo int\n" + ")"); GoVarDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nvar (\n foo int\nbar string = `1`\n)"); } public void testAddVarSpecWithoutParens() { myFixture.configureByText("a.go", "package main\n\nvar foo int\n"); GoVarDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nvar (foo int\nbar string = `1`\n)\n"); } public void testAddVarSpecNoNewLines() { myFixture.configureByText("a.go", "package main\n\nvar (foo int\n)"); GoVarDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nvar (foo int\nbar string = `1`\n)"); } public void testAddVarSpecWithAnchor() { myFixture.configureByText("a.go", "package main\n\nvar (\n" + " foo int\n" + ")"); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); GoVarDeclaration declaration = (GoVarDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nvar (\n bar string = `1`\nfoo int\n)"); } public void testAddVarSpecWithoutParensWithAnchor() { myFixture.configureByText("a.go", "package main\n\nvar foo int\n"); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); GoVarDeclaration declaration = (GoVarDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nvar (\nbar string = `1`\nfoo int)\n"); } public void testAddVarSpecNoNewLinesWithAnchor() { myFixture.configureByText("a.go", "package main\n\nvar (foo int\n)"); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); GoVarDeclaration declaration = (GoVarDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nvar (\nbar string = `1`\nfoo int\n)"); } public void testAddConstSpec() { myFixture.configureByText("a.go", "package main\n\nconst (\n" + " foo int\n" + ")"); GoConstDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nconst (\n foo int\nbar string = `1`\n)"); } public void testAddConstSpecWithoutParens() { myFixture.configureByText("a.go", "package main\n\nconst foo int\n"); GoConstDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nconst (foo int\nbar string = `1`\n)\n"); } public void testAddConstSpecNoNewLines() { myFixture.configureByText("a.go", "package main\n\nconst (foo int\n)"); GoConstDeclaration declaration = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDeclaration.class); assertNotNull(declaration); declaration.addSpec("bar", "string", "`1`", null); myFixture.checkResult("package main\n\nconst (foo int\nbar string = `1`\n)"); } public void testAddConstSpecWithAnchor() { myFixture.configureByText("a.go", "package main\n\nconst (\n" + " foo int\n" + ")"); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); GoConstDeclaration declaration = (GoConstDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nconst (\n bar string = `1`\nfoo int\n)"); } public void testAddConstSpecWithoutParensWithAnchor() { myFixture.configureByText("a.go", "package main\n\nconst foo int\n"); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); GoConstDeclaration declaration = (GoConstDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nconst (\nbar string = `1`\nfoo int)\n"); } public void testAddConstSpecNoNewLinesWithAnchor() { myFixture.configureByText("a.go", "package main\n\nconst (foo int\n)"); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); GoConstDeclaration declaration = (GoConstDeclaration)spec.getParent(); declaration.addSpec("bar", "string", "`1`", spec); myFixture.checkResult("package main\n\nconst (\nbar string = `1`\nfoo int\n)"); } public void testGetTypeOfSingleVarDefinition() { myFixture.configureByText("a.go", "package main\n\n var foo int"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoType type = definition.findSiblingType(); assertNotNull(type); assertEquals("int", type.getText()); } public void testGetTypeOfMultipleVarDefinition() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoType type = definition.findSiblingType(); assertNotNull(type); assertEquals("int", type.getText()); } public void testGetTypeOfSingleConstDefinition() { myFixture.configureByText("a.go", "package main\n\n const foo int = 1"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoType type = definition.findSiblingType(); assertNotNull(type); assertEquals("int", type.getText()); } public void testGetTypeOfMultipleConstDefinition() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoType type = definition.findSiblingType(); assertNotNull(type); assertEquals("int", type.getText()); } public void testGetValueOfVarDefinitionInSwitch() { myFixture.configureByText("a.go", "package main\n\n func _() { bar := nil; switch foo := bar.(type){}}"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("bar", value.getText()); } public void testGetValueOfSingleVarDefinition() { myFixture.configureByText("a.go", "package main\n\n var foo int = 1"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("1", value.getText()); } public void testGetValueOfMultipleVarDefinition_1() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1, 2"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("1", value.getText()); } public void testGetValueOfMultipleVarDefinition_2() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1, 2"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("2", value.getText()); } public void testGetValueOfMultipleVarDefinitionWithoutValues() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); assertNull(definition.getValue()); } public void testGetValueOfMultipleInvalidVarDefinition() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); assertNull(definition.getValue()); } public void testGetValueOfSingleConstDefinition() { myFixture.configureByText("a.go", "package main\n\n const foo int = 1"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("1", value.getText()); } public void testGetValueOfMultipleConstDefinition_1() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("1", value.getText()); } public void testGetValueOfMultipleConstDefinition_2() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoExpression value = definition.getValue(); assertNotNull(value); assertEquals("2", value.getText()); } public void testDeleteSingleVarDefinition() { myFixture.configureByText("a.go", "package main\n\n var bar int = 1, 2"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n "); } public void testDeleteFirstMultipleVarDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1, 2"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n var bar int = 2"); } public void testDeleteMiddleMultipleVarDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n var buzz, foo, bar int = 1, 2, 3"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n var buzz , bar int = 1 , 3"); } public void testDeleteLastMultipleVarDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1, 2"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n var foo int = 1 "); } public void testDeleteLastMultipleVarDefinitionWithoutValue() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n var foo int = 1"); } public void testDeleteFirstMultipleVarDefinitionWithoutValue() { myFixture.configureByText("a.go", "package main\n\n var foo, bar int = 1"); GoVarDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarDefinition.class); assertNotNull(definition); GoVarSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoVarSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n var bar int "); } public void testDeleteSingleConstDefinition() { myFixture.configureByText("a.go", "package main\n\n const bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n "); } public void testDeleteFirstMultipleConstDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n const bar int = 2"); } public void testDeleteMiddleMultipleConstDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n const buzz, foo, bar int = 1, 2, 3"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n const buzz , bar int = 1 , 3"); } public void testDeleteLastMultipleConstDefinitionWithValue() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1, 2"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n const foo int = 1 "); } public void testDeleteLastMultipleConstDefinitionWithoutValue() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n const foo int = 1"); } public void testDeleteFirstMultipleConstDefinitionWithoutValue() { myFixture.configureByText("a.go", "package main\n\n const foo, bar int = 1"); GoConstDefinition definition = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstDefinition.class); assertNotNull(definition); GoConstSpec spec = PsiTreeUtil.getNonStrictParentOfType(myFixture.getElementAtCaret(), GoConstSpec.class); assertNotNull(spec); spec.deleteDefinition(definition); myFixture.checkResult("package main\n\n const bar int "); } public void testGoIndexOrSliceExprGetIndices() { PsiFile file = myFixture.configureByText("a.go", "package main\n var a []int\n var b = a[1]"); GoIndexOrSliceExpr index = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), GoIndexOrSliceExpr.class); assertNotNull(index); assertEquals("1", index.getIndices().first.getText()); } @Override protected boolean isWriteActionRequired() { return true; } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveBuiltinTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import com.goide.SdkAware; import org.jetbrains.annotations.NotNull; @SdkAware public class GoLegacyResolveBuiltinTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/builtin"; } @Override protected boolean allowNullDefinition() { return true; } public void testMethodName() { doFileTest(); } public void testBuiltinTypes() { doFileTest(); } public void testBuiltinConversion() { doFileTest(); } public void testVarBuiltinType() { doFileTest(); } public void testVarMethodType() { doFileTest(); } public void testParameterType() { doFileTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveCallsTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import org.jetbrains.annotations.NotNull; public class GoLegacyResolveCallsTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/calls"; } public void testCallToLocalMethodByPointer() { doFileTest(); } public void testCallToLocalMethod() { doFileTest(); } public void testCallToLocalMethodNested() { doFileTest(); } public void testCallToLocalMethodViaMap() { doFileTest(); } public void testCallToLocalMethodViaShortVarDeclaration() { doFileTest(); } public void testCallToLocalMethodViaSlice() { doFileTest(); } public void testCallToLocalMethodViaTypeAssert() { doFileTest(); } public void testCallToLocalInterfaceMethod() { doFileTest(); } public void testCallToLocalInterfaceMethodNested() { doFileTest(); } public void testCallToLocalInterfaceMethodViaMap() { doFileTest(); } public void testCallToLocalInterfaceMethodViaSlice() { doFileTest(); } public void testCallToLocalInterfaceMethodViaTypeAssert() { doFileTest(); } public void testCallToLocalFunction() { doFileTest(); } public void testCallToFunctionLiteral() { doFileTest(); } public void testTypeConversionToLocalType() { doFileTest(); } public void testRecursiveMethodCall() { doFileTest(); } public void testCallToMethodParameter() { doFileTest(); } public void testCallToFunctionVariable() { doFileTest(); } public void testDirectlyInheritedMethodSet() { doFileTest(); } public void testGrandParentDirectlyInheritedMethodSet() { doFileTest(); } public void testCallToEmbeddedInterfaceMethod() { doFileTest(); } public void testCallToFunctionWithSameNameAsMethod() { doFileTest(); } public void testCallToMethodWithTheSameNameAsFunction() { doFileTest(); } public void testConversionToImportedType() { doDirTest(); } public void testConversionToImportedFunction() { doDirTest(); } public void testNoConversionToBlankImportedType() { doDirTest(); } public void testConversionToLocallyImportedType() { doDirTest(); } public void testFunctionInSamePackageDifferentFile() { doDirTest(); } public void testRelativePackageReference() { doDirTest(); } public void testRelativePackageReferenceDeep() { doDirTest(); } public void testCallToFunctionWithSameNameAsMethodAcrossPackages() { doDirTest(); } public void testCallToMethodViaShortVar() { doDirTest(); } public void testImportedEmbeddedTypeMethod() { doDirTest(); } public void testCallToMethodWithTheSameNameAsFunctionAcrossPackages() { doDirTest(); } public void testCallFromTestToMethodDefinedInTestFile() { doDirTest(); } public void testCallToMethodDefinedInTestFile() { doDirTest(); } public void testCallToDifferentBuildTargetFiles() { GoBuildTargetSettings buildTargetSettings = new GoBuildTargetSettings(); buildTargetSettings.customFlags = new String[]{"enabled"}; GoModuleSettings.getInstance(myFixture.getModule()).setBuildTargetSettings(buildTargetSettings); doDirTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveCompositeTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import org.jetbrains.annotations.NotNull; public class GoLegacyResolveCompositeTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/composite"; } public void testTypeName() { doFileTest(); } public void testTypeStruct() { doFileTest(); } public void testTypeStructArray() { doFileTest(); } public void testTypeStructSlice() { doFileTest(); } public void testTypeStructMap() { doFileTest(); } public void testTypeNameArray() { doFileTest(); } public void testTypeNameMap() { doFileTest(); } public void testTypeNameSlice() { doFileTest(); } public void testNestedStruct() { doFileTest(); } public void testNestedNamedStruct() { doFileTest(); } public void testKeyAsConstantExpression() { doFileTest(); } public void testExpressionKey() { doFileTest(); } public void testPromotedAnonymousField1() { doFileTest(); } public void testPromotedAnonymousField2() { doFileTest(); } public void testPromotedAnonymousField3() { doFileTest(); } public void testPromotedAnonymousField4() { doFileTest(); } public void testTypeSwitch() { doFileTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolvePackageTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import org.jetbrains.annotations.NotNull; public class GoLegacyResolvePackageTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/package"; } public void testImportAlias() { doFileTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveStructTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import org.jetbrains.annotations.NotNull; public class GoLegacyResolveStructTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/struct"; } public void testDirectStructField() { doFileTest(); } public void testAnonymousDirectStructField() { doFileTest(); } public void testPromotedStructField() { doFileTest(); } public void testStructFieldInMap() { doFileTest(); } public void testFieldVsParam() { doFileTest(); } public void testFieldVsParam2() { doFileTest(); } public void testFieldVsParam3() { doFileTest(); } public void testFieldVsParam4() { doFileTest(); } public void testDirectExportedFieldFromImportedPackage() { doDirTest(); } public void testDirectPrivateFieldFromImportedPackage() { doDirTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.project.GoModuleLibrariesService; import com.goide.psi.GoFile; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.FilteringProcessor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; public abstract class GoLegacyResolveTestBase extends GoCodeInsightFixtureTestCase { @NotNull private static final String REF_MARK = "/*ref*/"; @NotNull private static final String NO_REF_MARK = "/*no ref*/"; @NotNull private static final String DEF_MARK = "/*def*/"; @Nullable private PsiReference myReference; @Nullable private PsiElement myDefinition; private boolean myShouldBeResolved = true; @Override protected String getBasePath() { return "psi/resolve"; } protected void doFileTest() { processPsiFile((GoFile)myFixture.configureByFile(getTestName(false) + ".go")); doResolveTest(); } protected void doDirTest() { String testDataPath = getTestDataPath(); String testName = getTestName(false); File fromDir = new File(testDataPath + "/" + testName); if (!fromDir.isDirectory()) { throw new RuntimeException("Given file is not directory: " + fromDir); } //noinspection ConstantConditions for (File file : fromDir.listFiles()) { if (file.isDirectory()) { myFixture.copyDirectoryToProject(testName + "/" + file.getName(), file.getName()); } else { myFixture.copyFileToProject(testName + "/" + file.getName()); } } VirtualFile dirToTest = myFixture.getTempDirFixture().getFile("."); assertNotNull(dirToTest); GoModuleLibrariesService.getInstance(myFixture.getModule()).setLibraryRootUrls(dirToTest.getUrl()); doDirectoryTest(dirToTest); } private void doResolveTest() { if (myReference == null) fail("no reference defined in test case"); if (myShouldBeResolved && !allowNullDefinition() && myDefinition == null) fail("no definition defined in test case"); PsiElement resolve = myReference.resolve(); if (myShouldBeResolved) { assertNotNull("cannot resolve reference " + myReference.getCanonicalText(), resolve); if (myDefinition != null) { PsiElement def = PsiTreeUtil.getParentOfType(myDefinition, resolve.getClass(), false); assertSame("element resolved in non-expected element from " + getFileName(resolve) + ":\n" + resolve.getText(), def, resolve); } } else if (resolve != null) { fail("element is resolved but it wasn't should. resolved to element from " + getFileName(resolve) + ":\n" + resolve.getText()); } } @NotNull private static String getFileName(@NotNull PsiElement resolve) { return resolve instanceof PsiFile ? ((PsiFile)resolve).getName() : resolve.getContainingFile().getName(); } protected boolean allowNullDefinition() { return false; } private void processPsiFile(@NotNull GoFile file) { String fileContent = loadText(file.getVirtualFile()); String fileName = file.getName(); int refIndex = fileContent.indexOf(REF_MARK); if (refIndex != -1) { int offset = refIndex + REF_MARK.length(); myReference = findReference(file, offset); } int noRefIndex = fileContent.indexOf(NO_REF_MARK); if (noRefIndex != -1) { int offset = noRefIndex + NO_REF_MARK.length(); myReference = findReference(file, offset); myShouldBeResolved = false; } int defIndex = fileContent.indexOf(DEF_MARK); if (defIndex != -1) { if (myDefinition != null) fail("only one definition should be allowed in a resolve test case, see file: " + fileName); int offset = defIndex + DEF_MARK.length(); myDefinition = file.findElementAt(offset); if (myDefinition == null) fail("no definition was found at mark in file: " + fileName + ", offset: " + offset); } } @NotNull private PsiReference findReference(@NotNull GoFile file, int offset) { if (myReference != null) fail("only one reference should be declared in a test case, see file: " + file.getName()); PsiReference result = file.findReferenceAt(offset); if (result == null) fail("no reference was found at mark in file: " + file.getName() + ", offset: " + offset); return result; } private void doDirectoryTest(@NotNull VirtualFile file) { VfsUtilCore.processFilesRecursively(file, new FilteringProcessor<>( virtualFile -> !virtualFile.isDirectory() && virtualFile.getName().endsWith(".go"), virtualFile -> { PsiFile goFile = myFixture.getPsiManager().findFile(virtualFile); assert goFile instanceof GoFile; processPsiFile((GoFile)goFile); return true; } )); doResolveTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveTypesTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import org.jetbrains.annotations.NotNull; public class GoLegacyResolveTypesTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/types"; } public void testLocalType() { doFileTest(); } public void testFromMethodReceiver() { doFileTest(); } public void testResolveTypeNameInTypeSpec() { doFileTest(); } public void testResolveTypeInCast() { doFileTest(); } public void testResolveArrayInRange() { doFileTest(); } public void testMethodsOrder() { doFileTest(); } public void testFunctionTypeByRef() { doFileTest(); } public void testFromDefaultImportedPackage() { doDirTest(); } public void testFromInjectedPackage() { doDirTest(); } public void testFromCustomImportedPackage() { doDirTest(); } public void testIgnoreBlankImportedPackage() { doDirTest(); } public void testFromMultipleImportedPackage() { doDirTest(); } public void testCompositeLiteralFromImportedPackage() { doDirTest(); } public void testFromMixedCaseImportedPackage() { doDirTest(); } public void testFromLowerCasePackageInMixedCaseFolder() { doDirTest(); } public void testDontResolveIfImportedInAnotherFileSamePackage() { doDirTest(); } } ================================================ FILE: tests/com/goide/psi/legacy/GoLegacyResolveVarsTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.psi.legacy; import org.jetbrains.annotations.NotNull; public class GoLegacyResolveVarsTest extends GoLegacyResolveTestBase { @NotNull @Override protected String getBasePath() { return "psi/resolve/vars"; } public void testAnonymousFunctionInvocation() { doFileTest(); } public void testDeclaredInForRange1() { doFileTest(); } public void testDeclaredInForRange2() { doFileTest(); } public void testDeclaredInForRangeAsValue() { doFileTest(); } public void testDeclaredInForClause() { doFileTest(); } public void testMethodReturn() { doFileTest(); } public void testSimpleMethodParameter() { doFileTest(); } public void testMethodReturn2() { doFileTest(); } public void testGlobalVarDeclaration() { doFileTest(); } public void testGlobalShadowedVarDeclaration() { doFileTest(); } public void testGlobalVarDeclarationFromBlock() { doFileTest(); } public void testShortVarDeclaration() { doFileTest(); } public void testShortVarRedeclaration() { doFileTest(); } public void testShortVarDeclarationFromBlock() { doFileTest(); } public void testGlobalConstDeclaration() { doFileTest(); } public void testResolveToMethodName() { doFileTest(); } public void testLocalConstDeclaration() { doFileTest(); } public void testChainedSelector() { doFileTest(); } public void testVarInSwitchExpr() { doFileTest(); } public void testVarInSwitchExprInitialization() { doFileTest(); } public void testVarInSwitchType() { doFileTest(); } public void testVarInSwitchTypeInitialization() { doFileTest(); } public void testMultipleGlobalVars() { doFileTest(); } public void testMultipleGlobalConsts() { doFileTest(); } public void testDeclarationInsideLabeledStatement() { doFileTest(); } public void testStructFieldViaChannel() { doFileTest(); } public void testShortVarDeclarationFromSelectClause() { doFileTest(); } public void testVarDeclarationInSelectCommClauseRecv() { doFileTest(); } public void testVarDeclarationInSelectCommClauseDefault() { doFileTest(); } public void testRangeExpressionVarsShouldNotResolveToRangeVars() { doFileTest(); } public void testVarDereferenceAsTypeCast() { doFileTest(); } public void testShortAssignToReturnVar() { doFileTest(); } public void testResolveToFunctionName() { doFileTest(); } public void testVarInSwitchTypeWithNamedSwitchGuard() { doFileTest(); } public void testVarDeclarationInSelectCommClauseSend() { doFileTest(); } public void testVarDeclarationOutsideSwitch() { doFileTest(); } public void testVarVsInnerTypes() { doFileTest(); } public void testVarTypeGuard() { doFileTest(); } public void testResolveMethodReceiver() { doFileTest(); } public void testDontProcessExpressions() { doFileTest(); } public void testFromDefaultImportedPackage() { doDirTest(); } public void testLocalPackageDefinitionsShouldBeResolvedFirst() { doDirTest(); } public void testMultipleApplications() { doDirTest(); } public void testFromInjectedImportedPackage() { doDirTest(); } public void testDefaultImportDifferentPackage() { doDirTest(); } public void testFromCustomImportedPackage() { doDirTest(); } } ================================================ FILE: tests/com/goide/quickfix/GoAddMissingReturnQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoMissingReturnInspection; public class GoAddMissingReturnQuickFixTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoMissingReturnInspection.class); } public void testSimple() { doTest(GoMissingReturnInspection.ADD_RETURN_STATEMENT_QUICK_FIX_NAME, true); } @Override protected String getBasePath() { return "quickfixes/add-missing-return"; } } ================================================ FILE: tests/com/goide/quickfix/GoAddTrailingCommaQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoAddTrailingCommaInspection; import org.jetbrains.annotations.NotNull; public class GoAddTrailingCommaQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoAddTrailingCommaInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/add-comma"; } public void testSimple() { doTest(GoAddTrailingCommaInspection.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoAssignmentToComparisonQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoUsedAsValueInCondition; import org.jetbrains.annotations.NotNull; public class GoAssignmentToComparisonQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUsedAsValueInCondition.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/assignment-to-comparison"; } public void testAssignment() { doTest(GoUsedAsValueInCondition.QUICK_FIX_NAME); } public void testShortVar() { doTest(GoUsedAsValueInCondition.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoBoolExpressionsInspectionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.GoParametrizedTestBase; import com.goide.SdkAware; import com.goide.inspections.GoBoolExpressionsInspection; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) @SdkAware public class GoBoolExpressionsInspectionTest extends GoParametrizedTestBase { private final String expr; private final String vars; private final String after; @Parameterized.Parameters(name = "{1}") public static Collection data() { return Arrays.asList(new Object[][]{ {"var b bool", "b || true", "true"}, {"var b bool", "b || false", "b"}, {"var b bool", "b && true", "b"}, {"var b bool", "b && false", "false"}, {"var b bool", "b && b", "b"}, {"var b bool", "b || b", "b"}, {"var b,c,d bool", "b || c && b", "b || c && b"}, {"var b,c,d bool", "b || c || !b", "true"}, {"var b,c,d bool", "!b || !(!b)", "true"}, {"var b,c,d bool", "!b || d || c", "!b || d || c"}, {"var b,c,d bool", "!b && b", "false"}, {"var b,c,d bool", "(b && c) || (c && b)", "c && b"}, {"var b,c,d bool", "(b == c || c == b) || (b == c)", "b == c"}, {"var c1, c2 = 1, 2; var a, b, c int", "b == c1 || b == c2", "b == c1 || b == c2"}, {"var c1, c2 = 1, 2; var a, b, c int", "b != c1 && b != c2", "b != c1 && b != c2"}, }); } @Before public void enableInspections() { myFixture.enableInspections(GoBoolExpressionsInspection.class); } public GoBoolExpressionsInspectionTest(String vars, String expr, String after) { this.expr = expr; this.vars = vars; this.after = after; } @Override public void doTest() { myFixture.configureByText("a.go", "package main\n func main(){\n" + vars + "\nvar a = " + expr + "" + "\n}"); if (!expr.equals(after)) { applySingleQuickFix(GoSimplifyBoolExprQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package main\n func main(){\n" + vars + "\nvar a = " + after + "" + "\n}"); } else { assertEmpty(myFixture.filterAvailableIntentions(GoSimplifyBoolExprQuickFix.QUICK_FIX_NAME)); } } } ================================================ FILE: tests/com/goide/quickfix/GoContinueNotInLoopQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import org.jetbrains.annotations.NotNull; public class GoContinueNotInLoopQuickFixTest extends GoQuickFixTestBase { @NotNull @Override protected String getBasePath() { return "quickfixes/continue-outside-loop"; } public void testSimple() { doTest(GoReplaceWithReturnStatementQuickFix.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoConvertStringToByteQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.SdkAware; import com.goide.inspections.GoStringAndByteTypeMismatchInspection; import org.jetbrains.annotations.NotNull; @SdkAware public class GoConvertStringToByteQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoStringAndByteTypeMismatchInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/string-index-is-byte"; } private void doTest() { doTest(GoConvertStringToByteQuickFix.NAME); } private void doTestNoFix(boolean checkHighlighting) { doTestNoFix(GoConvertStringToByteQuickFix.NAME, checkHighlighting); } public void testEqualsCondition() { doTest(); } public void testNotEqualsCondition() { doTest(); } public void testGreaterCondition() { doTest(); } public void testGreaterOrEqualsCondition() { doTest(); } public void testLessCondition() { doTest(); } public void testLessOrEqualsCondition() { doTest(); } public void testReverse() { doTest(); } public void testLiterals() { doTest(); } public void testLongLiteral() { doTest(); } public void testSliceFromLeft() { doTestNoFix(false); } public void testSliceFromRight() { doTestNoFix(false); } public void testSliceUnbound() { doTestNoFix(false); } public void testMoreThanOneCharInString() { doTestNoFix(true); } } ================================================ FILE: tests/com/goide/quickfix/GoCreateGlobalConstQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoCreateGlobalConstQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/global-constant"; } public void testSimple() { doTest("Create global constant 'a'"); } public void testDoNotSuggestCreatingConstOnAssignment() { doTestNoFix("Create global constant 'a'"); } public void testDoNotSuggestCreatingConstOnChanRead() { doTestNoFix("Create global constant 'a'"); } } ================================================ FILE: tests/com/goide/quickfix/GoCreateGlobalVariableQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoCreateGlobalVariableQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/global-variable"; } public void testSimple() { doTest("Create global variable 'a'"); } } ================================================ FILE: tests/com/goide/quickfix/GoCreateLocalConstantQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoCreateLocalConstantQuickFixTest extends GoQuickFixTestBase { private static final String CREATE_LOCAL_CONSTANT_A = "Create local constant 'a'"; @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/local-constant"; } private void doTestCreateA() { doTest(CREATE_LOCAL_CONSTANT_A); } public void testSimple() { doTestCreateA(); } public void testIf() { doTestCreateA(); } public void testUnresolved() { doTestCreateA(); } public void testResolved() { doTestCreateA(); } public void testOnAssignment() { doTestNoFix(CREATE_LOCAL_CONSTANT_A); } public void testOnChanRead() { doTestNoFix(CREATE_LOCAL_CONSTANT_A); } public void testOnTopLevel() { doTestNoFix(CREATE_LOCAL_CONSTANT_A); } } ================================================ FILE: tests/com/goide/quickfix/GoCreateLocalVariableQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoCreateLocalVariableQuickFixTest extends GoQuickFixTestBase { private static final String CREATE_LOCAL_VARIABLE_A = "Create local variable 'a'"; @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/local-variable"; } private void doTestCreateA() { doTest(CREATE_LOCAL_VARIABLE_A); } public void testSimple() { doTestCreateA(); } public void testIf() { doTestCreateA(); } public void testUnresolved() { doTestCreateA(); } public void testResolved() { doTestCreateA(); } public void testOnTopLevel() { doTestNoFix(CREATE_LOCAL_VARIABLE_A); } } ================================================ FILE: tests/com/goide/quickfix/GoCreateWrapperTypeQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoCreateWrapperTypeQuickFixTest extends GoQuickFixTestBase { private static final String CREATE_TYPE_A = "Create type 'A'"; @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/create-type"; } public void testSimple() { doTest(CREATE_TYPE_A); } public void testGlobal() { doTest(CREATE_TYPE_A); } public void testProhibited() { doTestNoFix(CREATE_TYPE_A); } } ================================================ FILE: tests/com/goide/quickfix/GoDeleteConstDefinitionQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnusedConstInspection; public class GoDeleteConstDefinitionQuickFixTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedConstInspection.class); } public void testSimple() { myFixture.configureByText("a.go", "package main; func main() { const foo int = 2 }"); applySingleQuickFix("Delete const 'foo'"); myFixture.checkResult("package main; func main() {}"); } public void testRemoveFromMultiSpec() { myFixture.configureByText("a.go", "package main; func main() { const (foo, bar int = 2, 3) }"); applySingleQuickFix("Delete const 'foo'"); myFixture.checkResult("package main; func main() { const (\n" + "\tbar int = 3) }"); } } ================================================ FILE: tests/com/goide/quickfix/GoDeleteVarDefinitionQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnusedVariableInspection; public class GoDeleteVarDefinitionQuickFixTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedVariableInspection.class); } public void testSimple() { myFixture.configureByText("a.go", "package main; func main() { var variable int = 2 }"); applySingleQuickFix("Delete variable 'variable'"); myFixture.checkResult("package main; func main() {}"); } public void testRemoveFromMultiSpec() { myFixture.configureByText("a.go", "package main; func main() { var (\nfoo, bar int = 2, 3\n) }"); applySingleQuickFix("Delete variable 'foo'"); myFixture.checkResult("package main; func main() { var (\n" + "bar int = 3\n" + ") }"); } } ================================================ FILE: tests/com/goide/quickfix/GoEmptySignatureQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; public class GoEmptySignatureQuickFixTest extends GoQuickFixTestBase { public void testSimple() { myFixture.configureByText("a.go", "package main; func main() int {}"); applySingleQuickFix(GoEmptySignatureQuickFix.QUICK_FIX_NAME); myFixture.checkResult("package main; func main() {}"); } } ================================================ FILE: tests/com/goide/quickfix/GoExportedOwnDeclarationQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoExportedOwnDeclarationInspection; import org.jetbrains.annotations.NotNull; public class GoExportedOwnDeclarationQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoExportedOwnDeclarationInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/exported-own-declaration"; } public void testSingleLineMultipleExportedAndPrivateConsts() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testSingleLineMultipleConsts() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testSingleLineMultipleVars() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testMultiLineMultipleConstsWithType() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testMultiLineMultipleConstsWithoutType() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testMultiLineMultipleVarsOnlyType() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testMultiLineMultipleVarsWithTypeAndValues() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } public void testMultiLineMultipleVarsOnlyValues() { doTest(GoExportedOwnDeclarationInspection.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoIntroduceFunctionFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.SdkAware; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; @SdkAware public class GoIntroduceFunctionFixTest extends GoQuickFixTestBase { private final static String QUICK_FIX_NAME = "Create function asd"; @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } public void testSimpleFunction() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithOneParam() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithUnknownTypeParam() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithResultType() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithUnknownResultType() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithThreeParams() { doTest(QUICK_FIX_NAME, false); } public void testFuncWithThreeResultValues() { doTest(QUICK_FIX_NAME, false); } public void testDontCreate() { doTestNoFix(QUICK_FIX_NAME, false); } public void testShortVarDecl() { doTest(QUICK_FIX_NAME, false); } public void testInConstDeclaration() { doTestNoFix(QUICK_FIX_NAME); } public void testVarSpec() { doTest(QUICK_FIX_NAME, false); } public void testAsFunctionArg() { doTest(QUICK_FIX_NAME, false); } public void testAsFunctionArg2() { doTest(QUICK_FIX_NAME, false); } public void testAsFunctionArgWithoutReference() { doTest(QUICK_FIX_NAME, false); } public void testWithChan() { doTest(QUICK_FIX_NAME, false); } public void testInSamePackage() { myFixture.configureByText("a.go", "package foo; type MyType int; func createMyType() MyType { return MyType{}};"); myFixture.configureByText("b.go", "package foo; func _() { asd(createMyType());};"); myFixture.doHighlighting(); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package foo; func _() { asd(createMyType());}\nfunc asd(myType MyType) {\n\t\n};"); } public void testInOtherPackage() { myFixture.addFileToProject("a/a.go", "package a; type MyType int; func CreateMyType() MyType { return MyType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import \"a\"; func _() { asd(a.CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import \"a\"; func _() { asd(a.CreateMyType());}\nfunc asd(myType a.MyType) {\n\t\n};"); } public void testInOtherPackageWithAlias() { myFixture.addFileToProject("a/a.go", "package a; type MyType int; func CreateMyType() MyType { return MyType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import alias \"a\"; func _() { asd(alias.CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture .checkResult("package b; import alias \"a\"; func _() { asd(alias.CreateMyType());}\nfunc asd(myType alias.MyType) {\n\t\n};"); } public void testInOtherPackageWithDotAlias() { myFixture.addFileToProject("a/a.go", "package a; type MyType int; func CreateMyType() MyType { return MyType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import . \"a\"; func _() { asd(CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import . \"a\"; func _() { asd(CreateMyType());}\nfunc asd(myType MyType) {\n\t\n};"); } public void testInOtherPackageWithImportForSideEffects() { myFixture.addFileToProject("a/a.go", "package a; type MyType int"); myFixture.addFileToProject("b/b.go", "package b; import `a`; func CreateMyType() b.MyType {return b.MyType{}};"); PsiFile file = myFixture.addFileToProject("c/c.go", "package c; import `b`; import _ `a`; func _() { asd(b.CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult( "package c; import `b`; import _ `a`; func _() { asd(b.CreateMyType());}\nfunc asd(myType interface{}) {\n\t\n};"); } public void testInOtherPackageWithTwoAlias() { myFixture.addFileToProject("c/c.go", "package c; type MyType int;"); myFixture.addFileToProject("a/a.go", "package a; import myC \"c\" func CreateMyType() myC.MyType { return myC.MyType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import (. \"a\"; importC \"c\"); func _() { asd(CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture .checkResult( "package b; import (. \"a\"; importC \"c\"); func _() { asd(CreateMyType());}\nfunc asd(myType importC.MyType) {\n\t\n};"); } public void testInOtherPackageWithPrivateType() { myFixture.addFileToProject("a/a.go", "package a; type myType int; func CreateMyType() myType { return myType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import . \"a\"; func _() { asd(CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import . \"a\"; func _() { asd(CreateMyType());}\nfunc asd(myType interface{}) {\n\t\n};"); } public void testInOtherPackageWithVendoring() { myFixture.addFileToProject("a/vendor/c.go", "package c; type MyType int;"); myFixture.addFileToProject("a/a.go", "package a; import myC \"vendor\" func CreateMyType() myC.MyType { return myC.MyType{}};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import . \"a\"; func _() { asd(CreateMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import . \"a\"; func _() { asd(CreateMyType());}\nfunc asd(myType interface{}) {\n\t\n};"); } public void testInOtherPackageWithChanOfImportedTypes() { myFixture.addFileToProject("a/a.go", "package a; type MyType int; func CreateChanOfMyType() chan MyType { return nil};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import alias \"a\"; func _() { asd(alias.CreateChanOfMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import alias \"a\"; " + "func _() { asd(alias.CreateChanOfMyType());}\nfunc asd(myType chan alias.MyType) {\n\t\n};"); } public void testInOtherPackageWithStruct() { myFixture.addFileToProject("a/a.go", "package a; type MyType int; func CreateChanOfMyType() struct{ ch chan chan MyType} { return nil};"); PsiFile file = myFixture.addFileToProject("b/b.go", "package b; import alias \"a\"; func _() { asd(alias.CreateChanOfMyType());};"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); applySingleQuickFix(QUICK_FIX_NAME); myFixture.checkResult("package b; import alias \"a\"; " + "func _() { asd(alias.CreateChanOfMyType());}\nfunc asd(myType struct {ch chan chan alias.MyType}) {\n\t\n};"); } @NotNull @Override protected String getBasePath() { return "quickfixes/introduce-function"; } } ================================================ FILE: tests/com/goide/quickfix/GoMoveToStructInitializationIntentionTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.intentions.GoMoveToStructInitializationIntention; import org.jetbrains.annotations.NotNull; public class GoMoveToStructInitializationIntentionTest extends GoQuickFixTestBase { @NotNull @Override protected String getBasePath() { return "intentions/move-to-struct-initialization"; } private void doTest() { doTest(GoMoveToStructInitializationIntention.NAME); } private void doTestNoFix() { doTestNoFix(GoMoveToStructInitializationIntention.NAME); } public void testSimple() { doTest(); } public void testFieldExchange() { doTest(); } public void testCaretAtValue() { doTest(); } public void testAnonymousField() { doTest(); } public void testStructAssignment() { doTest(); } public void testStructAssignmentMultipleAssignee() { doTest(); } public void testMultipleFieldsSameStructureCaretAtValue() { doTest(); } public void testOneLineFieldDeclaration() { doTest(); } public void testMultipleFields() { doTest(); } public void testTwoSameStructures() { doTest(); } public void testTwoSameStructuresAssignment() { doTest(); } public void testJustAssignedVar() { doTest(); } public void testJustInitializedVar() { doTest(); } public void testInvalidAssignment() { doTest(); } public void testExistingField() { doTest(); } public void testMultipleAssignmentsLeftmost() { doTest(); } public void testMultipleAssignmentsRightmost() { doTest(); } public void testMultipleAssignmentsMiddle() { doTest(); } public void testMultipleFieldsPartlyAssigned() { doTest(); } public void testWithParens() { doTest(); } public void testFieldExtractedFromParens() { doTest(); } public void testDuplicateFields() { doTest(); } public void testMultiReturnFunction() { doTestNoFix(); } public void testWrongStruct() { doTestNoFix(); } public void testExistingDeclaration() { doTestNoFix(); } public void testNotExistingField() { doTestNoFix(); } public void testJustAssignedVarWrongCaret() { doTestNoFix(); } public void testJustAssignedVarWrongCaretWithParens() { doTestNoFix(); } public void testJustInitializedVarWrongCaret() { doTestNoFix(); } public void testJustAssignedVarBothParens() { doTestNoFix(); } public void testJustAssignedFieldParens() { doTestNoFix(); } } ================================================ FILE: tests/com/goide/quickfix/GoMultiplePackagesQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoMultiplePackagesInspection; import org.jetbrains.annotations.NotNull; public class GoMultiplePackagesQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoMultiplePackagesInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/multiple-packages"; } public void testMultiplePackagesQuickFix() { myFixture.configureByFile("c_test.go"); myFixture.configureByFile("b.go"); myFixture.configureByFile("b_test.go"); myFixture.configureByFile("a.go"); GoMultiplePackagesQuickFix.setTestingPackageName("a", getTestRootDisposable()); applySingleQuickFix("Rename packages"); myFixture.checkResultByFile("a.go", "a-after.go", true); myFixture.checkResultByFile("b.go", "b-after.go", true); myFixture.checkResultByFile("b_test.go", "b_test-after.go", true); myFixture.checkResultByFile("c_test.go", "c_test-after.go", true); } } ================================================ FILE: tests/com/goide/quickfix/GoQuickFixTestBase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.codeInsight.intention.IntentionAction; import org.jetbrains.annotations.NotNull; import java.util.List; public abstract class GoQuickFixTestBase extends GoCodeInsightFixtureTestCase { protected void doTest(@NotNull String quickFixName) { doTest(quickFixName, false); } protected void doTest(@NotNull String quickFixName, boolean checkHighlighting) { String testName = getTestName(true); configure(checkHighlighting, testName); applySingleQuickFix(quickFixName); myFixture.checkResultByFile(testName + "-after.go", true); } protected void doTestNoFix(@NotNull String name) { doTestNoFix(name, false); } protected void doTestNoFix(@NotNull String name, boolean checkHighlighting) { configure(checkHighlighting, getTestName(true)); List availableIntentions = myFixture.filterAvailableIntentions(name); assertEmpty(availableIntentions); } private void configure(boolean checkHighlighting, String testName) { if (checkHighlighting) { myFixture.testHighlighting(testName + ".go"); } else { myFixture.configureByFile(testName + ".go"); myFixture.doHighlighting(); } } } ================================================ FILE: tests/com/goide/quickfix/GoRenameFunctionQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnusedFunctionInspection; import org.jetbrains.annotations.NotNull; public class GoRenameFunctionQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedFunctionInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/rename-function"; } public void testSimple() { doTest(GoRenameToBlankQuickFix.NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoRenameVarQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoUnusedVariableInspection; import org.jetbrains.annotations.NotNull; public class GoRenameVarQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedVariableInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/rename-var"; } public void testSimple() { doTest(GoRenameToBlankQuickFix.NAME); } public void testProhibited() { doTestNoFix(GoRenameToBlankQuickFix.NAME); } public void testRenameAndReplaceWithAssignment_1() { doTest(GoRenameToBlankQuickFix.NAME); } public void testRenameAndReplaceWithAssignment_2() { doTest(GoRenameToBlankQuickFix.NAME); } public void testRenameAndReplaceWithAssignment_3() { doTest(GoRenameToBlankQuickFix.NAME); } public void testRenameAndReplaceWithAssignmentOnRange() { doTest(GoRenameToBlankQuickFix.NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoReplaceWithAssignmentStatementQuickFixTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoNoNewVariablesInspection; import org.jetbrains.annotations.NotNull; public class GoReplaceWithAssignmentStatementQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoNoNewVariablesInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/replace-with-assignment"; } public void testSimple() { doTest(GoNoNewVariablesInspection.QUICK_FIX_NAME); } public void testSeveralAssignments() { doTest(GoNoNewVariablesInspection.QUICK_FIX_NAME); } public void testRecvStatement() { doTest(GoNoNewVariablesInspection.QUICK_FIX_NAME); } public void testRecvStatementInSelect() { doTest(GoNoNewVariablesInspection.QUICK_FIX_NAME); } public void testRangeClause() { doTest(GoNoNewVariablesInspection.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoReplaceWithDeclarationQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.unresolved.GoReplaceAssignmentWithDeclarationQuickFix; import com.goide.inspections.unresolved.GoUnresolvedReferenceInspection; import org.jetbrains.annotations.NotNull; public class GoReplaceWithDeclarationQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnresolvedReferenceInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/replace-with-declaration"; } public void testOnRecv() { doTest(GoReplaceAssignmentWithDeclarationQuickFix.QUICK_FIX_NAME); } public void testOnRange() { doTest(GoReplaceAssignmentWithDeclarationQuickFix.QUICK_FIX_NAME); } public void testOnAssignment() { doTest(GoReplaceAssignmentWithDeclarationQuickFix.QUICK_FIX_NAME); } public void testOnChanRead() { doTestNoFix(GoReplaceAssignmentWithDeclarationQuickFix.QUICK_FIX_NAME); } public void testOnTopLevel() { doTestNoFix(GoReplaceAssignmentWithDeclarationQuickFix.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/quickfix/GoReplaceWithImportForSideEffectsQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.SdkAware; import com.goide.inspections.GoUnusedImportInspection; @SdkAware public class GoReplaceWithImportForSideEffectsQuickFixTest extends GoQuickFixTestBase { @Override public void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoUnusedImportInspection.class); } public void testSimple() { myFixture.configureByText("a.go", "package pack; import \"fmt\""); applySingleQuickFix("Import for side-effects"); myFixture.checkResult("package pack; import _ \"fmt\""); } } ================================================ FILE: tests/com/goide/quickfix/GoReplaceWithSelectStatementQuickFixTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.quickfix; import com.goide.inspections.GoInfiniteForInspection; import org.jetbrains.annotations.NotNull; public class GoReplaceWithSelectStatementQuickFixTest extends GoQuickFixTestBase { @Override protected void setUp() throws Exception { super.setUp(); myFixture.enableInspections(GoInfiniteForInspection.class); } @NotNull @Override protected String getBasePath() { return "quickfixes/replace-with-select"; } public void testSimple() { doTest(GoReplaceWithSelectStatementQuickFix.QUICK_FIX_NAME); } } ================================================ FILE: tests/com/goide/refactor/GoIntroduceVariableTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.refactor; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; public class GoIntroduceVariableTest extends GoCodeInsightFixtureTestCase { @NotNull @Override protected String getBasePath() { return "refactor/introduce-variable"; } private void doTest() { doTest(true); } private void doTest(boolean replaceAll) { String testName = getTestName(true); myFixture.configureByFile(testName + ".go"); GoIntroduceVariableBase.performAction(new GoIntroduceOperation(getProject(), myFixture.getEditor(), myFixture.getFile(), replaceAll)); myFixture.checkResultByFile(testName + "-after.go"); } private void doFailureTest(String msg) { try { doTest(); fail("Shouldn't be performed"); } catch (CommonRefactoringUtil.RefactoringErrorHintException e) { assertEquals("Cannot perform refactoring.\n" + msg, e.getMessage()); } } public void testCaretAfterRightParenthesis() { doTest(); } public void testCaretOnRightParenthesis() { doTest(); } public void testCaretOnCallParenthesis() { doTest(); } public void testNameSuggestOnGetterFunction() { doTest(); } public void testNameSuggestOnDefaultName() { doTest(); } public void testNameSuggestOnParamName() { doTest(); } public void testNameSuggestOnType() { doTest(); } public void testNameSuggestOnArrayType() { doTest(); } public void testDoNotSuggestKeywordBasedOnType() { doTest(); } public void testDoNotSuggestKeywordBasedOnCallName() { doTest(); } public void testDoNotSuggestNameEqualsToType() { doTest(); } public void testExtractFunctionLiteral() { doTest(); } public void testExtractSingleExpressionStatement_1() { doTest(); } public void testExtractSingleExpressionStatement_2() { doTest(); } public void testExtractSingleExpressionStatement_3() { doTest(); } public void testCompositeLiteral() { doTest(); } public void testIndexedExpression() { doTest(); } public void testConversion() { doTest(); } public void testVoidExpression() { doFailureTest("Expression fmt.Println() returns multiple values."); } public void testVoidCallExpression() { doFailureTest("Expression fmt.Println() returns multiple values."); } public void testWrongSelection() { doFailureTest(RefactoringBundle.message("selected.block.should.represent.an.expression")); } public void testTopLevelExpression() { doFailureTest(RefactoringBundle.message("refactoring.introduce.context.error"));} public void testReplaceAll() { doTest(true); } public void testReplaceOnly() { doTest(false);} public void testTwoOccurrences() { doTest(true);} } ================================================ FILE: tests/com/goide/regexp/GoRegExpLanguageTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.regexp; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; @SdkAware public class GoRegExpLanguageTest extends GoCodeInsightFixtureTestCase { public void testInjectingAndHighlighting() { // myFixture.testHighlighting(getTestName(true) + ".go"); } @Override protected String getBasePath() { return "regexp"; } } ================================================ FILE: tests/com/goide/rename/GoRenameTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.rename; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; public class GoRenameTest extends GoCodeInsightFixtureTestCase { public void testAnonymousField() { doTest("package foo; type A struct {*A}; func foo(a A) {a.A}", "B", "package foo; type B struct { *B }; func foo(a B) {a.B\n}"); } public void testType() { doTest("package foo; type A struct {*A}; func foo(a A) {a.A}", "B", "package foo; type B struct { *B }; func foo(a B) {a.B\n}"); } public void testLabel() { doTest("package foo; func foo() {a:{}; goto a}", "b", "package foo; func foo() {\n\tb:{}; goto b\n}"); } public void testAliasQualifier() { doTest("package foo; import a \"fmt\"; func c() { a.Println() }", "b", "package foo; import b \"fmt\"; func c() { b.Println() }"); } public void testImportAlias() { doTest("package foo; import a \"fmt\"; func foo() { a.Println() }", "b", "package foo; import b \"fmt\"; func foo() { b.Println() }"); } public void testDotImportAlias() { doTestDoNotRename("package foo; import . \"fmt\""); } public void testBlankImportAlias() { doTestDoNotRename("package foo; import _ \"fmt\""); } public void testNullAlias() { doTestDoNotRename("package foo; import \"fmt\""); } public void testPackageQualifier() { doTestDoNotRename("package foo; import \"fmt\" func foo() { fmt.Println() }"); } private void doTest(@NotNull String before, @NotNull String newName, @NotNull String after) { myFixture.configureByText("foo.go", before); myFixture.renameElementAtCaret(newName); myFixture.checkResult(after); } private void doTestDoNotRename(@NotNull String text) { myFixture.configureByText("foo.go", text); try { myFixture.renameElementAtCaret("bar"); fail("Shouldn't be performed"); } catch (CommonRefactoringUtil.RefactoringErrorHintException e) { assertEquals("This element cannot be renamed", e.getMessage()); } myFixture.checkResult(text); } } ================================================ FILE: tests/com/goide/runconfig/GoConsoleFilterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.project.GoApplicationLibrariesService; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.execution.filters.OpenFileHyperlinkInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.List; public class GoConsoleFilterTest extends GoCodeInsightFixtureTestCase { private GoConsoleFilter myFilter; @Override protected void setUp() throws Exception { super.setUp(); VirtualFile workingDirectory = createTestRoot("workingDirectory"); VirtualFile goPath = createTestRoot("goPath"); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(goPath.getUrl()); myFilter = new GoConsoleFilter(myFixture.getProject(), myFixture.getModule(), workingDirectory.getUrl()); } @Override protected void tearDown() throws Exception { myFilter = null; super.tearDown(); } public void testFileNameInParens() { doFileLineTest("Message (nestedWorkingDirectory.go) with file", 9, 34, "/src/workingDirectory/src/nestedWorkingDirectory.go", 1, 1); } public void testSimpleFileName() { doFileLineTest("nestedWorkingDirectory.go:57", 0, 28, "/src/workingDirectory/src/nestedWorkingDirectory.go", 57, 1); } public void testAbsolutePath() { doFileLineTest("\t/src/goPath/src/nestedGoPath.go:57: expected operand, found '<'", 1, 35, "/src/goPath/src/nestedGoPath.go", 57, 1); } public void testAbsolutePathWithoutColumn() { doFileLineTest("\t/src/goPath/src/nestedGoPath.go:57:1: expected operand, found '<'", 1, 37, "/src/goPath/src/nestedGoPath.go", 57, 1); } public void testAbsolutePathWithLoggingTime() { doFileLineTest("2015/03/30 09:15:13 /src/goPath/src/nestedGoPath.go:57:1: expected operand, found '<'", 20, 56, "/src/goPath/src/nestedGoPath.go", 57, 1); } public void testRelativeToWorkingDirectory() { doFileLineTest("src/nestedWorkingDirectory.go:5:5: found packages file.go (main) and file2.go (my) in /Some/path/to/directory", 0, 33, "/src/workingDirectory/src/nestedWorkingDirectory.go", 5, 5); } public void testRelativeToGoPath() { doFileLineTest("src/nestedGoPath.go:2: found packages file.go (main) and file2.go (my) in /Some/path/to/directory", 0, 21, "/src/goPath/src/nestedGoPath.go", 2, 1); } public void testAppEngineFullPaths() { doFileLineTest("/var/folders/m8/8sm6vlls2cs8xdmgs16y27zh0000gn/T/tmpzNDwX9appengine-go-bin/nestedGoPath.go:5:9: error", 0, 94, "/src/goPath/src/nestedGoPath.go", 5, 9); } public void testGoGetLines() { doGoGetTest("\tgo get golang.org/x/tools/cmd/cover", 1, 36, "golang.org/x/tools/cmd/cover"); } private void doGoGetTest(@NotNull String line, int startOffset, int endOffset, @NotNull String packageName) { Filter.Result result = myFilter.applyFilter(line, line.length()); assertNotNull(result); HyperlinkInfo info = assertResultAndGetHyperlink(result, startOffset, endOffset); assertInstanceOf(info, GoConsoleFilter.GoGetHyperlinkInfo.class); assertEquals(packageName, ((GoConsoleFilter.GoGetHyperlinkInfo)info).getPackageName()); } private void doFileLineTest(@NotNull String line, int startOffset, int endOffset, String targetPath, int targetLine, int targetColumn) { Filter.Result result = myFilter.applyFilter(line, line.length()); assertNotNull(result); HyperlinkInfo info = assertResultAndGetHyperlink(result, startOffset, endOffset); assertInstanceOf(info, OpenFileHyperlinkInfo.class); OpenFileDescriptor fileDescriptor = ((OpenFileHyperlinkInfo)info).getDescriptor(); assertNotNull(fileDescriptor); assertEquals(targetPath, fileDescriptor.getFile().getPath()); assertEquals("line", targetLine, fileDescriptor.getLine() + 1); assertEquals("column", targetColumn, fileDescriptor.getColumn() + 1); } @NotNull private static HyperlinkInfo assertResultAndGetHyperlink(@NotNull Filter.Result result, int startOffset, int endOffset) { List items = result.getResultItems(); assertSize(1, items); Filter.ResultItem item = ContainerUtil.getFirstItem(items); assertNotNull(item); assertEquals("start", startOffset, item.getHighlightStartOffset()); assertEquals("end", endOffset, item.getHighlightEndOffset()); HyperlinkInfo hyperlinkInfo = item.getHyperlinkInfo(); assertNotNull(hyperlinkInfo); return hyperlinkInfo; } @NotNull private VirtualFile createTestRoot(@NotNull String rootName) throws IOException { return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { @NotNull @Override public VirtualFile compute() throws IOException { VirtualFile workingDirectory = myFixture.getTempDirFixture().findOrCreateDir(rootName); workingDirectory.createChildData(this, rootName + ".go"); VirtualFile childDirectory = workingDirectory.createChildDirectory(this, "src"); childDirectory.createChildData(this, "nested" + Character.toUpperCase(rootName.charAt(0)) + rootName.substring(1) + ".go"); return workingDirectory; } }); } } ================================================ FILE: tests/com/goide/runconfig/GoRunConfigurationProducerTest.java ================================================ package com.goide.runconfig; import com.goide.runconfig.application.GoApplicationConfiguration; import com.goide.runconfig.application.GoApplicationRunConfigurationProducer; import com.goide.runconfig.application.GoApplicationRunConfigurationType; import com.goide.runconfig.file.GoRunFileConfiguration; import com.goide.runconfig.file.GoRunFileConfigurationProducer; import com.goide.runconfig.file.GoRunFileConfigurationType; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; public class GoRunConfigurationProducerTest extends GoRunConfigurationTestCase { public void testTestFile_test() { doTestProducedConfigurations(); } public void testFileWithMain() { doTestProducedConfigurations(); } public void testFileWithMainButNotMainPackage() { doTestProducedConfigurations(); } public void testFileWithoutMain() { doTestProducedConfigurations(); } public void testPackageClause() { doTestProducedConfigurations(); } public void testDirectory() { PsiFile file = myFixture.addFileToProject("import/path/a.go", "package main; func main(){}"); doTestProducedConfigurations(file.getParent()); } public void testSameRunFileConfigurationOnFile() { PsiFile file = myFixture.configureByText("a.go", "package main; \nfunc main() {}"); PsiElement at = file.findElementAt(myFixture.getCaretOffset()); assertNotNull(at); ConfigurationContext configurationContext = new ConfigurationContext(at); GoRunFileConfigurationProducer producer = new GoRunFileConfigurationProducer(); GoRunFileConfiguration runConfiguration = createFileConfiguration(file.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(file.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameRunApplicationConfigurationOnFile() { PsiFile file = myFixture.configureByText("a.go", "package main; \nfunc main() {}"); PsiElement at = file.findElementAt(myFixture.getCaretOffset()); assertNotNull(at); ConfigurationContext configurationContext = new ConfigurationContext(at); GoRunFileConfigurationProducer producer = new GoRunFileConfigurationProducer(); GoRunFileConfiguration runConfiguration = createFileConfiguration(file.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(file.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameRunApplicationConfigurationOnPackage() { PsiFile file = myFixture.configureByText("a.go", "package main; \nfunc main() {}"); PsiElement at = file.findElementAt(myFixture.getCaretOffset()); assertNotNull(at); ConfigurationContext configurationContext = new ConfigurationContext(at); GoApplicationRunConfigurationProducer producer = new GoApplicationRunConfigurationProducer(); GoApplicationConfiguration runConfiguration = createRunAppFileConfiguration(file.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createRunAppFileConfiguration(file.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameRunApplicationConfigurationOnDirectory() { PsiFile file = myFixture.addFileToProject("import/path/a.go", "package main; func main(){}"); PsiDirectory directory = file.getParent(); assertNotNull(directory); ConfigurationContext configurationContext = new ConfigurationContext(directory); GoApplicationRunConfigurationProducer producer = new GoApplicationRunConfigurationProducer(); GoApplicationConfiguration runConfiguration = createRunAppPackageConfiguration("import/path"); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createRunAppPackageConfiguration("import/path/other"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } private GoRunFileConfiguration createFileConfiguration(String filePath) { GoRunFileConfigurationType type = GoRunFileConfigurationType.getInstance(); GoRunFileConfiguration result = new GoRunFileConfiguration(myFixture.getProject(), "run file", type); result.setFilePath(filePath); return result; } private GoApplicationConfiguration createRunAppFileConfiguration(String filePath) { GoRunFileConfigurationType type = GoRunFileConfigurationType.getInstance(); GoApplicationConfiguration result = new GoApplicationConfiguration(myFixture.getProject(), "run file", type); result.setKind(GoApplicationConfiguration.Kind.FILE); result.setFilePath(filePath); return result; } private GoApplicationConfiguration createRunAppPackageConfiguration(String importPath) { GoApplicationRunConfigurationType type = GoApplicationRunConfigurationType.getInstance(); GoApplicationConfiguration result = new GoApplicationConfiguration(myFixture.getProject(), "run package", type); result.setKind(GoApplicationConfiguration.Kind.PACKAGE); result.setPackage(importPath); return result; } @Override protected String getBasePath() { return "running/producer"; } } ================================================ FILE: tests/com/goide/runconfig/GoRunConfigurationTestCase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.util.List; @SdkAware public abstract class GoRunConfigurationTestCase extends GoCodeInsightFixtureTestCase { protected void doTestProducedConfigurations() { VirtualFile file = myFixture.copyFileToProject(getTestName(true) + ".go", "import/path/" + getTestName(true) + ".go"); myFixture.configureFromExistingVirtualFile(file); doTestProducedConfigurations(myFixture.getFile().findElementAt(myFixture.getCaretOffset())); } protected void doTestProducedConfigurations(@Nullable PsiElement context) { assertNotNull(context); ConfigurationContext configurationContext = new ConfigurationContext(context); List configurationAndSettings = configurationContext.getConfigurationsFromContext(); Element configurationsElement = new Element("configurations"); if (configurationAndSettings != null) { for (ConfigurationFromContext setting : configurationAndSettings) { try { RunConfiguration configuration = setting.getConfiguration(); Element configurationElement = new Element("configurations"); configurationElement.setAttribute("name", configuration.getName()); configurationElement.setAttribute("class", configuration.getClass().getSimpleName()); configuration.writeExternal(configurationElement); configurationsElement.addContent(configurationElement); } catch (WriteExternalException e) { throw new RuntimeException(e); } } } assertSameLinesWithFile(getTestDataPath() + "/" + getTestName(true) + ".xml", JDOMUtil.writeElement(configurationsElement)); } } ================================================ FILE: tests/com/goide/runconfig/testing/GoEventsConverterTestCase.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.execution.Executor; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.text.ParseException; public abstract class GoEventsConverterTestCase extends GoCodeInsightFixtureTestCase { protected void doTest() { Executor executor = new DefaultRunExecutor(); GoTestRunConfiguration runConfig = new GoTestRunConfiguration(myFixture.getProject(), "", GoTestRunConfigurationType.getInstance()); runConfig.setTestFramework(getTestFramework()); GoTestConsoleProperties consoleProperties = new GoTestConsoleProperties(runConfig, executor); GoTestEventsConverterBase converter = (GoTestEventsConverterBase)consoleProperties.createTestEventsConverter("gotest", consoleProperties); LoggingServiceMessageVisitor serviceMessageVisitor = new LoggingServiceMessageVisitor(); try { for (String line : FileUtil.loadLines(new File(getTestDataPath(), getTestName(true) + ".txt"), CharsetToolkit.UTF8)) { converter.processServiceMessages(line + "\n", ProcessOutputTypes.STDOUT, serviceMessageVisitor); } } catch (IOException | ParseException e) { throw new RuntimeException(e); } ((OutputToGeneralTestEventsConverter)converter).flushBufferBeforeTerminating(); Disposer.dispose((OutputToGeneralTestEventsConverter)converter); assertSameLinesWithFile(getTestDataPath() + "/" + getTestName(true) + "-expected.txt", serviceMessageVisitor.getLog()); } @NotNull protected abstract GoTestFramework getTestFramework(); } ================================================ FILE: tests/com/goide/runconfig/testing/GoRunLineMarkerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.GoRunConfigurationTestCase; public class GoRunLineMarkerTest extends GoRunConfigurationTestCase { public void testRunTestLineMarker() { myFixture.configureByText("a_test.go", "package main\n" + "import .`gopkg.in/check.v1`\n" + "func TestName(){}\n" + "func BenchmarkName(){}\n" + "func ExampleName(){}\n" + "type MySuite struct{}\n" + "var _ = Suite(&MySuite{})\n" + "func (s *MySuite) TestHelloWorld(c *C) {}\n" + "func Hello() {}"); assertEquals(1, myFixture.findGuttersAtCaret().size()); assertEquals(5, myFixture.findAllGutters().size()); } public void testRunLineMarker() { myFixture.configureByText("a.go", "package main\n" + "func main(){}"); assertEquals(1, myFixture.findGuttersAtCaret().size()); assertEquals(1, myFixture.findAllGutters().size()); } public void testRunLineMarkerInNonMainFile() { myFixture.configureByText("a.go", "package not_main\n" + "func main(){}"); assertEquals(0, myFixture.findGuttersAtCaret().size()); assertEquals(0, myFixture.findAllGutters().size()); } } ================================================ FILE: tests/com/goide/runconfig/testing/GoTestRunConfigurationProducerTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.GoRunConfigurationTestCase; import com.goide.runconfig.testing.frameworks.gobench.GobenchFramework; import com.goide.runconfig.testing.frameworks.gobench.GobenchRunConfigurationProducer; import com.goide.runconfig.testing.frameworks.gotest.GotestFramework; import com.goide.runconfig.testing.frameworks.gotest.GotestRunConfigurationProducer; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; public class GoTestRunConfigurationProducerTest extends GoRunConfigurationTestCase { public void testDirectory() { PsiFile file = myFixture.configureByText("a.go", "package main"); doTestProducedConfigurations(file.getParent()); } public void testPackage_test() { PsiFile file = myFixture.addFileToProject("import/path/package_test.go", "package main; import `gopkg.in/check.v1`"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); doTestProducedConfigurations(myFixture.getFile().findElementAt(myFixture.getCaretOffset())); } public void testFileWithoutTest_test() { doTestProducedConfigurations(); } public void testNonTestFile() { doTestProducedConfigurations(); } public void testFileWithTestsOnly_test() { doTestProducedConfigurations(); } public void testFileWithBenchmarksOnly_test() { doTestProducedConfigurations(); } public void testFileWithGocheckTestsOnly_test() { doTestProducedConfigurations(); } public void testFileWithTestsAndBenchmarks_test() { doTestProducedConfigurations(); } public void testSimpleFunction_test() { doTestProducedConfigurations(); } public void testSimpleFunctionInFileWithTests_test() { doTestProducedConfigurations(); } public void testBenchmarkFunction_test() { doTestProducedConfigurations(); } public void testExampleFunction_test() { doTestProducedConfigurations(); } public void testTestFunction_test() { doTestProducedConfigurations(); } public void testGocheckMethod_test() { doTestProducedConfigurations(); } public void testTestFunctionNonTestFile() { doTestProducedConfigurations(); } public void testSameConfigurationOnFunction() { PsiFile file = myFixture.addFileToProject("import/path/a_test.go", "package main; func TestName() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); ConfigurationContext configurationContext = createConfigurationContext(); RunConfigurationProducer producer = new GotestRunConfigurationProducer(); GoTestRunConfiguration runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "^TestName$", "import/path"); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "otherPattern", "import/path"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GobenchFramework.INSTANCE, "^TestName$", "import/path"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "^TestName$", "import/path/other"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); producer = new GobenchRunConfigurationProducer(); runConfiguration = createFileConfiguration(GobenchFramework.INSTANCE, file.getVirtualFile().getPath()); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameConfigurationOnNonTestFunction() { PsiFile file = myFixture.addFileToProject("import/path/a_test.go", "package main; func SomeNonTestName() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); ConfigurationContext configurationContext = createConfigurationContext(); GotestRunConfigurationProducer producer = new GotestRunConfigurationProducer(); GoTestRunConfiguration runConfiguration = createFileConfiguration(GotestFramework.INSTANCE, file.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(GotestFramework.INSTANCE, file.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(GobenchFramework.INSTANCE, file.getVirtualFile().getPath()); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameConfigurationOnPackageClause() { PsiFile file = myFixture.addFileToProject("import/path/a_test.go", "package main; func SomeNonTestName() {}"); myFixture.configureFromExistingVirtualFile(file.getVirtualFile()); ConfigurationContext configurationContext = createConfigurationContext(); GotestRunConfigurationProducer producer = new GotestRunConfigurationProducer(); GoTestRunConfiguration runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "", "import/path"); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "otherPattern", "import/path"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GobenchFramework.INSTANCE, "", "import/path"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createPackageConfiguration(GotestFramework.INSTANCE, "", "import/path/other"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameConfigurationOnFile() { PsiFile file = myFixture.configureByText("a_test.go", "package main; \n\nfunc SomeNonTestName() {}"); ConfigurationContext configurationContext = createConfigurationContext(); GotestRunConfigurationProducer producer = new GotestRunConfigurationProducer(); GoTestRunConfiguration runConfiguration = createFileConfiguration(GotestFramework.INSTANCE, file.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(GotestFramework.INSTANCE, file.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createFileConfiguration(GobenchFramework.INSTANCE, file.getVirtualFile().getPath()); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } public void testSameConfigurationOnDirectory() { PsiFile file = myFixture.configureByText("a.go", "package main"); PsiDirectory directory = file.getParent(); assertNotNull(directory); ConfigurationContext configurationContext = new ConfigurationContext(directory); GotestRunConfigurationProducer producer = new GotestRunConfigurationProducer(); GoTestRunConfiguration runConfiguration = createDirectoryConfiguration(GotestFramework.INSTANCE, directory.getVirtualFile().getPath(), directory.getVirtualFile().getPath()); assertTrue(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createDirectoryConfiguration(GotestFramework.INSTANCE, directory.getVirtualFile().getPath() + "_vl", directory.getVirtualFile().getPath()); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createDirectoryConfiguration(GobenchFramework.INSTANCE, directory.getVirtualFile().getPath(), directory.getVirtualFile().getPath()); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); runConfiguration = createDirectoryConfiguration(GotestFramework.INSTANCE, directory.getVirtualFile().getPath(), directory.getVirtualFile().getPath() + "_vl"); assertFalse(producer.isConfigurationFromContext(runConfiguration, configurationContext)); } @NotNull private ConfigurationContext createConfigurationContext() { PsiElement at = myFixture.getFile().findElementAt(myFixture.getCaretOffset()); assertNotNull(at); return new ConfigurationContext(at); } @NotNull private GoTestRunConfiguration createPackageConfiguration(GoTestFramework framework, String pattern, String importPath) { GoTestRunConfigurationType configurationType = GoTestRunConfigurationType.getInstance(); GoTestRunConfiguration runConfiguration = new GoTestRunConfiguration(myFixture.getProject(), "name", configurationType); runConfiguration.setPattern(pattern); runConfiguration.setPackage(importPath); runConfiguration.setKind(GoTestRunConfiguration.Kind.PACKAGE); runConfiguration.setTestFramework(framework); return runConfiguration; } @NotNull private GoTestRunConfiguration createFileConfiguration(GoTestFramework framework, String path) { GoTestRunConfigurationType configurationType = GoTestRunConfigurationType.getInstance(); GoTestRunConfiguration runConfiguration = new GoTestRunConfiguration(myFixture.getProject(), "name", configurationType); runConfiguration.setFilePath(path); runConfiguration.setKind(GoTestRunConfiguration.Kind.FILE); runConfiguration.setTestFramework(framework); return runConfiguration; } @NotNull private GoTestRunConfiguration createDirectoryConfiguration(GoTestFramework framework, String path, String workingDirectoryPath) { GoTestRunConfigurationType configurationType = GoTestRunConfigurationType.getInstance(); GoTestRunConfiguration runConfiguration = new GoTestRunConfiguration(myFixture.getProject(), "name", configurationType); runConfiguration.setDirectoryPath(path); runConfiguration.setWorkingDirectory(workingDirectoryPath); runConfiguration.setKind(GoTestRunConfiguration.Kind.DIRECTORY); runConfiguration.setTestFramework(framework); return runConfiguration; } @Override protected String getBasePath() { return "testing/producer"; } } ================================================ FILE: tests/com/goide/runconfig/testing/GobenchEventsConverterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.testing.frameworks.gobench.GobenchFramework; import org.jetbrains.annotations.NotNull; public class GobenchEventsConverterTest extends GoEventsConverterTestCase { public void testSuccessBenchmark() { doTest(); } public void testBenchmarkWithoutSuffix() { doTest(); } public void testFailedBenchmark() { doTest(); } public void testMixedBenchmark() { doTest(); } public void testFailedCompilation() { doTest(); } @NotNull @Override protected String getBasePath() { return "testing/gobench"; } @NotNull @Override protected GoTestFramework getTestFramework() { return GobenchFramework.INSTANCE; } } ================================================ FILE: tests/com/goide/runconfig/testing/GocheckEventsConverterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.testing.frameworks.gocheck.GocheckFramework; import org.jetbrains.annotations.NotNull; public class GocheckEventsConverterTest extends GoEventsConverterTestCase { public void testPass() { doTest(); } public void testAssertions() { doTest(); } public void testAssertionsInvalidFormat() { doTest(); } public void testPanic() { doTest(); } public void testPanicInvalidFormat() { doTest(); } public void testFixtureStdOut() { doTest(); } public void testSuiteSetUpError() { doTest(); } public void testSuiteTearDownError() { doTest(); } public void testTestSetUpError() { doTest(); } public void testTestTearDownError() { doTest(); } public void testTestErrorWithFixtures() { doTest(); } public void testTestAndTestTearDownError() { doTest(); } public void testTestBothFixturesError() { doTest(); } public void testSkippingTests() { doTest(); } @NotNull @Override protected String getBasePath() { return "testing/gocheck"; } @NotNull @Override protected GoTestFramework getTestFramework() { return GocheckFramework.INSTANCE; } } ================================================ FILE: tests/com/goide/runconfig/testing/GotestEventsConverterTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.goide.runconfig.testing.frameworks.gotest.GotestFramework; import org.jetbrains.annotations.NotNull; public class GotestEventsConverterTest extends GoEventsConverterTestCase { public void testSingleTestFailed() { doTest(); } public void testSingleTestOk() { doTest(); } public void testMultipleTestsFailed() { doTest(); } public void testMultipleTestsOk() { doTest(); } public void testSingleTestLeadingSpaceOk() { doTest(); } public void testSkipTest() { doTest(); } public void testStdOut() { doTest(); } public void testOneLineEvents() { doTest(); } public void testUnicodeTestName() { doTest(); } public void testSubTests() { doTest(); } @NotNull @Override protected String getBasePath() { return "testing/gotest"; } @NotNull @Override protected GoTestFramework getTestFramework() { return GotestFramework.INSTANCE; } } ================================================ FILE: tests/com/goide/runconfig/testing/LoggingServiceMessageVisitor.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.runconfig.testing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import jetbrains.buildServer.messages.serviceMessages.*; import org.jetbrains.annotations.NotNull; import java.util.Map; public class LoggingServiceMessageVisitor implements ServiceMessageVisitor { private static final String MY_INDENT = " "; private final StringBuilder myLog = new StringBuilder(); private String myIndent = ""; @NotNull public String getLog() { return myLog.toString(); } private void increaseIndent() { myIndent += MY_INDENT; } private void decreaseIndent() { myIndent = StringUtil.trimEnd(myIndent, MY_INDENT); } private void append(@NotNull MessageWithAttributes message) { myLog.append(myIndent).append(message.getClass().getSimpleName()).append('\n'); increaseIndent(); increaseIndent(); for (Map.Entry entry : ContainerUtil.newTreeMap(message.getAttributes()).entrySet()) { String key = entry.getKey(); String value = "duration".equals(key) ? "42" : entry.getValue(); myLog.append(myIndent).append("- ").append(key).append("=") .append(value.replace("\n", "\\n")).append('\n'); } decreaseIndent(); decreaseIndent(); } @Override public void visitTestSuiteStarted(@NotNull TestSuiteStarted testSuiteStarted) { append(testSuiteStarted); increaseIndent(); } @Override public void visitTestSuiteFinished(@NotNull TestSuiteFinished testSuiteFinished) { decreaseIndent(); append(testSuiteFinished); } @Override public void visitTestStarted(@NotNull TestStarted testStarted) { append(testStarted); increaseIndent(); } @Override public void visitTestFinished(@NotNull TestFinished testFinished) { decreaseIndent(); append(testFinished); } @Override public void visitTestIgnored(@NotNull TestIgnored testIgnored) { append(testIgnored); } @Override public void visitTestStdOut(@NotNull TestStdOut testStdOut) { append(testStdOut); } @Override public void visitTestStdErr(@NotNull TestStdErr testStdErr) { append(testStdErr); } @Override public void visitTestFailed(@NotNull TestFailed testFailed) { append(testFailed); } @Override public void visitPublishArtifacts(@NotNull PublishArtifacts artifacts) { } @Override public void visitProgressMessage(@NotNull ProgressMessage message) { } @Override public void visitProgressStart(@NotNull ProgressStart start) { } @Override public void visitProgressFinish(@NotNull ProgressFinish finish) { } @Override public void visitBuildStatus(@NotNull BuildStatus status) { } @Override public void visitBuildNumber(@NotNull BuildNumber number) { } @Override public void visitBuildStatisticValue(@NotNull BuildStatisticValue value) { } @Override public void visitMessageWithStatus(@NotNull Message message) { } @Override public void visitBlockOpened(@NotNull BlockOpened opened) { } @Override public void visitBlockClosed(@NotNull BlockClosed closed) { } @Override public void visitCompilationStarted(@NotNull CompilationStarted started) { } @Override public void visitCompilationFinished(@NotNull CompilationFinished finished) { } @Override public void visitServiceMessage(@NotNull ServiceMessage message) { } } ================================================ FILE: tests/com/goide/sdk/GoPathLibraryTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.GoModuleType; import com.goide.project.GoApplicationLibrariesService; import com.goide.project.GoModuleLibrariesInitializer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.OrderEntryUtil; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @SuppressWarnings("ConstantConditions") public class GoPathLibraryTest extends GoCodeInsightFixtureTestCase { @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return new DefaultLightProjectDescriptor() { @NotNull @Override public ModuleType getModuleType() { return GoModuleType.getInstance(); } }; } private final Collection contentRootsToClean = ContainerUtil.newHashSet(); private final Collection tempRootsToClean = ContainerUtil.newHashSet(); @Override protected void setUp() throws Exception { super.setUp(); GoModuleLibrariesInitializer.setTestingMode(getTestRootDisposable()); } @Override protected void tearDown() throws Exception { try { for (VirtualFile file : tempRootsToClean) { ApplicationManager.getApplication().runWriteAction(() -> { try { file.delete(this); } catch (IOException e) { e.printStackTrace(); } }); } } finally { tempRootsToClean.clear(); } ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); try { for (ContentEntry entry : model.getContentEntries()) { if (contentRootsToClean.contains(entry.getFile())) { model.removeContentEntry(entry); } } ApplicationManager.getApplication().runWriteAction(model::commit); } finally { contentRootsToClean.clear(); if (!model.isDisposed()) model.dispose(); } super.tearDown(); } /** * src * goPath * - src * -- test */ public void testAddGoPathAsLibrary() throws IOException { VirtualFile goPath = createGoPath(); VirtualFile goPathContent = goPath.createChildDirectory(this, "src").createChildDirectory(this, "test"); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(goPath.getUrl()); assertLibrary(Collections.singletonList(goPathContent.getUrl()), "temp:///src"); } /** * src * goPath * - src * -- contentRoot * -- notContentRoot */ public void testExcludeChildContentRootFromLibrary() throws IOException { VirtualFile goPath = createGoPath(); VirtualFile src = goPath.createChildDirectory(this, "src"); VirtualFile contentRoot = src.createChildDirectory(this, "contentRoot"); VirtualFile notContentRoot = src.createChildDirectory(this, "notContentRoot"); addContentRoot(contentRoot); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(goPath.getUrl()); assertLibrary(Collections.singletonList(notContentRoot.getUrl()), "temp:///src", contentRoot.getUrl()); } /** * src * contentRoot * - gopath * -- src * --- test * otherGoPath * -- src * --- test */ public void testExcludeParentContentRootFromLibrary() throws IOException { VirtualFile contentRoot = createGoPath(); VirtualFile goPath = contentRoot.createChildDirectory(this, "gopath"); VirtualFile goPathContent = goPath.createChildDirectory(this, "src").createChildDirectory(this, "test"); VirtualFile otherGoPath = createGoPath(); VirtualFile otherGoPathContent = otherGoPath.createChildDirectory(this, "src").createChildDirectory(this, "test"); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(goPath.getUrl(), otherGoPath.getUrl()); assertLibrary(ContainerUtil.newHashSet(goPathContent.getUrl(), otherGoPathContent.getUrl()), "temp:///src"); addContentRoot(contentRoot); assertLibrary(Collections.singletonList(otherGoPathContent.getUrl()), "temp:///src", contentRoot.getUrl()); } /** * src * gopath * - src * -- subdir * --- contentRoot */ public void testUpdateLibraryOnAddingContentRoot() throws IOException { VirtualFile goPath = createGoPath(); VirtualFile goPathContent = goPath.createChildDirectory(this, "src").createChildDirectory(this, "subdir"); GoApplicationLibrariesService.getInstance().setLibraryRootUrls(goPath.getUrl()); assertLibrary(Collections.singletonList(goPathContent.getUrl()), "temp:///src"); VirtualFile contentRoot = goPathContent.createChildDirectory(this, "contentRoot"); addContentRoot(contentRoot); assertLibrary(Collections.singletonList(goPathContent.getUrl()), "temp:///src", contentRoot.getUrl()); } private void addContentRoot(@NotNull VirtualFile contentRoot) { ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel(); try { model.addContentEntry(contentRoot); contentRootsToClean.add(contentRoot); model.commit(); } finally { if (!model.isDisposed()) model.dispose(); } } private void assertLibrary(@NotNull Collection libUrls, String... exclusionUrls) { UIUtil.dispatchAllInvocationEvents(); GoModuleLibrariesInitializer initializer = myModule.getComponent(GoModuleLibrariesInitializer.class); ModuleRootManager model = ModuleRootManager.getInstance(myModule); LibraryOrderEntry libraryOrderEntry = OrderEntryUtil.findLibraryOrderEntry(model, initializer.getLibraryName()); if (libUrls.isEmpty()) { assertNull(libraryOrderEntry); return; } LibraryEx library = (LibraryEx)libraryOrderEntry.getLibrary(); assertNotNull(library); assertSameElements(Arrays.asList(library.getUrls(OrderRootType.CLASSES)), libUrls); assertSameElements(library.getExcludedRootUrls(), exclusionUrls); } private VirtualFile createGoPath() throws IOException { VirtualFile goPath = VfsUtil.findFileByIoFile(FileUtil.createTempDirectory("go", "path"), true); tempRootsToClean.add(goPath); return goPath; } @Override protected boolean isWriteActionRequired() { return true; } } ================================================ FILE: tests/com/goide/sdk/GoSdkUtilTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.sdk; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GoSdkUtilTest { @Test public void testCompareVersions() { assertEquals(-1, GoSdkUtil.compareVersions("1.1.2", "1.1.3")); assertEquals(-1, GoSdkUtil.compareVersions("1.1.2", "1.2.1")); assertEquals(-1, GoSdkUtil.compareVersions("1.1.2", "2.1.1")); assertEquals(-1, GoSdkUtil.compareVersions("1.2", "1.2.1")); assertEquals(-1, GoSdkUtil.compareVersions("1", "1.1")); assertEquals(-1, GoSdkUtil.compareVersions("1.4rc2", "1.4")); assertEquals(0, GoSdkUtil.compareVersions("1.2.3", "1.2.3")); assertEquals(0, GoSdkUtil.compareVersions("1.2", "1.2")); assertEquals(0, GoSdkUtil.compareVersions("1", "1")); assertEquals(0, GoSdkUtil.compareVersions("1.4rc2", "1.4rc2")); assertEquals(1, GoSdkUtil.compareVersions("1.2.4", "1.2.3")); assertEquals(1, GoSdkUtil.compareVersions("1.3.3", "1.2.4")); assertEquals(1, GoSdkUtil.compareVersions("2.2.3", "1.4.4")); assertEquals(1, GoSdkUtil.compareVersions("1.2.1", "1.2")); assertEquals(1, GoSdkUtil.compareVersions("1.4rc2", "1.3")); assertEquals(1, GoSdkUtil.compareVersions("1.5beta1", "1.4rc2")); } @Test public void testParseGoVersion() { assertEquals("1.5beta1", GoSdkUtil.parseGoVersion("const theVersion = `go1.5beta1`")); assertEquals("1.4rc2", GoSdkUtil.parseGoVersion("const theVersion = `go1.4rc2`")); assertEquals("1.4.2", GoSdkUtil.parseGoVersion("const theVersion = `go1.4.2`")); assertEquals("1.4.1 (appengine-1.9.18)", GoSdkUtil.parseGoVersion("const theVersion = `go1.4.1 (appengine-1.9.18)`")); assertEquals("devel +e8057df Sun May 3 05:34:01 2015 +0000", GoSdkUtil.parseGoVersion("const theVersion = `devel +e8057df Sun May 3 05:34:01 2015 +0000`")); } } ================================================ FILE: tests/com/goide/stubs/GoPackageClauseStubTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoFile; import com.goide.psi.GoPackageClause; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.testFramework.exceptionCases.AssertionErrorCase; public class GoPackageClauseStubTest extends GoCodeInsightFixtureTestCase { public void testStub() { GoFile file = (GoFile)myFixture.addFileToProject("bar/bar.go", "package bar; import `foo`; func _() { println(CONST_NAME) }"); failOnFileLoading(); file.getPackageName(); } public void testParsingPsi() throws Throwable { GoFile file = (GoFile)myFixture.addFileToProject("bar/bar.go", "package bar; import `foo`; func _() { println(CONST_NAME) }"); failOnFileLoading(); GoPackageClause packageClause = file.getPackage(); assertNotNull(packageClause); assertException(new AssertionErrorCase() { @Override public void tryClosure() { try { packageClause.getIdentifier(); } catch (AssertionError e) { String message = e.getMessage(); assertTrue(message.contains("Access to tree elements not allowed in tests")); assertTrue(message.contains("bar.go")); throw e; } } }); } private void failOnFileLoading() { ((PsiManagerImpl)myFixture.getPsiManager()).setAssertOnFileLoadingFilter(VirtualFileFilter.ALL, getTestRootDisposable()); } } ================================================ FILE: tests/com/goide/stubs/GoStubTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.stubs; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiFile; import com.intellij.testFramework.ParsingTestCase; import java.io.File; import java.io.IOException; public class GoStubTest extends GoCodeInsightFixtureTestCase { public void testStub() throws IOException { doTest(true); } public void testStubMismatch2540() throws IOException { doTest(false); } private void doTest(boolean checkErrors) throws IOException { String fileName = getTestName(true) + ".go"; String text = FileUtil.loadFile(new File(getTestDataPath(), fileName)); PsiFile file = myFixture.addFileToProject(fileName, text); String s = buildStubTreeText(getProject(), file.getVirtualFile(), text, checkErrors); ParsingTestCase.doCheckResult(getTestDataPath(), getTestName(true) + ".txt", s); } @Override protected String getBasePath() { return "stubs"; } } ================================================ FILE: tests/com/goide/type/GoExpectedTypesTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.type; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.goide.psi.GoExpression; import com.goide.psi.impl.GoTypeUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; @SdkAware public class GoExpectedTypesTest extends GoCodeInsightFixtureTestCase { public void testAssignment() { doStatementTest("var a int; a = asd()", "int"); } public void testTwoVariablesAssignment() { doStatementTest("var (a int; b string); a, b = asd()", "int, string; int"); } public void testTwoVariablesAssignmentWithTeoRightExpressions() { doStatementTest("var (a int; b string); a, b = asd(), \"qwe\"", "int"); } public void testTwoVariablesAssignmentWithFewLeftAndRightExpressions() { doStatementTest("var (a, c int; b string); a, b, c = 1, asd(), \"qwe\"", "string"); } public void testTwoVariablesAssignmentWithLeftWithoutRightExpressions() { doStatementTest("var (a, c int; b string); a, b, c = 1, asd()", "string"); } public void testShortVarDeclaration() { doStatementTest(" c := asd()", "interface{}"); } public void testShortVarDeclarationWithTwoVariablesAtRight() { doStatementTest(" c, d := asd()", "interface{}, interface{}; interface{}"); } public void testVarDeclaration() { doStatementTest(" var a int = asd()", "int"); } public void testVarDeclarationWithStructTypeAndTwoVariablesAtRight() { doStatementTest(" var a, b struct{i int} = asd()", "struct{i int}, struct{i int}; struct{i int}"); } public void testVarDeclWithTwoMembersAtRightAndLeft() { doStatementTest(" var a, b struct{i int} = struct{i int} {1}, asd()", "struct{i int}"); } public void testCall() { doTopLevelTest(" func f(string){}; func _() { f(asd()) }", "string"); } public void testCallWithThreeParametersInReceiver() { doTopLevelTest(" func f(string, int, int){}; func _() { f(asd()) }", "string, int, int; string"); } public void testCallWithTwoArgumentsAndThreeParametersInReceiver() { doTopLevelTest(" func f(string, int, int){}; func _() { f(\"\", asd()) }", "int"); } public void testCallWithNoParametersInReceiver() { doTopLevelTest(" func f(){}; func _() { f(asd()) }", "interface{}"); } public void testCallWithNoParametersInReceiverAndThreeArguments() { doTopLevelTest(" func f(){}; func _() { f(1, 2, asd()) }", "interface{}"); } public void testCallWithOneExpectedType() { doTopLevelTest(" func f(int, int){}; func _() { f(1, asd()) }", "int"); } public void testCallWithParamDefinition() { doTopLevelTest(" func f(i, j int, string, int){}; func _() { f(asd()) }", "int, int, string, int; int"); } public void testRange() { doStatementTest("for _ = range asd() {}", "interface{}"); } public void testRangeWithTwoArguments() { doStatementTest("for _, _ = range asd() {}", "interface{}"); } public void testCaseStatement() { doStatementTest("var k int; switch k { case asd(): }", "int"); } public void testCaseStatementWithoutArg() { doStatementTest("var k int; switch { case asd(): }", "bool"); } public void testCaseStatementOnStatementAndExpr() { doStatementTest("var k int; switch q:=1; q { case asd(): }", "int"); } public void testSendStatementArg() { doStatementTest("var ch chan int; ch <- asd()", "int"); } public void testSendStatementChan() { doStatementTest("var i string; asd() <- i", "chan string"); } public void testSendStatementArgInSelect() { doStatementTest("var ch chan int; select { case ch <- asd() : }", "int"); } public void testSendUnaryOperation() { doStatementTest("var i int; i = <-asd()", "chan int"); } public void testSendUnaryOperationVarSpec() { doStatementTest("i := <-asd()", "chan interface{}"); } public void testSendUnaryOperationNoExpectedType() { doStatementTest(" <-asd()", "chan interface{}"); } public void testRecvStatement() { doStatementTest("var i string; select { case <-asd() : }", "chan interface{}"); } public void testRecvStatementOnFunc() { doStatementTest("var i string; select { case asd() : }", "interface{}"); } public void testRecvStatementOnVarAssign() { doStatementTest("var i string; select { case i = asd() : }", "string"); } public void testRecvStatementOnShortVarAssign() { doStatementTest("select { case i := asd() : }", "interface{}"); } private void doTopLevelTest(@NotNull String text, @NotNull String expectedTypeText) { myFixture.configureByText("a.go", "package a;" + text); PsiElement elementAt = findElementAtCaretOrInSelection(); GoExpression typeOwner = PsiTreeUtil.getNonStrictParentOfType(elementAt, GoExpression.class); assertNotNull("Cannot find type owner. Context element: " + elementAt.getText(), typeOwner); assertEquals(expectedTypeText, StringUtil.join(GoTypeUtil.getExpectedTypes(typeOwner), PsiElement::getText, "; ")); } private void doStatementTest(@NotNull String text, @NotNull String expectedTypeText) { doTopLevelTest("func _() {\n" + text + "\n}", expectedTypeText); } } ================================================ FILE: tests/com/goide/type/GoTypeResolveTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.type; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.SdkAware; import com.goide.psi.GoType; import com.goide.psi.GoTypeOwner; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; @SdkAware public class GoTypeResolveTest extends GoCodeInsightFixtureTestCase { public void testAnon() { doTopLevelTest("type A struct{};type E A;type B struct{ E };func (e E) foo() {};func main() { b := B{}; b.E }", "E"); } public void testAnon2() { doTopLevelTest("type A struct{};type E A;type B struct{ *E };func (e E) foo() {};func main() { b := B{}; b.E }", "*E"); } public void testTypeSwitchDeclaration() { doStatementTest("switch foo := \"hello\".(type) {}", "string"); } public void testTypeSwitchUsageInContext() { doStatementTest("switch foo := \"hello\".(type) { case bool:\n println(foo)\n}", "bool"); } public void testWrappedSlice() { doTopLevelTest("type Foo int[]\nfunc _() { var foo Foo\nbar := foo[2:9]", "Foo"); } public void testSlice() { doStatementTest("var foo []int\nbar := foo[2:9]", "[]int"); } public void testRangeOverString() { doStatementTest("for _, foo := range \"hello\" {}", "int32"); } public void testIndexExpressionOfString() { doStatementTest("foo := \"hello\"\na := foo[0]", "byte"); } public void testIndexExpressionOfStringLiteral() { doExpressionTest("\"hello\"[0]", "byte"); } public void testIndexExpressionOfPointer() { doStatementTest("var buckhash *[20]*int\nfoo := buckhash[0]", "*int"); } public void testNestedTypeSwitchUsageInContext() { doStatementTest("var p interface{}\n" + "switch foo := p.(type) {\n" + "case int:\n" + " switch p.(type) {\n" + " case bool:" + " println(foo)\n" + " }\n" + "}", "int"); } public void testIndexExpression() { doTopLevelTest("type foo string; var bar []foo; func _() { println(bar[0]) }", "foo"); doTopLevelTest("var bar []string; func _() { println(bar[0]) }", "string"); } public void testFuncLiteral() { doTopLevelTest("func voidFunction(a int) {} func _() { voidFunction() }", "func (a int)"); } public void testCallExpression() { doTopLevelTest("func voidFunction() int {} func _() { voidFunction() }", "int"); } public void testCallExpressionOnVoidFunction() { doTopLevelTest("func voidFunction() {} func _() { voidFunction() }", ""); } public void testCallExpressionOnVoidFunction2() { doTopLevelTest("func voidFunction() () {} func _() { voidFunction() }", ""); } private void doTopLevelTest(@NotNull String text, @NotNull String expectedTypeText) { myFixture.configureByText("a.go", "package a;" + text); PsiElement elementAt = findElementAtCaretOrInSelection(); GoTypeOwner typeOwner = PsiTreeUtil.getNonStrictParentOfType(elementAt, GoTypeOwner.class); assertNotNull("Cannot find type owner. Context element: " + elementAt.getText(), typeOwner); GoType type = typeOwner.getGoType(null); assertEquals(expectedTypeText, type == null ? "" : type.getText()); } private void doStatementTest(@NotNull String text, @NotNull String expectedTypeText) { doTopLevelTest("func _() {\n" + text + "\n}", expectedTypeText); } private void doExpressionTest(@NotNull String text, @NotNull String expectedTypeText) { doStatementTest("a := " + text, expectedTypeText); } } ================================================ FILE: tests/com/goide/type/GoUnderlyingTypeTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.type; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoType; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; public class GoUnderlyingTypeTest extends GoCodeInsightFixtureTestCase { private void doTest(@NotNull String text, String expected) { myFixture.configureByText("a.go", "package a\n" + text); PsiElement element = myFixture.getFile().findElementAt(myFixture.getEditor().getCaretModel().getOffset()); GoType type = PsiTreeUtil.getParentOfType(element, GoType.class); assertNotNull(type); assertEquals(expected, type.getUnderlyingType().getText()); } public void testT1() { doTest("type T1 string", "string"); } public void testT1SOE() { doTest("type T1 T2; type T2 T1", "T1 T2"); } public void testT2SOE() { doTest("type T1 T2; type T2 T3; type T3 T2", "T2 T3"); } public void testT2() { doTest("type T1 string; type T2 T1", "string"); } public void testT3() { doTest("type T1 string; type T2 T1; type T3 []T1", "[]T1"); } public void testT4() { doTest("type T1 string; type T2 T1; type T3 []T1; type T4 T3", "[]T1"); } public void testLiteralType() { doTest("type T1 string; type T4 []T1", "[]T1"); } } ================================================ FILE: tests/com/goide/usages/GoFileStructureGroupRuleTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.usages; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoFunctionDeclaration; import com.goide.psi.GoTypeSpec; import com.intellij.psi.PsiElement; import com.intellij.usageView.UsageInfo; import com.intellij.usages.PsiElementUsageGroupBase; import com.intellij.usages.Usage; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageInfo2UsageAdapter; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GoFileStructureGroupRuleTest extends GoCodeInsightFixtureTestCase { public void testMethod() { assertInstanceOf(getGroupElement(), GoFunctionDeclaration.class); } public void testType() { assertInstanceOf(getGroupElement(), GoTypeSpec.class); } @NotNull private PsiElement getGroupElement() { UsageGroup group = GoFileStructureGroupRuleProvider.USAGE_GROUPING_RULE.groupUsage(findSingleUsage()); assertNotNull(group); assertInstanceOf(group, PsiElementUsageGroupBase.class); return ((PsiElementUsageGroupBase)group).getElement(); } @NotNull private Usage findSingleUsage() { Collection infos = myFixture.testFindUsages(getTestName(true) + ".go"); assertEquals(1, infos.size()); UsageInfo item = ContainerUtil.getFirstItem(infos); assertNotNull(item); return new UsageInfo2UsageAdapter(item); } @Override protected String getBasePath() { return "usages"; } } ================================================ FILE: tests/com/goide/util/GoBuildMatcherTest.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoCodeInsightFixtureTestCase; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import org.jetbrains.annotations.NotNull; public class GoBuildMatcherTest extends GoCodeInsightFixtureTestCase { public void testMatchFile() { GoBuildMatcher matcher; matcher = new GoBuildMatcher(new GoTargetSystem("plan9", "arm", "1.4", null, ThreeState.UNSURE)); checkMatchFile(matcher, true, "foo_arm.go", ""); checkMatchFile(matcher, false, "foo1_arm.go", "// +build linux"); checkMatchFile(matcher, false, "foo_darwin.go", ""); checkMatchFile(matcher, true, "foo.go", ""); checkMatchFile(matcher, false, "foo1.go", "// +build linux"); matcher = new GoBuildMatcher(new GoTargetSystem("android", "arm", "1.4", null, ThreeState.UNSURE)); checkMatchFile(matcher, true, "foo_linux.go", ""); checkMatchFile(matcher, true, "foo_android.go", ""); checkMatchFile(matcher, false, "foo_plan9.go", ""); checkMatchFile(matcher, true, "android.go", ""); checkMatchFile(matcher, true, "android.go", "// +build linux\n"); checkMatchFile(matcher, true, "plan9.go", ""); checkMatchFile(matcher, true, "plan9_test.go", ""); } public void testMatchFileName() { GoBuildMatcher matcher = new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)); assertTrue(matcher.matchFileName("file.go")); assertTrue(matcher.matchFileName("file_foo.go")); assertTrue(matcher.matchFileName("file_linux.go")); assertTrue(matcher.matchFileName("file_amd64.go")); assertTrue(matcher.matchFileName("file_linux_test.go")); assertTrue(matcher.matchFileName("file_amd64_test.go")); assertTrue(matcher.matchFileName("file_foo_linux.go")); assertTrue(matcher.matchFileName("file_foo_linux_test.go")); assertTrue(matcher.matchFileName("file_foo_amd64.go")); assertTrue(matcher.matchFileName("file_foo_amd64_test.go")); assertTrue(matcher.matchFileName("file_linux_amd64.go")); assertTrue(matcher.matchFileName("file_linux_amd64_test.go")); assertFalse(matcher.matchFileName("file_386.go")); assertFalse(matcher.matchFileName("file_windows.go")); assertFalse(matcher.matchFileName("file_windows_test.go")); assertFalse(matcher.matchFileName("file_linux_386.go")); assertFalse(matcher.matchFileName("file_linux_386_test.go")); assertFalse(matcher.matchFileName("file_windows_amd64.go")); assertFalse(matcher.matchFileName("file_windows_amd64_test.go")); assertFalse(matcher.matchFileName("file_darwin_arm.go")); assertFalse(matcher.matchFileName("file_foo_arm.go")); } public void testMatchBuildFlags() { GoBuildMatcher matcher = new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)); assertFalse(matcher.matchBuildFlag("")); assertFalse(matcher.matchBuildFlag("!!")); assertTrue(matcher.matchBuildFlag("linux,amd64")); assertTrue(matcher.matchBuildFlag("linux,amd64,!foo")); assertFalse(matcher.matchBuildFlag("linux,amd64,foo")); assertTrue(matcher.matchBuildFlag("!windows,!foo")); } public void testMatchCompiler() { assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)).matchBuildFlag("gc")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)).matchBuildFlag("gccgo")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", "gc", ThreeState.UNSURE)).matchBuildFlag("gc")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", "gccgo", ThreeState.UNSURE)).matchBuildFlag("gccgo")); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", "gc", ThreeState.UNSURE)).matchBuildFlag("gccgo")); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", "gccgo", ThreeState.UNSURE)).matchBuildFlag("gc")); } public void testMatchVersion() { assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)).matchBuildFlag("go1.4")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)).matchBuildFlag("go1.3")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE)).matchBuildFlag("go1.2")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", "gc", ThreeState.UNSURE)).matchBuildFlag("go1.1")); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.2", "gc", ThreeState.UNSURE)).matchBuildFlag("go1.1")); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.2", "gc", ThreeState.UNSURE)).matchBuildFlag("go1.3")); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.2", "gc", ThreeState.UNSURE)).matchBuildFlag("go1.4")); } public void testMatchCgo() { assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.YES)).matchBuildFlag("cgo")); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.NO)).matchBuildFlag("cgo")); } public void testCgoCImport() { myFixture.configureByText("a.go", "package a; import \"C\""); PsiFile file = myFixture.getFile(); assertTrue(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.YES)).matchFile(file)); assertFalse(new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.NO)).matchFile(file)); } public void testMatchSupportedTags() { GoBuildMatcher matcher = new GoBuildMatcher(new GoTargetSystem("linux", "amd64", "1.4", null, ThreeState.UNSURE, "foo")); assertTrue(matcher.matchBuildFlag("linux,amd64")); assertTrue(matcher.matchBuildFlag("linux,amd64,foo")); assertFalse(matcher.matchBuildFlag("linux,amd64,!foo")); assertTrue(matcher.matchBuildFlag("linux,amd64,!bar")); assertFalse(matcher.matchBuildFlag("linux,amd64,bar")); } private void checkMatchFile(@NotNull GoBuildMatcher matcher, boolean expected, @NotNull String fileName, @NotNull String text) { myFixture.configureByText(fileName, text + "\n\n package main\n\n func main() {}"); assertEquals(fileName + ":" + text, expected, matcher.matchFile(myFixture.getFile())); } } ================================================ FILE: tests/com/goide/util/GoExpressionUtilTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoParametrizedTestBase; import com.goide.SdkAware; import com.goide.psi.GoCallExpr; import com.goide.psi.GoExpression; import com.goide.psi.impl.GoExpressionUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.List; @RunWith(Parameterized.class) @SdkAware public class GoExpressionUtilTest extends GoParametrizedTestBase { private final String vars; private final String left; private final String right; private final boolean ok; @Parameterized.Parameters(name = "{1} == {2}; {0}") public static Collection data() { return Arrays.asList(new Object[][]{ {"var a = 1", "a", "a", true}, //{"", "1.00", "1.0", false}, {"var a, b = 1, 2", "a + b", "a + b", true}, {"var a, b = 1, 2", "a + b", "(a + b)", true}, {"var a, b = 1, 2", "+a", "a", true}, {"var a, b = 1, 2", "a + b", "(+((+(a + b))))", true}, {"var a, b []int", "len(a)", "len(a)", false}, {"var a, b = 1, 2", "a + b", "a - b", false}, {"var a, b = 1, 2", "a + b", "a >> b", false}, {"var a, b = 1, 2", "a + b", " -(a + b)", false}, {"var a, b = 1, 2", "1", " 23", false}, {"var a, b = 1, 2", "1", " 1", true}, {"var a, b = 1, 2", "105 - 3", " 105 - (+3)", true}, {"var a, b = 1, 2", "\"hello\"", " `hello`", true}, {"var a, b []int", "a[1]", "a[2]", false}, {"var a, b []int", "a[1 : 2]", "a[1 : 2]", true}, {"type T struct{name string}", "&T{name : \"name\"}", "&T{name : \"name\"}", true}, {"type T struct{name string}", "&T{name : \"name\"}", "&T{name : \"\"}", false}, {"func f() int {return 0}", "f()", "f()", false}, {"var i interface{}; type T int", "i.(T)", "i.(T)", true}, {"var i interface{}; type T int", "(a).(T)", "i.(T)", false}, }); } @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") public GoExpressionUtilTest(@NotNull String vars, @NotNull String left, @NotNull String right, boolean ok) { this.vars = vars; this.left = left; this.right = right; this.ok = ok; } @Override protected void doTest() { PsiFile file = myFixture.configureByText("a.go", "package main\n func foo(i interface{}, j interface{}){}\n" + vars + "\n func _(){\n foo(" + left + ", " + right + ")\n}"); myFixture.checkHighlighting(); GoCallExpr call = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), GoCallExpr.class); assert call != null; List expressions = call.getArgumentList().getExpressionList(); assertTrue(left + " should " + (ok ? "" : "not ") + "be identical " + right, ok == GoExpressionUtil.identical(expressions.get(0), expressions.get(1))); } } ================================================ FILE: tests/com/goide/util/GoPackageUtilTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.project.GoBuildTargetSettings; import com.goide.project.GoModuleSettings; import com.goide.sdk.GoPackageUtil; public class GoPackageUtilTest extends GoCodeInsightFixtureTestCase { public void testPackageNameOfTestPackageInNonTestFile() { myFixture.configureByText("foo.go", "package foo"); myFixture.configureByText("foo_test.go", "package foo_test"); myFixture.configureByText("main.go", "package main"); myFixture.configureByText("docs.go", "package documentation"); myFixture.configureByText("bar_test.go", "package tricky_package_name"); myFixture.configureByText("non_test_file.go", "package non_test"); myFixture.configureByText("ignored.go", "// +build ignored\n\npackage ignored"); assertSameElements(GoPackageUtil.getAllPackagesInDirectory(myFixture.getFile().getContainingDirectory(), null, true), "foo", "main", "non_test", "tricky_package_name"); assertSameElements(GoPackageUtil.getAllPackagesInDirectory(myFixture.getFile().getContainingDirectory(), null, false), "foo", "foo_test", "main", "non_test", "tricky_package_name"); } public void testInvalidateCacheOnChangingBuildTags() { myFixture.configureByText("foo.go", "// +build ignored\n\npackage ignored"); myFixture.configureByText("bar.go", "package not_ignored"); assertSameElements(GoPackageUtil.getAllPackagesInDirectory(myFixture.getFile().getContainingDirectory(), null, true), "not_ignored"); GoBuildTargetSettings newSettings = new GoBuildTargetSettings(); newSettings.customFlags = new String[]{"ignored"}; GoModuleSettings.getInstance(myFixture.getModule()).setBuildTargetSettings(newSettings); assertSameElements(GoPackageUtil.getAllPackagesInDirectory(myFixture.getFile().getContainingDirectory(), null, true), "not_ignored", "ignored"); } } ================================================ FILE: tests/com/goide/util/GoStringLiteralEscaperEscapeStringTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class GoStringLiteralEscaperEscapeStringTest { @Parameterized.Parameter public String input; @Parameterized.Parameter(1) public String expected; @Parameterized.Parameters(name = "{0}") public static Collection data() { return Arrays.asList(new Object[][]{ {"abc", "abc"}, {"歡迎", "歡迎"}, {"歡\t迎", "歡\\t迎"}, {"a\u0007b", "a\\ab"}, {"a\u0008b", "a\\bb"}, {"a\u000Cb", "a\\fb"}, {"a\nb", "a\\nb"}, {"a\rb", "a\\rb"}, {"a\tb", "a\\tb"}, {"a\u000bb", "a\\vb"}, {"a\\b", "a\\\\b"}, {"a'b", "a\\'b"}, {"a\"b", "a\\\"b"}, {"a\u0001b", "a\\u0001b"}, {"\uD801\uDC37", "\uD801\uDC37"}, {"\uD852\uDF62", "\uD852\uDF62"}, }); } @Test public void testEscapeString() { StringBuilder outChars = new StringBuilder(); GoStringLiteralEscaper.escapeString(input, outChars); assertEquals(expected, outChars.toString()); } } ================================================ FILE: tests/com/goide/util/GoStringLiteralEscaperTest.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide.util; import com.goide.GoCodeInsightFixtureTestCase; import com.goide.psi.GoStringLiteral; import com.goide.psi.impl.GoElementFactory; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.psi.LiteralTextEscaper; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.testFramework.PlatformTestUtil; import org.jetbrains.annotations.NotNull; import java.util.Locale; public class GoStringLiteralEscaperTest extends GoCodeInsightFixtureTestCase { private static String decodeRange(@NotNull GoStringLiteral expr, @NotNull TextRange range) { StringBuilder builder = new StringBuilder(); expr.createLiteralTextEscaper().decode(range, builder); return builder.toString(); } public void testEscaperDecodeString() { GoStringLiteral expr = createStringFromText("\\nfoo"); assertNotNull(expr); assertEquals("fo", decodeRange(expr, TextRange.create(3, 5))); assertEquals("\n", decodeRange(expr, TextRange.create(1, 3))); } public void testEscaperDecodeRawString() { GoStringLiteral expr = createRawStringFromText("\nfoo"); assertNotNull(expr); assertEquals("fo", decodeRange(expr, TextRange.create(2, 4))); assertEquals("\n", decodeRange(expr, TextRange.create(1, 2))); } public void testEscaperOffsetInStringHost() { GoStringLiteral expr = createStringFromText("\\nfoo"); assertNotNull(expr); LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange newLineFoo = TextRange.create(1, 6); escaper.decode(newLineFoo, new StringBuilder()); assertEquals(1, escaper.getOffsetInHost(0, newLineFoo)); assertEquals(3, escaper.getOffsetInHost(1, newLineFoo)); assertEquals(4, escaper.getOffsetInHost(2, newLineFoo)); assertEquals(5, escaper.getOffsetInHost(3, newLineFoo)); assertEquals(6, escaper.getOffsetInHost(4, newLineFoo)); assertEquals(-1, escaper.getOffsetInHost(5, newLineFoo)); } public void testEscaperOffsetInRawStringHost() { GoStringLiteral expr = createRawStringFromText("\nfoo"); assertNotNull(expr); LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange newLineFoo = TextRange.create(1, 5); escaper.decode(newLineFoo, new StringBuilder()); assertEquals(1, escaper.getOffsetInHost(0, newLineFoo)); assertEquals(2, escaper.getOffsetInHost(1, newLineFoo)); assertEquals(3, escaper.getOffsetInHost(2, newLineFoo)); assertEquals(4, escaper.getOffsetInHost(3, newLineFoo)); assertEquals(5, escaper.getOffsetInHost(4, newLineFoo)); assertEquals(-1, escaper.getOffsetInHost(5, newLineFoo)); } public void testEscaperOffsetInStringHostSubString() { GoStringLiteral expr = createStringFromText("\\nfoo"); assertNotNull(expr); LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange fooOnly = TextRange.create(3, 6); escaper.decode(fooOnly, new StringBuilder()); assertEquals(3, escaper.getOffsetInHost(0, fooOnly)); assertEquals(4, escaper.getOffsetInHost(1, fooOnly)); assertEquals(5, escaper.getOffsetInHost(2, fooOnly)); assertEquals(6, escaper.getOffsetInHost(3, fooOnly)); assertEquals(-1, escaper.getOffsetInHost(4, fooOnly)); } public void testEscaperOffsetInRawStringHostSubString() { GoStringLiteral expr = createRawStringFromText("\nfoo"); assertNotNull(expr); LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange fooOnly = TextRange.create(2, 5); escaper.decode(fooOnly, new StringBuilder()); assertEquals(2, escaper.getOffsetInHost(0, fooOnly)); assertEquals(3, escaper.getOffsetInHost(1, fooOnly)); assertEquals(4, escaper.getOffsetInHost(2, fooOnly)); assertEquals(5, escaper.getOffsetInHost(3, fooOnly)); assertEquals(-1, escaper.getOffsetInHost(4, fooOnly)); } public void testEscaperOffsetInSingleCharString() { doSingleCharTest(createStringFromText("c")); } public void testEscaperOffsetInSingleCharRawString() { doSingleCharTest(createRawStringFromText("c")); } private static void doSingleCharTest(@NotNull GoStringLiteral expr) { LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange range = TextRange.create(1, 2); escaper.decode(range, new StringBuilder()); assertEquals(1, escaper.getOffsetInHost(0, range)); assertEquals(2, escaper.getOffsetInHost(1, range)); assertEquals(-1, escaper.getOffsetInHost(2, range)); } public void testEscaperOffsetInSingleEscapedCharString() { GoStringLiteral expr = createStringFromText("\\n"); assertNotNull(expr); LiteralTextEscaper escaper = expr.createLiteralTextEscaper(); TextRange range = TextRange.create(1, 3); escaper.decode(range, new StringBuilder()); assertEquals(1, escaper.getOffsetInHost(0, range)); assertEquals(3, escaper.getOffsetInHost(1, range)); assertEquals(-1, escaper.getOffsetInHost(2, range)); } // region decode tests public void testDecodeEscapedString() { GoStringLiteral expr = createStringFromText("\\t\\n\\b"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 7)); assertEquals("\t\n\b", a); } public void testDecodeEscapedVerticalTabString() { GoStringLiteral expr = createStringFromText("\\v"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 3)); assertEquals("\013", a); } public void testDecodeEscapedBellString() { GoStringLiteral expr = createStringFromText("\\a"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 3)); assertEquals("\007", a); } public void testDecodeOctalCharString() { GoStringLiteral expr = createStringFromText("\\011"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 5)); assertEquals("\t", a); } public void testDecodeHexCharString() { GoStringLiteral expr = createStringFromText("\\x41"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 5)); assertEquals("A", a); } public void testDecodeShortUnicodeCharString() { GoStringLiteral expr = createStringFromText("\\u8a9e"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 7)); assertEquals("語", a); } public void testDecodeLongUnicodeCharString() { PlatformTestUtil.withEncoding(CharsetToolkit.UTF8, () -> { GoStringLiteral expr = createStringFromText("\\U00008a9e"); assertNotNull(expr); String a = decodeRange(expr, TextRange.create(1, 11)); assertEquals("語", a); }); } public void testQuote() { PlatformTestUtil.withEncoding(CharsetToolkit.UTF8, () -> { GoStringLiteral expr = createStringFromText("import \\\"fmt\\\""); assertNotNull(expr); assertEquals("\"fmt\"", decodeRange(expr, TextRange.create(8, 15))); }); } // endregion @NotNull private GoStringLiteral createStringFromText(@NotNull String text) { return GoElementFactory.createStringLiteral(myFixture.getProject(), String.format(Locale.US, "\"%s\"", text)); } @NotNull private GoStringLiteral createRawStringFromText(@NotNull String text) { return GoElementFactory.createStringLiteral(myFixture.getProject(), String.format(Locale.US, "`%s`", text)); } } ================================================ FILE: utils/src/com/goide/GoConstants.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.notification.NotificationGroup; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import java.util.Set; public class GoConstants { public static final String MODULE_TYPE_ID = "GO_MODULE"; public static final String SDK_TYPE_ID = "Go SDK"; public static final String PATH = "PATH"; public static final String GO_PATH = "GOPATH"; public static final String GO_ROOT = "GOROOT"; public static final String GO_VENDORING_EXPERIMENT = "GO15VENDOREXPERIMENT"; public static final String GO_LIBRARIES_SERVICE_NAME = "GoLibraries"; public static final String GO_LIBRARIES_CONFIG_FILE = "goLibraries.xml"; public static final String GO_MODULE_SESTTINGS_SERVICE_NAME = "Go"; private static final String IDENTIFIER_REGEX = "[\\p{javaLetter}_][\\p{javaLetterOrDigit}_]*"; public static final String TEST_NAME_REGEX = IDENTIFIER_REGEX + "(/\\S*)?"; public static final String TESTDATA_NAME = "testdata"; public static final String TEST_SUFFIX = "_test"; public static final String TEST_SUFFIX_WITH_EXTENSION = "_test.go"; public static final String TEST_PREFIX = "Test"; public static final String BENCHMARK_PREFIX = "Benchmark"; public static final String EXAMPLE_PREFIX = "Example"; public static final String TEST_MAIN = "TestMain"; public static final String MAIN = "main"; public static final String INIT = "init"; public static final String IOTA = "iota"; public static final String DOCUMENTATION = "documentation"; public static final String C_PATH = "C"; public static final String TESTING_PATH = "testing"; public static final String VENDOR = "vendor"; public static final String INTERNAL = "internal"; public static final String INTERFACE_TYPE = "interface{}"; public static final NotificationGroup GO_NOTIFICATION_GROUP = NotificationGroup.balloonGroup("Go plugin notifications"); public static final NotificationGroup GO_EXECUTION_NOTIFICATION_GROUP = NotificationGroup.toolWindowGroup("Go Execution", ToolWindowId.RUN); @NonNls public static final String LIB_EXEC_DIRECTORY = "libexec"; @NonNls public static final String GO_VERSION_FILE_PATH = "runtime/zversion.go"; @NonNls public static final String GO_VERSION_NEW_FILE_PATH = "runtime/internal/sys/zversion.go"; public static final String BUILTIN_FILE_NAME = "builtin.go"; public static final String BUILTIN_PACKAGE_NAME = "builtin"; public static final String BUILTIN_FILE_PATH = BUILTIN_PACKAGE_NAME + "/" + BUILTIN_FILE_NAME; @NonNls public static final String APP_ENGINE_MARKER_FILE = "appcfg.py"; @NonNls public static final String APP_ENGINE_GO_ROOT_DIRECTORY_PATH = "/goroot"; @NonNls public static final String GCLOUD_APP_ENGINE_DIRECTORY_PATH = "/platform/google_appengine"; @NonNls public static final String GAE_EXECUTABLE_NAME = "goapp"; @NonNls public static final String GAE_BAT_EXECUTABLE_NAME = "goapp.bat"; @NonNls public static final String GAE_CMD_EXECUTABLE_NAME = "goapp.cmd"; @NonNls public static final String DELVE_EXECUTABLE_NAME = "dlv"; @NonNls public static final String GO_EXECUTABLE_NAME = "go"; public static final String BUILD_FLAG = "+build"; public static final String LINUX_OS = "linux"; public static final String ANDROID_OS = "android"; // see "$GOROOT/src/go/build/syslist.go public static final Set KNOWN_OS = ContainerUtil.immutableSet("android", "darwin", "dragonfly", "freebsd", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows"); public static final Set KNOWN_ARCH = ContainerUtil.immutableSet("386", "amd64", "amd64p32", "arm", "armbe", "arm64", "arm64be", "ppc64", "ppc64le", "mips", "mipsle", "mips64", "mips64le", "mips64p32", "mips64p32le", "ppc", "s390", "s390x", "sparc", "sparc64"); public static final Set KNOWN_VERSIONS = ContainerUtil.immutableSet("go1.1", "go1.2", "go1.3", "go1.4", "go1.5", "go1.6", "go1.7"); public static final Set KNOWN_CGO = ContainerUtil.immutableSet("darwin/386", "darwin/amd64", "dragonfly/386", "dragonfly/amd64", "freebsd/386", "freebsd/amd64", "freebsd/arm", "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "android/386", "android/amd64", "android/arm", "netbsd/386", "netbsd/amd64", "netbsd/arm", "openbsd/386", "openbsd/amd64", "windows/386", "windows/amd64", "linux/ppc64le"); public static final Set KNOWN_COMPILERS = ContainerUtil.immutableSet("gc", "gccgo"); @NonNls public static final String NIL = "nil"; @NonNls public static final String GO = "Go"; @NonNls public static final String AMD64 = "amd64"; private GoConstants() { } } ================================================ FILE: utils/src/com/goide/GoEnvironmentUtil.java ================================================ /* * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.EnvironmentUtil; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GoEnvironmentUtil { private GoEnvironmentUtil() {} @NotNull public static String getBinaryFileNameForPath(@NotNull String path) { String resultBinaryName = FileUtil.getNameWithoutExtension(PathUtil.getFileName(path)); return SystemInfo.isWindows ? resultBinaryName + ".exe" : resultBinaryName; } @NotNull public static String getGaeExecutableFileName(boolean gcloudInstallation) { if (SystemInfo.isWindows) { return gcloudInstallation ? GoConstants.GAE_CMD_EXECUTABLE_NAME : GoConstants.GAE_BAT_EXECUTABLE_NAME; } return GoConstants.GAE_EXECUTABLE_NAME; } @Nullable public static String retrieveGoPathFromEnvironment() { if (ApplicationManager.getApplication().isUnitTestMode()) return null; String path = EnvironmentUtil.getValue(GoConstants.GO_PATH); return path != null ? path : PathMacros.getInstance().getValue(GoConstants.GO_PATH); } } ================================================ FILE: utils/src/com/goide/GoLibrariesState.java ================================================ /* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * 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 com.goide; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GoLibrariesState { @NotNull private Collection myUrls = ContainerUtil.newArrayList(); @NotNull public Collection getUrls() { return myUrls; } public void setUrls(@NotNull Collection urls) { myUrls = urls; } }