diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..f660e39 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,20 @@ +/**@type {import('eslint').Linter.Config} */ +// eslint-disable-next-line no-undef +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + plugins: [ + '@typescript-eslint', + ], + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + ], + rules: { + 'semi': [2, "always"], + '@typescript-eslint/no-unused-vars': 0, + '@typescript-eslint/no-explicit-any': 0, + '@typescript-eslint/explicit-module-boundary-types': 0, + '@typescript-eslint/no-non-null-assertion': 0, + } +}; \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/1_new_config.yaml b/.github/ISSUE_TEMPLATE/1_new_config.yaml new file mode 100644 index 0000000..1af1a95 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1_new_config.yaml @@ -0,0 +1,70 @@ +name: New Config Request +description: Suggest support for a new config +labels: [new-config] +body: + - type: markdown + attributes: + value: | + # Thank you for suggesting a new config! + + As implementing a new config requires a lot of work, make sure to provide as much information as possible to help understand the request. + This is not a 1-minute issue that can be done quickly without any work. We are distributing some work to you so that the maintainers can focus on implementing the actual LSP instead of spending time searching for documentation, examples, etc. If it takes you between 10 - 30 minutes to fill out this form, you are saving the maintainers hours of work. + + - type: checkboxes + attributes: + label: You must fill out all the fields + options: + - label: I understand that this issue may be closed without any notice if the template is not filled out correctly + required: true + + - label: I've checked that I'm using the latest version of config-lsp + required: true + + - type: input + attributes: + label: Program + description: Provide the URL of the program's official website + placeholder: https://www.openssh.com/ + + - type: textarea + id: description + attributes: + label: Description + description: Describe the purpose of the program and the config file and what it is used for + placeholder: Your description here + + - type: textarea + id: documentation + attributes: + label: Documentation + description: Enter the URL of the official documentation for the config. If the program provides a manpage, you may specify this as well. Do not link to the site https://linux.die.net/ - use alternatives instead. + placeholder: https://man.openbsd.org/ssh_config.5 + + - type: textarea + id: examples + attributes: + label: Examples + description: Provide *at least* 3 examples of the config file. One simple example, one (theoretical) complex example, and one real-world example. If the examples contain real data, you may anonymize the values but try to keep the structure intact. + placeholder: Your examples here + + - type: textarea + id: locations + attributes: + label: File locations + description: What are the usual locations for the config file? If the program supports multiple config files, mention them as well. + placeholder: /etc/ssh/sshd_config + + - type: textarea + id: tutorial + attributes: + label: Tutorial + description: Provide a step-by-step tutorial on how to use the config file and get the program up and running. If there are any specific settings that are required, mention them as well. + placeholder: Your tutorial here + + - type: textarea + id: additional + attributes: + label: Additional Information + description: Provide any additional information that you think is relevant to the config file. This can be anything from specific use-cases to known issues. + placeholder: Your additional information here + diff --git a/.github/workflows/pr-tests.yaml b/.github/workflows/pr-tests.yaml index 71a2213..fa90407 100644 --- a/.github/workflows/pr-tests.yaml +++ b/.github/workflows/pr-tests.yaml @@ -19,6 +19,6 @@ jobs: - name: Check Nix flake run: nix flake check - - name: Run tests - run: nix develop --command bash -c 'go test ./...' + - name: Build app + run: nix develop --command bash -c "cd server && go build" diff --git a/.gitignore b/.gitignore index 3a8d51a..73e8f25 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ test.lua config-lsp result bin +debug.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..acbcf86 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +## Supported Features + +| | diagnostics | `completion` | `hover` | `code-action` | `definition` | `rename` | `signature-help` | +|-------------|-------------|--------------|---------|---------------|--------------|----------|------------------| +| aliases | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| fstab | ✅ | ✅ | ✅ | ❓ | ❓ | ❓ | 🟡 | +| hosts | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 | +| sshd_config | ✅ | ✅ | ✅ | ❓ | ✅ | ❓ | 🟡 | +| wireguard | ✅ | ✅ | ✅ | ✅ | ❓ | ❓ | 🟡 | + +✅ = Supported + +🟡 = Will be supported, but not yet implemented + +❓ = No idea what to implement here, please let me know if you have any ideas + diff --git a/common/location.go b/common/location.go deleted file mode 100644 index 5db293f..0000000 --- a/common/location.go +++ /dev/null @@ -1,121 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/antlr4-go/antlr/v4" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type Location struct { - Line uint32 - Character uint32 -} - -type LocationRange struct { - Start Location - End Location -} - -func (l LocationRange) ShiftHorizontal(offset uint32) LocationRange { - return LocationRange{ - Start: Location{ - Line: l.Start.Line, - Character: l.Start.Character + offset, - }, - End: Location{ - Line: l.End.Line, - Character: l.End.Character + offset, - }, - } -} - -func (l LocationRange) String() string { - if l.Start.Line == l.End.Line { - return fmt.Sprintf("%d:%d-%d", l.Start.Line, l.Start.Character, l.End.Character) - } - - return fmt.Sprintf("%d:%d-%d:%d", l.Start.Line, l.Start.Character, l.End.Line, l.End.Character) -} - -var GlobalLocationRange = LocationRange{ - Start: Location{ - Line: 0, - Character: 0, - }, - End: Location{ - Line: 0, - Character: 0, - }, -} - -func (l LocationRange) ToLSPRange() protocol.Range { - return protocol.Range{ - Start: protocol.Position{ - Line: l.Start.Line, - Character: l.Start.Character, - }, - End: protocol.Position{ - Line: l.End.Line, - Character: l.End.Character, - }, - } -} - -func (l *LocationRange) ChangeBothLines(newLine uint32) { - l.Start.Line = newLine - l.End.Line = newLine -} - -func (l LocationRange) ContainsCursor(line uint32, character uint32) bool { - return line == l.Start.Line && character >= l.Start.Character && character <= l.End.Character -} - -func (l LocationRange) ContainsCursorByCharacter(character uint32) bool { - return character >= l.Start.Character && character <= l.End.Character -} - -func CreateFullLineRange(line uint32) LocationRange { - return LocationRange{ - Start: Location{ - Line: line, - Character: 0, - }, - End: Location{ - Line: line, - Character: 999999, - }, - } -} - -func CreateSingleCharRange(line uint32, character uint32) LocationRange { - return LocationRange{ - Start: Location{ - Line: line, - Character: character, - }, - End: Location{ - Line: line, - Character: character, - }, - } -} - -func CharacterRangeFromCtx( - ctx antlr.BaseParserRuleContext, -) LocationRange { - line := uint32(ctx.GetStart().GetLine()) - start := uint32(ctx.GetStart().GetStart()) - end := uint32(ctx.GetStop().GetStop()) - - return LocationRange{ - Start: Location{ - Line: line, - Character: start, - }, - End: Location{ - Line: line, - Character: end + 1, - }, - } -} diff --git a/doc-values/value-custom.go b/doc-values/value-custom.go deleted file mode 100644 index 22f0e8d..0000000 --- a/doc-values/value-custom.go +++ /dev/null @@ -1,37 +0,0 @@ -package docvalues - -import ( - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type CustomValueContext interface { - GetIsContext() bool -} - -type EmptyValueContext struct{} - -func (EmptyValueContext) GetIsContext() bool { - return true -} - -var EmptyValueContextInstance = EmptyValueContext{} - -type CustomValue struct { - FetchValue func(context CustomValueContext) Value -} - -func (v CustomValue) GetTypeDescription() []string { - return v.FetchValue(EmptyValueContextInstance).GetTypeDescription() -} - -func (v CustomValue) CheckIsValid(value string) []*InvalidValue { - return v.FetchValue(EmptyValueContextInstance).CheckIsValid(value) -} - -func (v CustomValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - return v.FetchValue(EmptyValueContextInstance).FetchCompletions(line, cursor) -} - -func (v CustomValue) FetchHoverInfo(line string, cursor uint32) []string { - return v.FetchValue(EmptyValueContextInstance).FetchHoverInfo(line, cursor) -} diff --git a/doc-values/value-documentation.go b/doc-values/value-documentation.go deleted file mode 100644 index 7666356..0000000 --- a/doc-values/value-documentation.go +++ /dev/null @@ -1,28 +0,0 @@ -package docvalues - -import ( - "strings" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type DocumentationValue struct { - Documentation string - Value Value -} - -func (v DocumentationValue) GetTypeDescription() []string { - return v.Value.GetTypeDescription() -} - -func (v DocumentationValue) CheckIsValid(value string) []*InvalidValue { - return v.Value.CheckIsValid(value) -} - -func (v DocumentationValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - return v.Value.FetchCompletions(line, cursor) -} - -func (v DocumentationValue) FetchHoverInfo(line string, cursor uint32) []string { - return strings.Split(v.Documentation, "\n") -} diff --git a/doc-values/value-prefix.go b/doc-values/value-prefix.go deleted file mode 100644 index 80ed331..0000000 --- a/doc-values/value-prefix.go +++ /dev/null @@ -1,73 +0,0 @@ -package docvalues - -import ( - "config-lsp/utils" - "fmt" - "strings" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type Prefix struct { - Prefix string - Meaning string -} -type PrefixWithMeaningValue struct { - Prefixes []Prefix - SubValue Value -} - -func (v PrefixWithMeaningValue) GetTypeDescription() []string { - subDescription := v.SubValue.GetTypeDescription() - - prefixDescription := utils.Map(v.Prefixes, func(prefix Prefix) string { - return fmt.Sprintf("_%s_ -> %s", prefix.Prefix, prefix.Meaning) - }) - - return append(subDescription, - append( - []string{"The following prefixes are allowed:"}, - prefixDescription..., - )..., - ) -} - -func (v PrefixWithMeaningValue) CheckIsValid(value string) []*InvalidValue { - for _, prefix := range v.Prefixes { - if strings.HasPrefix(value, prefix.Prefix) { - return v.SubValue.CheckIsValid(value[len(prefix.Prefix):]) - } - } - - return v.SubValue.CheckIsValid(value) -} - -func (v PrefixWithMeaningValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - textFormat := protocol.InsertTextFormatPlainText - kind := protocol.CompletionItemKindText - - prefixCompletions := utils.Map(v.Prefixes, func(prefix Prefix) protocol.CompletionItem { - return protocol.CompletionItem{ - Label: prefix.Prefix, - Detail: &prefix.Meaning, - InsertTextFormat: &textFormat, - Kind: &kind, - } - }) - - return append(prefixCompletions, v.SubValue.FetchCompletions(line, cursor)...) -} - -func (v PrefixWithMeaningValue) FetchHoverInfo(line string, cursor uint32) []string { - for _, prefix := range v.Prefixes { - if strings.HasPrefix(line, prefix.Prefix) { - return append([]string{ - fmt.Sprintf("Prefix: _%s_ -> %s", prefix.Prefix, prefix.Meaning), - }, - v.SubValue.FetchHoverInfo(line[1:], cursor)..., - ) - } - } - - return v.SubValue.FetchHoverInfo(line[1:], cursor) -} diff --git a/flake.nix b/flake.nix index 337a65a..b1f5a7f 100644 --- a/flake.nix +++ b/flake.nix @@ -26,26 +26,53 @@ }; inputs = [ pkgs.go_1_22 - pkgs.wireguard-tools ]; - in { - packages = { - default = pkgs.buildGoModule { + server = pkgs.buildGoModule { nativeBuildInputs = inputs; pname = "github.com/Myzel394/config-lsp"; version = "v0.0.1"; - src = ./.; - vendorHash = "sha256-KhyqogTyb3jNrGP+0Zmn/nfx+WxzjgcrFOp2vivFgT0="; + src = ./server; + vendorHash = "sha256-s+sjOVvqU20+mbEFKg+RCD+dhScqSatk9eseX2IioPI="; checkPhase = '' go test -v $(pwd)/... ''; }; + in { + packages = { + default = server; + "vs-code-extension" = let + name = "config-lsp-vs-code-extension"; + node-modules = pkgs.mkYarnPackage { + src = ./vs-code-extension; + name = name; + packageJSON = ./vs-code-extension/package.json; + yarnLock = ./vs-code-extension/yarn.lock; + yarnNix = ./vs-code-extension/yarn.nix; + + buildPhase = '' + yarn --offline run compile + ''; + installPhase = '' + mv deps/${name}/out $out + cp ${server}/bin/config-lsp $out/ + ''; + distPhase = "true"; + }; + in node-modules; }; devShells.default = pkgs.mkShell { buildInputs = inputs ++ (with pkgs; [ mailutils - swaks - ]); + wireguard-tools + antlr + ]) ++ (if pkgs.stdenv.isLinux then with pkgs; [ + postfix + ] else []); + }; + devShells."vs-code-extension" = pkgs.mkShell { + buildInputs = [ + pkgs.nodejs + ]; }; } ); diff --git a/handlers/aliases/lsp/workspace-execute-command.go b/handlers/aliases/lsp/workspace-execute-command.go deleted file mode 100644 index 41f5298..0000000 --- a/handlers/aliases/lsp/workspace-execute-command.go +++ /dev/null @@ -1,21 +0,0 @@ -package lsp - -import ( - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteCommandParams) (*protocol.ApplyWorkspaceEditParams, error) { - // _, command, _ := strings.Cut(params.Command, ".") - // - // switch command { - // case string(handlers.CodeActionInlineAliases): - // args := handlers.CodeActionInlineAliasesArgsFromArguments(params.Arguments[0].(map[string]any)) - // - // document := hosts.DocumentParserMap[args.URI] - // - // return args.RunCommand(*document.Parser) - // } - - return nil, nil -} diff --git a/handlers/fstab/shared.go b/handlers/fstab/shared.go deleted file mode 100644 index 05aaebb..0000000 --- a/handlers/fstab/shared.go +++ /dev/null @@ -1,7 +0,0 @@ -package fstab - -import ( - protocol "github.com/tliron/glsp/protocol_3_16" -) - -var documentParserMap = map[protocol.DocumentUri]*FstabParser{} diff --git a/handlers/fstab/text-document-completion.go b/handlers/fstab/text-document-completion.go deleted file mode 100644 index 5358634..0000000 --- a/handlers/fstab/text-document-completion.go +++ /dev/null @@ -1,112 +0,0 @@ -package fstab - -import ( - docvalues "config-lsp/doc-values" - fstabdocumentation "config-lsp/handlers/fstab/documentation" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { - parser := documentParserMap[params.TextDocument.URI] - - entry, found := parser.GetEntry(params.Position.Line) - - if !found { - // Empty line, return spec completions - return fstabdocumentation.SpecField.FetchCompletions( - "", - params.Position.Character, - ), nil - } - - if entry.Type == FstabEntryTypeComment { - return nil, nil - } - - cursor := params.Position.Character - line := entry.Line - - return getCompletion(line, cursor) -} - -func getCompletion( - line FstabLine, - cursor uint32, -) ([]protocol.CompletionItem, error) { - targetField := line.GetFieldAtPosition(cursor) - - switch targetField { - case FstabFieldSpec: - value, cursor := GetFieldSafely(line.Fields.Spec, cursor) - - return fstabdocumentation.SpecField.FetchCompletions( - value, - cursor, - ), nil - case FstabFieldMountPoint: - value, cursor := GetFieldSafely(line.Fields.MountPoint, cursor) - - return fstabdocumentation.MountPointField.FetchCompletions( - value, - cursor, - ), nil - case FstabFieldFileSystemType: - value, cursor := GetFieldSafely(line.Fields.FilesystemType, cursor) - - return fstabdocumentation.FileSystemTypeField.FetchCompletions( - value, - cursor, - ), nil - case FstabFieldOptions: - fileSystemType := line.Fields.FilesystemType.Value - - var optionsField docvalues.Value - - if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found { - optionsField = foundField - } else { - optionsField = fstabdocumentation.DefaultMountOptionsField - } - - value, cursor := GetFieldSafely(line.Fields.Options, cursor) - - completions := optionsField.FetchCompletions( - value, - cursor, - ) - - return completions, nil - case FstabFieldFreq: - value, cursor := GetFieldSafely(line.Fields.Freq, cursor) - - return fstabdocumentation.FreqField.FetchCompletions( - value, - cursor, - ), nil - case FstabFieldPass: - value, cursor := GetFieldSafely(line.Fields.Pass, cursor) - - return fstabdocumentation.PassField.FetchCompletions( - value, - cursor, - ), nil - } - - return nil, nil -} - -// Safely get value and new cursor position -// If field is nil, return empty string and 0 -func GetFieldSafely(field *Field, character uint32) (string, uint32) { - if field == nil { - return "", 0 - } - - if field.Value == "" { - return "", 0 - } - - return field.Value, character - field.Start -} diff --git a/handlers/fstab/text-document-did-open.go b/handlers/fstab/text-document-did-open.go deleted file mode 100644 index d64f3ea..0000000 --- a/handlers/fstab/text-document-did-open.go +++ /dev/null @@ -1,30 +0,0 @@ -package fstab - -import ( - "config-lsp/common" - "config-lsp/utils" - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentDidOpen( - context *glsp.Context, - params *protocol.DidOpenTextDocumentParams, -) error { - common.ClearDiagnostics(context, params.TextDocument.URI) - - parser := FstabParser{} - documentParserMap[params.TextDocument.URI] = &parser - - errors := parser.ParseFromContent(params.TextDocument.Text) - diagnostics := utils.Map( - errors, - func(err common.ParseError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) - - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - - return nil -} diff --git a/handlers/fstab/text-document-hover.go b/handlers/fstab/text-document-hover.go deleted file mode 100644 index 96fa182..0000000 --- a/handlers/fstab/text-document-hover.go +++ /dev/null @@ -1,71 +0,0 @@ -package fstab - -import ( - docvalues "config-lsp/doc-values" - fstabdocumentation "config-lsp/handlers/fstab/documentation" - "strings" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) { - cursor := params.Position.Character - - parser := documentParserMap[params.TextDocument.URI] - - entry, found := parser.GetEntry(params.Position.Line) - - // Empty line - if !found { - return nil, nil - } - - // Comment line - if entry.Type == FstabEntryTypeComment { - return nil, nil - } - - return getHoverInfo(entry, cursor) -} - -func getHoverInfo(entry *FstabEntry, cursor uint32) (*protocol.Hover, error) { - line := entry.Line - targetField := line.GetFieldAtPosition(cursor) - - switch targetField { - case FstabFieldSpec: - return &SpecHoverField, nil - case FstabFieldMountPoint: - return &MountPointHoverField, nil - case FstabFieldFileSystemType: - return &FileSystemTypeField, nil - case FstabFieldOptions: - fileSystemType := line.Fields.FilesystemType.Value - var optionsField docvalues.Value - - if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found { - optionsField = foundField - } else { - optionsField = fstabdocumentation.DefaultMountOptionsField - } - - relativeCursor := cursor - line.Fields.Options.Start - fieldInfo := optionsField.FetchHoverInfo(line.Fields.Options.Value, relativeCursor) - - hover := protocol.Hover{ - Contents: protocol.MarkupContent{ - Kind: protocol.MarkupKindMarkdown, - Value: strings.Join(fieldInfo, "\n"), - }, - } - - return &hover, nil - case FstabFieldFreq: - return &FreqHoverField, nil - case FstabFieldPass: - return &PassHoverField, nil - } - - return nil, nil -} diff --git a/handlers/hosts/analyzer/handler_test.go b/handlers/hosts/analyzer/handler_test.go deleted file mode 100644 index 38e34c1..0000000 --- a/handlers/hosts/analyzer/handler_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package analyzer - -import ( - "config-lsp/handlers/hosts/ast" - "config-lsp/utils" - "net" - "testing" -) - -func TestValidSimpleExampleWorks( - t *testing.T, -) { - input := utils.Dedent(` -1.2.3.4 hello.com - `) - - parser := ast.NewHostsParser() - errors := parser.Parse(input) - - if len(errors) != 0 { - t.Errorf("Expected no errors, but got %v", errors) - } - - if !(len(parser.Tree.Entries) == 1) { - t.Errorf("Expected 1 entry, but got %v", len(parser.Tree.Entries)) - } - - if parser.Tree.Entries[0].IPAddress == nil { - t.Errorf("Expected IP address to be present, but got nil") - } - - if !(parser.Tree.Entries[0].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be 1.2.3.4, but got %v", parser.Tree.Entries[0].IPAddress.Value) - } - - if !(parser.Tree.Entries[0].Hostname.Value == "hello.com") { - t.Errorf("Expected hostname to be hello.com, but got %v", parser.Tree.Entries[0].Hostname.Value) - } - - if !(parser.Tree.Entries[0].Aliases == nil) { - t.Errorf("Expected no aliases, but got %v", parser.Tree.Entries[0].Aliases) - } - - if !(parser.Tree.Entries[0].Location.Start.Line == 0) { - t.Errorf("Expected line to be 1, but got %v", parser.Tree.Entries[0].Location.Start.Line) - } - - if !(parser.Tree.Entries[0].Location.Start.Character == 0) { - t.Errorf("Expected start to be 0, but got %v", parser.Tree.Entries[0].Location.Start) - } - - if !(parser.Tree.Entries[0].Location.End.Character == 17) { - t.Errorf("Expected end to be 17, but got %v", parser.Tree.Entries[0].Location.End.Character) - } - - if !(parser.Tree.Entries[0].IPAddress.Location.Start.Line == 0) { - t.Errorf("Expected IP address line to be 1, but got %v", parser.Tree.Entries[0].IPAddress.Location.Start.Line) - } - - if !(parser.Tree.Entries[0].IPAddress.Location.Start.Character == 0) { - t.Errorf("Expected IP address start to be 0, but got %v", parser.Tree.Entries[0].IPAddress.Location.Start.Character) - } - - if !(parser.Tree.Entries[0].IPAddress.Location.End.Character == 7) { - t.Errorf("Expected IP address end to be 7, but got %v", parser.Tree.Entries[0].IPAddress.Location.End.Character) - } - - if !(len(parser.CommentLines) == 0) { - t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines)) - } -} - -func TestValidComplexExampleWorks( - t *testing.T, -) { - input := utils.Dedent(` - -# This is a comment -1.2.3.4 hello.com test.com # This is another comment -5.5.5.5 test.com -1.2.3.4 example.com check.com -`) - - parser := ast.NewHostsParser() - errors := parser.Parse(input) - - if len(errors) != 0 { - t.Errorf("Expected no errors, but got %v", errors) - } - - if !(len(parser.Tree.Entries) == 3) { - t.Errorf("Expected 3 entries, but got %v", len(parser.Tree.Entries)) - } - - if parser.Tree.Entries[2].IPAddress == nil { - t.Errorf("Expected IP address to be present, but got nil") - } - - if !(parser.Tree.Entries[2].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be 1.2.3.4, but got %v", parser.Tree.Entries[2].IPAddress.Value) - } - - if !(len(parser.CommentLines) == 1) { - t.Errorf("Expected 1 comment line, but got %v", len(parser.CommentLines)) - } - - if !(utils.KeyExists(parser.CommentLines, 1)) { - t.Errorf("Expected comment line 2 to exist, but it does not") - } -} - -func TestInvalidExampleWorks( - t *testing.T, -) { - input := utils.Dedent(` -1.2.3.4 - `) - - parser := ast.NewHostsParser() - errors := parser.Parse(input) - - if len(errors) == 0 { - t.Errorf("Expected errors, but got none") - } - - if !(len(parser.Tree.Entries) == 1) { - t.Errorf("Expected 1 entries, but got %v", len(parser.Tree.Entries)) - } - - if !(len(parser.CommentLines) == 0) { - t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines)) - } - - if !(parser.Tree.Entries[0].IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { - t.Errorf("Expected IP address to be nil, but got %v", parser.Tree.Entries[0].IPAddress) - } - - if !(parser.Tree.Entries[0].Hostname == nil) { - t.Errorf("Expected hostname to be nil, but got %v", parser.Tree.Entries[0].Hostname) - } - - if !(parser.Tree.Entries[0].Aliases == nil) { - t.Errorf("Expected aliases to be nil, but got %v", parser.Tree.Entries[0].Aliases) - } -} diff --git a/handlers/hosts/ast/parser/Hosts.interp b/handlers/hosts/ast/parser/Hosts.interp deleted file mode 100644 index 9417135..0000000 --- a/handlers/hosts/ast/parser/Hosts.interp +++ /dev/null @@ -1,48 +0,0 @@ -token literal names: -null -null -'/' -'.' -':' -'#' -null -null -null -null -null - -token symbolic names: -null -COMMENTLINE -SLASH -DOT -COLON -HASHTAG -SEPARATOR -NEWLINE -DIGITS -OCTETS -DOMAIN - -rule names: -lineStatement -entry -aliases -alias -hostname -domain -ipAddress -ipv4Address -singleIPv4Address -ipv6Address -singleIPv6Address -ipv4Digit -ipv6Octet -ipRange -ipRangeBits -comment -leadingComment - - -atn: -[4, 1, 10, 110, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, 2, 16, 7, 16, 1, 0, 3, 0, 36, 8, 0, 1, 0, 1, 0, 3, 0, 40, 8, 0, 1, 0, 3, 0, 43, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 52, 8, 1, 1, 2, 1, 2, 3, 2, 56, 8, 2, 4, 2, 58, 8, 2, 11, 2, 12, 2, 59, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1, 6, 3, 6, 70, 8, 6, 1, 7, 1, 7, 3, 7, 74, 8, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 3, 9, 86, 8, 9, 1, 10, 1, 10, 1, 10, 4, 10, 91, 8, 10, 11, 10, 12, 10, 92, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 0, 0, 17, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 0, 0, 102, 0, 35, 1, 0, 0, 0, 2, 46, 1, 0, 0, 0, 4, 57, 1, 0, 0, 0, 6, 61, 1, 0, 0, 0, 8, 63, 1, 0, 0, 0, 10, 65, 1, 0, 0, 0, 12, 69, 1, 0, 0, 0, 14, 71, 1, 0, 0, 0, 16, 75, 1, 0, 0, 0, 18, 83, 1, 0, 0, 0, 20, 90, 1, 0, 0, 0, 22, 96, 1, 0, 0, 0, 24, 98, 1, 0, 0, 0, 26, 100, 1, 0, 0, 0, 28, 103, 1, 0, 0, 0, 30, 105, 1, 0, 0, 0, 32, 107, 1, 0, 0, 0, 34, 36, 5, 6, 0, 0, 35, 34, 1, 0, 0, 0, 35, 36, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 3, 2, 1, 0, 38, 40, 5, 6, 0, 0, 39, 38, 1, 0, 0, 0, 39, 40, 1, 0, 0, 0, 40, 42, 1, 0, 0, 0, 41, 43, 3, 32, 16, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 45, 5, 0, 0, 1, 45, 1, 1, 0, 0, 0, 46, 47, 3, 12, 6, 0, 47, 48, 5, 6, 0, 0, 48, 51, 3, 8, 4, 0, 49, 50, 5, 6, 0, 0, 50, 52, 3, 4, 2, 0, 51, 49, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 3, 1, 0, 0, 0, 53, 55, 3, 6, 3, 0, 54, 56, 5, 6, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, 1, 0, 0, 0, 57, 53, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 57, 1, 0, 0, 0, 59, 60, 1, 0, 0, 0, 60, 5, 1, 0, 0, 0, 61, 62, 5, 10, 0, 0, 62, 7, 1, 0, 0, 0, 63, 64, 3, 10, 5, 0, 64, 9, 1, 0, 0, 0, 65, 66, 5, 10, 0, 0, 66, 11, 1, 0, 0, 0, 67, 70, 3, 14, 7, 0, 68, 70, 3, 18, 9, 0, 69, 67, 1, 0, 0, 0, 69, 68, 1, 0, 0, 0, 70, 13, 1, 0, 0, 0, 71, 73, 3, 16, 8, 0, 72, 74, 3, 26, 13, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 15, 1, 0, 0, 0, 75, 76, 3, 22, 11, 0, 76, 77, 5, 3, 0, 0, 77, 78, 3, 22, 11, 0, 78, 79, 5, 3, 0, 0, 79, 80, 3, 22, 11, 0, 80, 81, 5, 3, 0, 0, 81, 82, 3, 22, 11, 0, 82, 17, 1, 0, 0, 0, 83, 85, 3, 20, 10, 0, 84, 86, 3, 26, 13, 0, 85, 84, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 19, 1, 0, 0, 0, 87, 88, 3, 24, 12, 0, 88, 89, 5, 4, 0, 0, 89, 91, 1, 0, 0, 0, 90, 87, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 90, 1, 0, 0, 0, 92, 93, 1, 0, 0, 0, 93, 94, 1, 0, 0, 0, 94, 95, 3, 24, 12, 0, 95, 21, 1, 0, 0, 0, 96, 97, 5, 8, 0, 0, 97, 23, 1, 0, 0, 0, 98, 99, 5, 9, 0, 0, 99, 25, 1, 0, 0, 0, 100, 101, 5, 2, 0, 0, 101, 102, 3, 28, 14, 0, 102, 27, 1, 0, 0, 0, 103, 104, 5, 8, 0, 0, 104, 29, 1, 0, 0, 0, 105, 106, 5, 1, 0, 0, 106, 31, 1, 0, 0, 0, 107, 108, 5, 1, 0, 0, 108, 33, 1, 0, 0, 0, 10, 35, 39, 42, 51, 55, 59, 69, 73, 85, 92] \ No newline at end of file diff --git a/handlers/hosts/ast/parser/HostsLexer.interp b/handlers/hosts/ast/parser/HostsLexer.interp deleted file mode 100644 index e92d869..0000000 --- a/handlers/hosts/ast/parser/HostsLexer.interp +++ /dev/null @@ -1,50 +0,0 @@ -token literal names: -null -null -'/' -'.' -':' -'#' -null -null -null -null -null - -token symbolic names: -null -COMMENTLINE -SLASH -DOT -COLON -HASHTAG -SEPARATOR -NEWLINE -DIGITS -OCTETS -DOMAIN - -rule names: -COMMENTLINE -SLASH -DOT -COLON -HASHTAG -SEPARATOR -NEWLINE -DIGITS -DIGIT -OCTETS -OCTET -DOMAIN -STRING - -channel names: -DEFAULT_TOKEN_CHANNEL -HIDDEN - -mode names: -DEFAULT_MODE - -atn: -[4, 0, 10, 83, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 1, 0, 1, 0, 4, 0, 30, 8, 0, 11, 0, 12, 0, 31, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 43, 8, 5, 11, 5, 12, 5, 44, 1, 6, 3, 6, 48, 8, 6, 1, 6, 1, 6, 1, 7, 4, 7, 53, 8, 7, 11, 7, 12, 7, 54, 1, 8, 1, 8, 1, 9, 4, 9, 60, 8, 9, 11, 9, 12, 9, 61, 1, 10, 1, 10, 1, 11, 4, 11, 67, 8, 11, 11, 11, 12, 11, 68, 1, 11, 1, 11, 4, 11, 73, 8, 11, 11, 11, 12, 11, 74, 5, 11, 77, 8, 11, 10, 11, 12, 11, 80, 9, 11, 1, 12, 1, 12, 0, 0, 13, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 0, 19, 9, 21, 0, 23, 10, 25, 0, 1, 0, 8, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 1, 0, 48, 57, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 65, 90, 97, 122, 5, 0, 9, 10, 13, 13, 32, 32, 35, 35, 46, 46, 87, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 1, 27, 1, 0, 0, 0, 3, 33, 1, 0, 0, 0, 5, 35, 1, 0, 0, 0, 7, 37, 1, 0, 0, 0, 9, 39, 1, 0, 0, 0, 11, 42, 1, 0, 0, 0, 13, 47, 1, 0, 0, 0, 15, 52, 1, 0, 0, 0, 17, 56, 1, 0, 0, 0, 19, 59, 1, 0, 0, 0, 21, 63, 1, 0, 0, 0, 23, 66, 1, 0, 0, 0, 25, 81, 1, 0, 0, 0, 27, 29, 3, 9, 4, 0, 28, 30, 8, 0, 0, 0, 29, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 29, 1, 0, 0, 0, 31, 32, 1, 0, 0, 0, 32, 2, 1, 0, 0, 0, 33, 34, 5, 47, 0, 0, 34, 4, 1, 0, 0, 0, 35, 36, 5, 46, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 5, 58, 0, 0, 38, 8, 1, 0, 0, 0, 39, 40, 5, 35, 0, 0, 40, 10, 1, 0, 0, 0, 41, 43, 7, 1, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 12, 1, 0, 0, 0, 46, 48, 7, 2, 0, 0, 47, 46, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 7, 3, 0, 0, 50, 14, 1, 0, 0, 0, 51, 53, 3, 17, 8, 0, 52, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 52, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 16, 1, 0, 0, 0, 56, 57, 7, 4, 0, 0, 57, 18, 1, 0, 0, 0, 58, 60, 3, 21, 10, 0, 59, 58, 1, 0, 0, 0, 60, 61, 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 20, 1, 0, 0, 0, 63, 64, 7, 5, 0, 0, 64, 22, 1, 0, 0, 0, 65, 67, 3, 25, 12, 0, 66, 65, 1, 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 78, 1, 0, 0, 0, 70, 72, 3, 5, 2, 0, 71, 73, 7, 6, 0, 0, 72, 71, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 72, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 77, 1, 0, 0, 0, 76, 70, 1, 0, 0, 0, 77, 80, 1, 0, 0, 0, 78, 76, 1, 0, 0, 0, 78, 79, 1, 0, 0, 0, 79, 24, 1, 0, 0, 0, 80, 78, 1, 0, 0, 0, 81, 82, 8, 7, 0, 0, 82, 26, 1, 0, 0, 0, 9, 0, 31, 44, 47, 54, 61, 68, 74, 78, 0] \ No newline at end of file diff --git a/handlers/openssh/analyzer.go b/handlers/openssh/analyzer.go deleted file mode 100644 index 52ad3d5..0000000 --- a/handlers/openssh/analyzer.go +++ /dev/null @@ -1,28 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" -) - -func AnalyzeValues( - parser SimpleConfigParser, - availableOptions map[string]Option, -) []docvalues.ValueError { - errors := make([]docvalues.ValueError, 0) - - for optionName, line := range parser.Lines { - documentationOption := availableOptions[optionName] - - err := documentationOption.Value.CheckIsValid(line.Value) - - if err != nil { - errors = append(errors, docvalues.ValueError{ - Line: line.Position.Line, - Option: optionName, - Value: line.Value, - }) - } - } - - return errors -} diff --git a/handlers/openssh/diagnose-ssh-options.go b/handlers/openssh/diagnose-ssh-options.go deleted file mode 100644 index 3591318..0000000 --- a/handlers/openssh/diagnose-ssh-options.go +++ /dev/null @@ -1,67 +0,0 @@ -package openssh - -import ( - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func DiagnoseSSHOptions( - context *glsp.Context, - documentURI protocol.DocumentUri, - parser *SimpleConfigParser, -) []protocol.Diagnostic { - diagnostics := make([]protocol.Diagnostic, 0) - - diagnostics = append( - diagnostics, - DiagnoseOption( - context, - documentURI, - parser, - "Port", - func(value string, position SimpleConfigPosition) []protocol.Diagnostic { - if value == "22" { - severity := protocol.DiagnosticSeverityWarning - - return []protocol.Diagnostic{ - { - Range: protocol.Range{ - Start: protocol.Position{ - Line: position.Line, - Character: uint32(len("Port ")), - }, - End: protocol.Position{ - Line: position.Line, - Character: uint32(len("Port " + value)), - }, - }, - Severity: &severity, - Message: "Port should not be 22 as it's often enumarated by attackers", - }, - } - } - - return []protocol.Diagnostic{} - }, - )..., - ) - - return diagnostics -} - -func DiagnoseOption( - context *glsp.Context, - uri protocol.DocumentUri, - parser *SimpleConfigParser, - optionName string, - checkerFunc func(string, SimpleConfigPosition) []protocol.Diagnostic, -) []protocol.Diagnostic { - option, err := parser.GetOption(optionName) - - if err != nil { - // Nothing to diagnose - return nil - } - - return checkerFunc(option.Value, option.Position) -} diff --git a/handlers/openssh/diagnostics.go b/handlers/openssh/diagnostics.go deleted file mode 100644 index 2fe3c92..0000000 --- a/handlers/openssh/diagnostics.go +++ /dev/null @@ -1,47 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "config-lsp/utils" - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func DiagnoseParser( - context *glsp.Context, - documentURI protocol.DocumentUri, - content string, -) []protocol.Diagnostic { - diagnostics := make([]protocol.Diagnostic, 0) - - diagnostics = append( - diagnostics, - utils.Map( - Parser.ParseFromFile(content), - func(err docvalues.OptionError) protocol.Diagnostic { - return err.GetPublishDiagnosticsParams() - }, - )..., - ) - - diagnostics = append( - diagnostics, - utils.Map( - AnalyzeValues(Parser, Options), - func(err docvalues.ValueError) protocol.Diagnostic { - return err.GetPublishDiagnosticsParams() - }, - )..., - ) - - diagnostics = append( - diagnostics, - DiagnoseSSHOptions( - context, - documentURI, - &Parser, - )..., - ) - - return diagnostics -} diff --git a/handlers/openssh/documentation-common.go b/handlers/openssh/documentation-common.go deleted file mode 100644 index 5158146..0000000 --- a/handlers/openssh/documentation-common.go +++ /dev/null @@ -1,26 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "strings" - - protocol "github.com/tliron/glsp/protocol_3_16" -) - -type Option struct { - Documentation string - Value docvalues.Value -} - -func GetDocumentation(o *Option) protocol.MarkupContent { - typeDescription := strings.Join(o.Value.GetTypeDescription(), "\n") - - return protocol.MarkupContent{ - Kind: protocol.MarkupKindPlainText, - Value: "### Type\n" + typeDescription + "\n\n---\n\n### Documentation\n" + o.Documentation, - } -} - -func NewOption(documentation string, value docvalues.Value) Option { - return Option{documentation, value} -} diff --git a/handlers/openssh/documentation-utils.go b/handlers/openssh/documentation-utils.go deleted file mode 100644 index 687f541..0000000 --- a/handlers/openssh/documentation-utils.go +++ /dev/null @@ -1,96 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "config-lsp/utils" - "os/exec" - "strings" -) - -var BooleanEnumValue = docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("no"), - }, -} - -var plusMinuxCaretPrefixes = []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Append to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - { - Prefix: "^", - Meaning: "Place at the head of the default set", - }, -} - -var ChannelTimeoutExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") -var SetEnvExtractor = docvalues.ExtractKeyDuplicatesExtractor("=") - -func PrefixPlusMinusCaret(values []docvalues.EnumString) docvalues.PrefixWithMeaningValue { - return docvalues.PrefixWithMeaningValue{ - Prefixes: []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Append to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - { - Prefix: "^", - Meaning: "Place at the head of the default set", - }, - }, - SubValue: docvalues.ArrayValue{ - Separator: ",", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.EnumValue{ - Values: values, - }, - }, - } -} - -var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) - -func queryValues(query string) ([]string, error) { - cmd := exec.Command("ssh", "-Q", query) - - output, err := cmd.Output() - - if err != nil { - return []string{}, err - } - - return strings.Split(string(output), "\n"), nil -} - -func QueryOpenSSHOptions( - query string, -) ([]docvalues.EnumString, error) { - var availableQueries []docvalues.EnumString - key := query - - if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { - return _cachedQueries[key], nil - } else { - availableRawQueries, err := queryValues(query) - availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) - - if err != nil { - return []docvalues.EnumString{}, err - } - - _cachedQueries[key] = availableQueries - } - - return availableQueries, nil -} diff --git a/handlers/openssh/documentation.go b/handlers/openssh/documentation.go deleted file mode 100644 index adb61d8..0000000 --- a/handlers/openssh/documentation.go +++ /dev/null @@ -1,897 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "regexp" -) - -var ZERO = 0 -var MAX_PORT = 65535 -var MAX_FILE_MODE = 0777 - -var Options = map[string]Option{ - "AcceptEnv": NewOption( - `Specifies what environment variables sent by the client will be copied into the session's environ(7). See SendEnv and SetEnv in ssh_config(5) for how to configure the client. The TERM environment variable is always accepted whenever the client requests a pseudo-terminal as it is required by the protocol. Variables are specified by name, which may contain the wildcard characters ‘*’ and ‘?’. Multiple environment variables may be separated by whitespace or spread across multiple AcceptEnv directives. Be warned that some environment variables could be used to bypass restricted user environments. For this reason, care should be taken in the use of this directive. The default is not to accept any environment variables.`, - docvalues.StringValue{}, - ), - "AddressFamily": NewOption( - `Specifies which address family should be used by sshd(8). Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("any"), - docvalues.CreateEnumString("inet"), - docvalues.CreateEnumString("inet6"), - }, - }, - ), - "AllowAgentForwarding": NewOption( - `Specifies whether ssh-agent(1) forwarding is permitted. The default is yes. Note that disabling agent forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - BooleanEnumValue, - ), - "AllowGroups": NewOption( - `This keyword can be followed by a list of group name patterns, separated by spaces. If specified, login is allowed only for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. - -See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.GroupValue(" ", false), - ), - "AllowStreamLocalForwarding": NewOption( - `Specifies whether StreamLocal (Unix-domain socket) forwarding is permitted. The available options are yes (the default) or all to allow StreamLocal forwarding, no to prevent all StreamLocal forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling StreamLocal forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("all"), - docvalues.CreateEnumString("no"), - docvalues.CreateEnumString("local"), - docvalues.CreateEnumString("remote"), - }, - }, - ), - "AllowTcpForwarding": NewOption( - `Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("all"), - docvalues.CreateEnumString("no"), - docvalues.CreateEnumString("local"), - docvalues.CreateEnumString("remote"), - }, - }, - ), - "AllowUsers": NewOption( - `This keyword can be followed by a list of user name patterns, separated by spaces. If specified, login is allowed only for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.UserValue(" ", false), - ), - "AuthenticationMethods": NewOption( - `Specifies the authentication methods that must be successfully completed for a user to be granted access. This option must be followed by one or more lists of comma-separated authentication method names, or by the single string any to indicate the default behaviour of accepting any single authentication method. If the default is overridden, then successful authentication requires completion of every method in at least one of these lists. - For example, "publickey,password publickey,keyboard-interactive" would require the user to complete public key authentication, followed by either password or keyboard interactive authentication. Only methods that are next in one or more lists are offered at each stage, so for this example it would not be possible to attempt password or keyboard-interactive authentication before public key. - For keyboard interactive authentication it is also possible to restrict authentication to a specific device by appending a colon followed by the device identifier bsdauth or pam. depending on the server configuration. For example, "keyboard-interactive:bsdauth" would restrict keyboard interactive authentication to the bsdauth device. - If the publickey method is listed more than once, sshd(8) verifies that keys that have been used successfully are not reused for subsequent authentications. For example, "publickey,publickey" requires successful authentication using two different public keys.PATTERNS - Note that each authentication method listed should also be explicitly enabled in the configuration. - The available authentication methods are: "gssapi-with-mic", "hostbased", "keyboard-interactive", "none" (used for access to password-less accounts when PermitEmptyPasswords is enabled), "password" and "publickey".`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("any"), - }, - }, - docvalues.ArrayValue{ - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - - docvalues.CreateEnumString("password"), - docvalues.CreateEnumString("publickey"), - docvalues.CreateEnumString("gssapi-with-mic"), - docvalues.CreateEnumString("keyboard-interactive"), - docvalues.CreateEnumString("hostbased"), - - docvalues.CreateEnumString("password:bsdauth"), - docvalues.CreateEnumString("publickey:bsdauth"), - docvalues.CreateEnumString("gssapi-with-mic:bsdauth"), - docvalues.CreateEnumString("keyboard-interactive:bsdauth"), - docvalues.CreateEnumString("hostbased:bsdauth"), - - docvalues.CreateEnumString("password:pam"), - docvalues.CreateEnumString("publickey:pam"), - docvalues.CreateEnumString("gssapi-with-mic:pam"), - docvalues.CreateEnumString("keyboard-interactive:pam"), - docvalues.CreateEnumString("hostbased:pam"), - }, - }, - }, - }, - }, - ), - "AuthorizedKeysCommand": NewOption( - `Specifies a program to be used to look up the user's public keys. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedKeysCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. - The program should produce on standard output zero or more lines of authorized_keys output (see “AUTHORIZED_KEYS” in sshd(8)). AuthorizedKeysCommand is tried after the usual AuthorizedKeysFile files and will not be executed if a matching key is found there. By default, no AuthorizedKeysCommand is run.`, - docvalues.StringValue{}, - ), - - "AuthorizedKeysCommandUser": NewOption( - `Specifies the user under whose account the AuthorizedKeysCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized keys commands. If AuthorizedKeysCommand is specified but AuthorizedKeysCommandUser is not, then sshd(8) will refuse to start.`, - docvalues.UserValue("", true), - ), - "AuthorizedKeysFile": NewOption( - `Specifies the file that contains the public keys used for user authentication. The format is described in the AUTHORIZED_KEYS FILE FORMAT section of sshd(8). Arguments to AuthorizedKeysFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedKeysFile is taken to be an absolute path or one relative to the user's home directory. Multiple files may be listed, separated by whitespace. Alternately this option may be set to none to skip checking for user keys in files. The default is ".ssh/authorized_keys .ssh/authorized_keys2".`, - docvalues.ArrayValue{ - SubValue: docvalues.StringValue{}, - Separator: " ", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - }, - ), - "AuthorizedPrincipalsCommand": NewOption( - `Specifies a program to be used to generate the list of allowed certificate principals as per AuthorizedPrincipalsFile. The program must be owned by root, not writable by group or others and specified by an absolute path. Arguments to AuthorizedPrincipalsCommand accept the tokens described in the “TOKENS” section. If no arguments are specified then the username of the target user is used. - The program should produce on standard output zero or more lines of AuthorizedPrincipalsFile output. If either AuthorizedPrincipalsCommand or AuthorizedPrincipalsFile is specified, then certificates offered by the client for authentication must contain a principal that is listed. By default, no AuthorizedPrincipalsCommand is run.`, - docvalues.StringValue{}, - ), - "AuthorizedPrincipalsCommandUser": NewOption( - `Specifies the user under whose account the AuthorizedPrincipalsCommand is run. It is recommended to use a dedicated user that has no other role on the host than running authorized principals commands. If AuthorizedPrincipalsCommand is specified but AuthorizedPrincipalsCommandUser is not, then sshd(8) will refuse to start.`, - docvalues.UserValue("", true), - ), - "AuthorizedPrincipalsFile": NewOption( - `Specifies a file that lists principal names that are accepted for certificate authentication. When using certificates signed by a key listed in TrustedUserCAKeys, this file lists names, one of which must appear in the certificate for it to be accepted for authentication. Names are listed one per line preceded by key options (as described in “AUTHORIZED_KEYS FILE FORMAT” in sshd(8)). Empty lines and comments starting with ‘#’ are ignored. - Arguments to AuthorizedPrincipalsFile accept the tokens described in the “TOKENS” section. After expansion, AuthorizedPrincipalsFile is taken to be an absolute path or one relative to the user's home directory. The default is none, i.e. not to use a principals file – in this case, the username of the user must appear in a certificate's principals list for it to be accepted. - Note that AuthorizedPrincipalsFile is only used when authentication proceeds using a CA listed in TrustedUserCAKeys and is not consulted for certification authorities trusted via ~/.ssh/authorized_keys, though the principals= key option offers a similar facility (see sshd(8) for details).`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "Banner": NewOption(`The contents of the specified file are sent to the remote user before authentication is allowed. If the argument is none then no banner is displayed. By default, no banner is displayed.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "CASignatureAlgorithms": NewOption( - `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: - ssh-ed25519,ecdsa-sha2-nistp256, ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. - Certificates signed using other algorithms will not be accepted for public key or host-based authentication.`, - docvalues.PrefixWithMeaningValue{ - Prefixes: []docvalues.Prefix{ - { - Prefix: "+", - Meaning: "Appende to the default set", - }, - { - Prefix: "-", - Meaning: "Remove from the default set", - }, - }, - SubValue: docvalues.ArrayValue{ - Separator: ",", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - // TODO: Add - SubValue: docvalues.StringValue{}, - }, - }, - ), - "ChannelTimeout": NewOption(`Specifies whether and how quickly sshd(8) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. - The timeout value “interval” is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. - The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. - The available channel type names include: - - agent-connection Open connections to ssh-agent(1). - direct-tcpip, direct-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established from a ssh(1) local forwarding, i.e. LocalForward or DynamicForward. - forwarded-tcpip, forwarded-streamlocal@openssh.com Open TCP or Unix socket (respectively) connections that have been established to a sshd(8) listening on behalf of a ssh(1) remote forwarding, i.e. RemoteForward. - session The interactive main session, including shell session, command execution, scp(1), sftp(1), etc. - tun-connection Open TunnelForward connections. - x11-connection Open X11 forwarding sessions. - - Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. - Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. - The default is not to expire channels of any type for inactivity.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &ChannelTimeoutExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: false, - Separator: "=", - Key: docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("global"), - docvalues.CreateEnumString("agent-connection"), - docvalues.CreateEnumString("direct-tcpip"), - docvalues.CreateEnumString("direct-streamlocal@openssh.com"), - docvalues.CreateEnumString("forwarded-tcpip"), - docvalues.CreateEnumString("forwarded-streamlocal@openssh.com"), - docvalues.CreateEnumString("session"), - docvalues.CreateEnumString("tun-connection"), - docvalues.CreateEnumString("x11-connection"), - }, - }, - Value: TimeFormatValue{}, - }, - }, - ), - "ChrootDirectory": NewOption(`Specifies the pathname of a directory to chroot(2) to after authentication. At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others. After the chroot, sshd(8) changes the working directory to the user's home directory. Arguments to ChrootDirectory accept the tokens described in the “TOKENS” section. - The ChrootDirectory must contain the necessary files and directories to support the user's session. For an interactive session this requires at least a shell, typically sh(1), and basic /dev nodes such as null(4), zero(4), stdin(4), stdout(4), stderr(4), and tty(4) devices. For file transfer sessions using SFTP no additional configuration of the environment is necessary if the in-process sftp-server is used, though sessions which use logging may require /dev/log inside the chroot directory on some operating systems (see sftp-server(8) for details). - For safety, it is very important that the directory hierarchy be prevented from modification by other processes on the system (especially those outside the jail). Misconfiguration can lead to unsafe environments which sshd(8) cannot detect. - The default is none, indicating not to chroot(2).`, - docvalues.StringValue{}, - ), - "Ciphers": NewOption(`Specifies the ciphers allowed. Multiple ciphers must be comma-separated. If the specified list begins with a ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. - The supported ciphers are: - 3des-cbc aes128-cbc aes192-cbc aes256-cbc aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com chacha20-poly1305@openssh.com - The default is: - chacha20-poly1305@openssh.com, aes128-ctr,aes192-ctr,aes256-ctr, aes128-gcm@openssh.com,aes256-gcm@openssh.com - The list of available ciphers may also be obtained using "ssh -Q cipher".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("3des-cbc"), - docvalues.CreateEnumString("aes128-cbc"), - docvalues.CreateEnumString("aes192-cbc"), - docvalues.CreateEnumString("aes256-cbc"), - docvalues.CreateEnumString("aes128-ctr"), - docvalues.CreateEnumString("aes192-ctr"), - docvalues.CreateEnumString("aes256-ctr"), - docvalues.CreateEnumString("aes128-gcm@openssh.com"), - docvalues.CreateEnumString("aes256-gcm@openssh.com"), - docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), - }), - ), - "ClientAliveCountMax": NewOption(`Sets the number of client alive messages which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session. It is important to note that the use of client alive messages is very different from TCPKeepAlive. The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. - The default value is 3. If ClientAliveInterval is set to 15, and ClientAliveCountMax is left at the default, unresponsive SSH clients will be disconnected after approximately 45 seconds. Setting a zero ClientAliveCountMax disables connection termination.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "ClientAliveInterval": NewOption( - `Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client. The default is 0, indicating that these messages will not be sent to the client.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "Compression": NewOption( - `Specifies whether compression is enabled after the user has authenticated successfully. The argument must be yes, delayed (a legacy synonym for yes) or no. The default is yes.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("delayed"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "DenyGroups": NewOption(`This keyword can be followed by a list of group name patterns, separated by spaces. Login is disallowed for users whose primary group or supplementary group list matches one of the patterns. Only group names are valid; a numerical group ID is not recognized. By default, login is allowed for all groups. The allow/deny groups directives are processed in the following order: DenyGroups, AllowGroups. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.GroupValue(" ", false), - ), - "DenyUsers": NewOption(`This keyword can be followed by a list of user name patterns, separated by spaces. Login is disallowed for user names that match one of the patterns. Only user names are valid; a numerical user ID is not recognized. By default, login is allowed for all users. If the pattern takes the form USER@HOST then USER and HOST are separately checked, restricting logins to particular users from particular hosts. HOST criteria may additionally contain addresses to match in CIDR address/masklen format. The allow/deny users directives are processed in the following order: DenyUsers, AllowUsers. - See PATTERNS in ssh_config(5) for more information on patterns. This keyword may appear multiple times in sshd_config with each instance appending to the list.`, - docvalues.UserValue(" ", false), - ), - "DisableForwarding": NewOption( - `Disables all forwarding features, including X11, ssh-agent(1), TCP and StreamLocal. This option overrides all other forwarding-related options and may simplify restricted configurations.`, - BooleanEnumValue, - ), - "ExposeAuthInfo": NewOption( - `Writes a temporary file containing a list of authentication methods and public credentials (e.g. keys) used to authenticate the user. The location of the file is exposed to the user session through the SSH_USER_AUTH environment variable. The default is no.`, - BooleanEnumValue, - ), - "FingerprintHash": NewOption( - `Specifies the hash algorithm used when logging key fingerprints. Valid options are: md5 and sha256. The default is sha256.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("md5"), - docvalues.CreateEnumString("sha256"), - }, - }, - ), - "ForceCommand": NewOption( - `Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present. The command is invoked by using the user's login shell with the -c option. This applies to shell, command, or subsystem execution. It is most useful inside a Match block. The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. Specifying a command of internal-sftp will force the use of an in- process SFTP server that requires no support files when used with ChrootDirectory. The default is none.`, - docvalues.StringValue{}, - ), - "GatewayPorts": NewOption( - `Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.`, - BooleanEnumValue, - ), - "GSSAPIAuthentication": NewOption( - `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, - BooleanEnumValue, - ), - "GSSAPICleanupCredentials": NewOption( - `Specifies whether to automatically destroy the user's credentials cache on logout. The default is yes.`, - BooleanEnumValue, - ), - "GSSAPIStrictAcceptorCheck": NewOption( - `Determines whether to be strict about the identity of the GSSAPI acceptor a client authenticates against. If set to yes then the client must authenticate against the host service on the current hostname. If set to no then the client may authenticate against any service key stored in the machine's default store. This facility is provided to assist with operation on multi homed machines. The default is yes.`, - BooleanEnumValue, - ), - "HostbasedAcceptedAlgorithms": NewOption(`Specifies the signature algorithms that will be accepted for hostbased authentication as a list of comma-separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q HostbasedAcceptedAlgorithms". This was formerly named HostbasedAcceptedKeyTypes.`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, err := QueryOpenSSHOptions("HostbasedAcceptedAlgorithms") - - if err != nil { - // Fallback - options, _ = QueryOpenSSHOptions("HostbasedAcceptedKeyTypes") - } - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "HostbasedAuthentication": NewOption( - `Specifies whether rhosts or /etc/hosts.equiv authentication together with successful public key client host authentication is allowed (host-based authentication). The default is no.`, - BooleanEnumValue, - ), - "HostbasedUsesNameFromPacketOnly": NewOption( - `Specifies whether or not the server will attempt to perform a reverse name lookup when matching the name in the ~/.shosts, ~/.rhosts, and /etc/hosts.equiv files during HostbasedAuthentication. A setting of yes means that sshd(8) uses the name supplied by the client rather than attempting to resolve the name from the TCP connection itself. The default is no.`, - BooleanEnumValue, - ), - "HostCertificate": NewOption( - `Specifies a file containing a public host certificate. The certificate's public key must match a private host key already specified by HostKey. The default behaviour of sshd(8) is not to load any certificates.`, - docvalues.PathValue{}, - ), - "HostKey": NewOption(`Specifies a file containing a private host key used by SSH. The defaults are /etc/ssh/ssh_host_ecdsa_key, /etc/ssh/ssh_host_ed25519_key and /etc/ssh/ssh_host_rsa_key. - Note that sshd(8) will refuse to use a file if it is group/world-accessible and that the HostKeyAlgorithms option restricts which of the keys are actually used by sshd(8). - It is possible to have multiple host key files. It is also possible to specify public host key files instead. In this case operations on the private key will be delegated to an ssh-agent(1).`, - docvalues.PathValue{}, - ), - "HostKeyAgent": NewOption( - `Identifies the UNIX-domain socket used to communicate with an agent that has access to the private host keys. If the string "SSH_AUTH_SOCK" is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumStringWithDoc("SSH_AUTH_SOCK", "The location of the socket will be read from the SSH_AUTH_SOCK environment variable."), - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "HostKeyAlgorithms": NewOption(`Specifies the host key signature algorithms that the server offers. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := QueryOpenSSHOptions("HostKeyAlgorithms") - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "IgnoreRhosts": NewOption(`Specifies whether to ignore per-user .rhosts and .shosts files during HostbasedAuthentication. The system-wide /etc/hosts.equiv and /etc/shosts.equiv are still used regardless of this setting. - Accepted values are yes (the default) to ignore all per- user files, shosts-only to allow the use of .shosts but to ignore .rhosts or no to allow both .shosts and rhosts.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("shosts-only"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "IgnoreUserKnownHosts": NewOption( - `Specifies whether sshd(8) should ignore the user's ~/.ssh/known_hosts during HostbasedAuthentication and use only the system-wide known hosts file /etc/ssh/ssh_known_hosts. The default is “no”.`, - BooleanEnumValue, - ), - "Include": NewOption(`Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards that will be expanded and processed in lexical order. Files without absolute paths are assumed to be in /etc/ssh. An Include directive may appear inside a Match block to perform conditional inclusion.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - }, - // TODO: Add extra check - ), - - "IPQoS": NewOption(`Specifies the IPv4 type-of-service or DSCP class for the connection. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.NumberValue{}, - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - }, - }, - docvalues.ArrayValue{ - Separator: " ", - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("af11"), - docvalues.CreateEnumString("af12"), - docvalues.CreateEnumString("af13"), - docvalues.CreateEnumString("af21"), - docvalues.CreateEnumString("af22"), - docvalues.CreateEnumString("af23"), - docvalues.CreateEnumString("af31"), - docvalues.CreateEnumString("af32"), - docvalues.CreateEnumString("af33"), - docvalues.CreateEnumString("af41"), - docvalues.CreateEnumString("af42"), - docvalues.CreateEnumString("af43"), - docvalues.CreateEnumString("cs0"), - docvalues.CreateEnumString("cs1"), - docvalues.CreateEnumString("cs2"), - docvalues.CreateEnumString("cs3"), - docvalues.CreateEnumString("cs4"), - docvalues.CreateEnumString("cs5"), - docvalues.CreateEnumString("cs6"), - docvalues.CreateEnumString("cs7"), - docvalues.CreateEnumString("ef"), - docvalues.CreateEnumString("le"), - docvalues.CreateEnumString("lowdelay"), - docvalues.CreateEnumString("throughput"), - docvalues.CreateEnumString("reliability"), - docvalues.CreateEnumString("none"), - }, - }, - }, - }, - }, - ), - "KbdInteractiveAuthentication": NewOption( - `Specifies whether to allow keyboard-interactive authentication. All authentication styles from login.conf(5) are supported. The default is yes. The argument to this keyword must be yes or no. ChallengeResponseAuthentication is a deprecated alias for this.`, - BooleanEnumValue, - ), - "KerberosAuthentication": NewOption(`Specifies whether the password provided by the user for PasswordAuthentication will be validated through the Kerberos KDC. To use this option, the server needs a Kerberos servtab which allows the verification of the KDC's identity. The default is no.`, - BooleanEnumValue, - ), - "KerberosGetAFSToken": NewOption(`If AFS is active and the user has a Kerberos 5 TGT, attempt to acquire an AFS token before accessing the user's home directory. The default is no.`, - BooleanEnumValue, - ), - "KerberosOrLocalPasswd": NewOption(`If password authentication through Kerberos fails then the password will be validated via any additional local mechanism such as /etc/passwd. The default is yes.`, - BooleanEnumValue, - ), - "KerberosTicketCleanup": NewOption(`Specifies whether to automatically destroy the user's ticket cache file on logout. The default is yes.`, - BooleanEnumValue, - ), - "KexAlgorithms": NewOption(`Specifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The supported algorithms are: - curve25519-sha256 curve25519-sha256@libssh.org diffie-hellman-group1-sha1 diffie-hellman-group14-sha1 diffie-hellman-group14-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group-exchange-sha1 diffie-hellman-group-exchange-sha256 ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 sntrup761x25519-sha512@openssh.com - The default is: - sntrup761x25519-sha512@openssh.com, curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512,diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 - The list of available key exchange algorithms may also be obtained using "ssh -Q KexAlgorithms".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("curve25519-sha256"), - docvalues.CreateEnumString("curve25519-sha256@libssh.org"), - docvalues.CreateEnumString("diffie-hellman-group1-sha1"), - docvalues.CreateEnumString("diffie-hellman-group14-sha1"), - docvalues.CreateEnumString("diffie-hellman-group14-sha256"), - docvalues.CreateEnumString("diffie-hellman-group16-sha512"), - docvalues.CreateEnumString("diffie-hellman-group18-sha512"), - docvalues.CreateEnumString("diffie-hellman-group-exchange-sha1"), - docvalues.CreateEnumString("diffie-hellman-group-exchange-sha256"), - docvalues.CreateEnumString("ecdh-sha2-nistp256"), - docvalues.CreateEnumString("ecdh-sha2-nistp384"), - docvalues.CreateEnumString("ecdh-sha2-nistp521"), - docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), - }), - ), - "ListenAddress": NewOption(`Specifies the local addresses sshd(8) should listen on. The following forms may be used: - ListenAddress hostname|address [rdomain domain] ListenAddress hostname:port [rdomain domain] ListenAddress IPv4_address:port [rdomain domain] ListenAddress [hostname|address]:port [rdomain domain] - The optional rdomain qualifier requests sshd(8) listen in an explicit routing domain. If port is not specified, sshd will listen on the address and all Port options specified. The default is to listen on all local addresses on the current default routing domain. Multiple ListenAddress options are permitted. For more information on routing domains, see rdomain(4).`, - docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - Separator: ":", - Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - ), - "LoginGraceTime": NewOption(`The server disconnects after this time if the user has not successfully logged in. If the value is 0, there is no time limit. The default is 120 seconds.`, - TimeFormatValue{}, - ), - "LogLevel": NewOption(`Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of debugging output. Logging with a DEBUG level violates the privacy of users and is not recommended.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("QUIET"), - docvalues.CreateEnumString("FATAL"), - docvalues.CreateEnumString("ERROR"), - docvalues.CreateEnumString("INFO"), - docvalues.CreateEnumString("VERBOSE"), - docvalues.CreateEnumString("DEBUG"), - docvalues.CreateEnumString("DEBUG1"), - docvalues.CreateEnumString("DEBUG2"), - docvalues.CreateEnumString("DEBUG3"), - }, - }, - ), - "LogVerbose": NewOption(`Specify one or more overrides to LogLevel. An override consists of a pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: - kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* - would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, - docvalues.StringValue{}, - ), - - "MACs": NewOption(`Specifies the available MAC (message authentication code) algorithms. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. - The algorithms that contain "-etm" calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. The supported MACs are: - hmac-md5 hmac-md5-96 hmac-sha1 hmac-sha1-96 hmac-sha2-256 hmac-sha2-512 umac-64@openssh.com umac-128@openssh.com hmac-md5-etm@openssh.com hmac-md5-96-etm@openssh.com hmac-sha1-etm@openssh.com hmac-sha1-96-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com umac-64-etm@openssh.com umac-128-etm@openssh.com - The default is: - umac-64-etm@openssh.com,umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com,umac-128@openssh.com, hmac-sha2-256,hmac-sha2-512,hmac-sha1 - The list of available MAC algorithms may also be obtained using "ssh -Q mac".`, - PrefixPlusMinusCaret([]docvalues.EnumString{ - docvalues.CreateEnumString("hmac-md5"), - docvalues.CreateEnumString("hmac-md5-96"), - docvalues.CreateEnumString("hmac-sha1"), - docvalues.CreateEnumString("hmac-sha1-96"), - docvalues.CreateEnumString("hmac-sha2-256"), - docvalues.CreateEnumString("hmac-sha2-256"), - docvalues.CreateEnumString("hmac-sha2-512"), - docvalues.CreateEnumString("umac-64@openssh.com"), - docvalues.CreateEnumString("umac-128@openssh.com"), - docvalues.CreateEnumString("hmac-md5-etm@openssh.com"), - docvalues.CreateEnumString("hmac-md5-96-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha1-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha1-96-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha2-256-etm@openssh.com"), - docvalues.CreateEnumString("hmac-sha2-512-etm@openssh.com"), - docvalues.CreateEnumString("umac-64-etm@openssh.com"), - docvalues.CreateEnumString("umac-128-etm@openssh.com"), - }), - ), - - // Match Introduces a conditional block. If all of the criteria on the Match line are satisfied, the keywords on the following lines override those set in the global section of the config file, until either another Match line or the end of the file. If a keyword appears in multiple Match blocks that are satisfied, only the first instance of the keyword is applied. - // The arguments to Match are one or more criteria-pattern pairs or the single token All which matches all criteria. The available criteria are User, Group, Host, LocalAddress, LocalPort, RDomain, and Address (with RDomain representing the rdomain(4) on which the connection was received). - // The match patterns may consist of single entries or comma-separated lists and may use the wildcard and negation operators described in the “PATTERNS” section of ssh_config(5). - // The patterns in an Address criteria may additionally contain addresses to match in CIDR address/masklen format, such as 192.0.2.0/24 or 2001:db8::/32. Note that the mask length provided must be consistent with the address - it is an error to specify a mask length that is too long for the address or one with bits set in this host portion of the address. For example, 192.0.2.0/33 and 192.0.2.0/8, respectively. - // Only a subset of keywords may be used on the lines following a Match keyword. Available keywords are AcceptEnv, AllowAgentForwarding, AllowGroups, AllowStreamLocalForwarding, AllowTcpForwarding, AllowUsers, AuthenticationMethods, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedKeysFile, AuthorizedPrincipalsCommand, AuthorizedPrincipalsCommandUser, AuthorizedPrincipalsFile, Banner, CASignatureAlgorithms, ChannelTimeout, ChrootDirectory, ClientAliveCountMax, ClientAliveInterval, DenyGroups, DenyUsers, DisableForwarding, ExposeAuthInfo, ForceCommand, GatewayPorts, GSSAPIAuthentication, HostbasedAcceptedAlgorithms, HostbasedAuthentication, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, Include, IPQoS, KbdInteractiveAuthentication, KerberosAuthentication, LogLevel, MaxAuthTries, MaxSessions, PasswordAuthentication, PermitEmptyPasswords, PermitListen, PermitOpen, PermitRootLogin, PermitTTY, PermitTunnel, PermitUserRC, PubkeyAcceptedAlgorithms, PubkeyAuthentication, PubkeyAuthOptions, RekeyLimit, RevokedKeys, RDomain, SetEnv, StreamLocalBindMask, StreamLocalBindUnlink, TrustedUserCAKeys, UnusedConnectionTimeout, X11DisplayOffset, X11Forwarding and X11UseLocalhost.`, - "MaxAuthTries": NewOption(`Specifies the maximum number of authentication attempts permitted per connection. Once the number of failures reaches half this value, additional failures are logged. The default is 6.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "MaxSessions": NewOption(`Specifies the maximum number of open shell, login or subsystem (e.g. sftp) sessions permitted per network connection. Multiple sessions may be established by clients that support connection multiplexing. Setting MaxSessions to 1 will effectively disable session multiplexing, whereas setting it to 0 will prevent all shell, login and subsystem sessions while still permitting forwarding. The default is 10.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "MaxStartups": NewOption(`Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon. Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection. The default is 10:30:100. - Alternatively, random early drop can be enabled by specifying the three colon separated values start:rate:full (e.g. "10:30:60"). sshd(8) will refuse connection attempts with a probability of rate/100 (30%) if there are currently start (10) unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).`, - // TODO: Add custom value `SeapartorValue` that takes an array of values and separators - docvalues.RegexValue{ - Regex: *regexp.MustCompile(`^(\d+):(\d+):(\d+)$`), - }, - ), - "ModuliFile": NewOption(`Specifies the moduli(5) file that contains the Diffie- Hellman groups used for the “diffie-hellman-group-exchange-sha1” and “diffie-hellman-group-exchange-sha256” key exchange methods. The default is /etc/moduli.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - "PasswordAuthentication": NewOption(`Specifies whether password authentication is allowed. The default is yes.`, - BooleanEnumValue, - ), - "PermitEmptyPasswords": NewOption(`When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is no.`, - BooleanEnumValue, - ), - "PermitListen": NewOption(`Specifies the addresses/ports on which a remote TCP port forwarding may listen. The listen specification must be one of the following forms: - PermitListen port PermitListen host:port - Multiple permissions may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any listen requests. An argument of none can be used to prohibit all listen requests. The host name may contain wildcards as described in the PATTERNS section in ssh_config(5). The wildcard ‘*’ can also be used in place of a port number to allow all ports. By default all port forwarding listen requests are permitted. Note that the GatewayPorts option may further restrict which addresses may be listened on. Note also that ssh(1) will request a listen host of “localhost” if no listen host was specifically requested, and this name is treated differently to explicit localhost addresses of “127.0.0.1” and “::1”.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - Separator: ":", - Value: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all ports", - }, - }, - EnforceValues: true, - }, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - }, - }, - }, - ), - "PermitOpen": NewOption(`Specifies the destinations to which TCP port forwarding is permitted. The forwarding specification must be one of the following forms: - PermitOpen host:port PermitOpen IPv4_addr:port PermitOpen [IPv6_addr]:port - Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names. By default all port forwarding requests are permitted.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: true, - Key: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all hosts", - }, - }, - }, - docvalues.IPAddressValue{ - AllowIPv4: true, - AllowIPv6: true, - AllowRange: false, - DisallowedIPs: &docvalues.NonRoutableNetworks, - }, - }, - }, - Separator: ":", - Value: docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "*", - DescriptionText: "\\*", - Documentation: "Allow all ports", - }, - }, - EnforceValues: true, - }, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - }, - }, - }, - }, - ), - "PermitRootLogin": NewOption(`Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password, forced-commands-only, or no. The default is prohibit-password. - If this option is set to prohibit-password (or its deprecated alias, without-password), password and keyboard-interactive authentication are disabled for root. - If this option is set to forced-commands-only, root login with public key authentication will be allowed, but only if the command option has been specified (which may be useful for taking remote backups even if root login is normally not allowed). All other authentication methods are disabled for root. - If this option is set to no, root is not allowed to log in.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("prohibit-password"), - docvalues.CreateEnumString("forced-commands-only"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "PermitTTY": NewOption(`Specifies whether pty(4) allocation is permitted. The default is yes.`, - BooleanEnumValue, - ), - "PermitTunnel": NewOption(`Specifies whether tun(4) device forwarding is allowed. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no. Specifying yes permits both point-to-point and ethernet. The default is no. - Independent of this setting, the permissions of the selected tun(4) device must allow access to the user.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("point-to-point"), - docvalues.CreateEnumString("ethernet"), - docvalues.CreateEnumString("no"), - }, - }, - ), - "PermitUserEnvironment": NewOption(`Specifies whether ~/.ssh/environment and environment= options in ~/.ssh/authorized_keys are processed by sshd(8). Valid options are yes, no or a pattern-list specifying which environment variable names to accept (for example "LANG,LC_*"). The default is no. Enabling environment processing may enable users to bypass access restrictions in some configurations using mechanisms such as LD_PRELOAD.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("yes"), - docvalues.CreateEnumString("no"), - }, - }, - docvalues.ArrayValue{ - SubValue: docvalues.StringValue{}, - Separator: ",", - DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, - }, - }, - }, - ), - "PermitUserRC": NewOption(`Specifies whether any ~/.ssh/rc file is executed. The default is yes.`, - BooleanEnumValue, - ), - "PerSourceMaxStartups": NewOption(`Specifies the number of unauthenticated connections allowed from a given source address, or “none” if there is no limit. This limit is applied in addition to MaxStartups, whichever is lower. The default is none.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - { - InsertText: "none", - DescriptionText: "none", - Documentation: "No limit", - }, - }, - }, - docvalues.NumberValue{Min: &ZERO}, - }, - }, - ), - "PerSourceNetBlockSize": NewOption(`Specifies the number of bits of source address that are grouped together for the purposes of applying PerSourceMaxStartups limits. Values for IPv4 and optionally IPv6 may be specified, separated by a colon. The default is 32:128, which means each address is considered individually.`, - docvalues.KeyValueAssignmentValue{ - Separator: ":", - ValueIsOptional: false, - Key: docvalues.NumberValue{Min: &ZERO}, - Value: docvalues.NumberValue{Min: &ZERO}, - }, - ), - "PidFile": NewOption(`Specifies the file that contains the process ID of the SSH daemon, or none to not write one. The default is /var/run/sshd.pid.`, - docvalues.StringValue{}, - ), - - "Port": NewOption(`Specifies the port number that sshd(8) listens on. The default is 22. Multiple options of this type are permitted. See also ListenAddress.`, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, - ), - "PrintLastLog": NewOption(`Specifies whether sshd(8) should print the date and time of the last user login when a user logs in interactively. The default is yes.`, - BooleanEnumValue, - ), - "PrintMotd": NewOption(`Specifies whether sshd(8) should print /etc/motd when a user logs in interactively. (On some systems it is also printed by the shell, /etc/profile, or equivalent.) The default is yes.`, - BooleanEnumValue, - ), - "PubkeyAcceptedAlgorithms": NewOption(`Specifies the signature algorithms that will be accepted for public key authentication as a list of comma- separated patterns. Alternately if the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: - ssh-ed25519-cert-v01@openssh.com, ecdsa-sha2-nistp256-cert-v01@openssh.com, ecdsa-sha2-nistp384-cert-v01@openssh.com, ecdsa-sha2-nistp521-cert-v01@openssh.com, sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, rsa-sha2-512-cert-v01@openssh.com, rsa-sha2-256-cert-v01@openssh.com, ssh-ed25519, ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com, rsa-sha2-512,rsa-sha2-256 - The list of available signature algorithms may also be obtained using "ssh -Q PubkeyAcceptedAlgorithms".`, - docvalues.CustomValue{ - FetchValue: func(_ docvalues.CustomValueContext) docvalues.Value { - options, _ := QueryOpenSSHOptions("PubkeyAcceptedAlgorithms") - - return PrefixPlusMinusCaret(options) - }, - }, - ), - "PubkeyAuthOptions": NewOption(`Sets one or more public key authentication options. The supported keywords are: none (the default; indicating no additional options are enabled), touch-required and verify-required. - The touch-required option causes public key authentication using a FIDO authenticator algorithm (i.e. ecdsa-sk or ed25519-sk) to always require the signature to attest that a physically present user explicitly confirmed the authentication (usually by touching the authenticator). By default, sshd(8) requires user presence unless overridden with an authorized_keys option. The touch-required flag disables this override. - The verify-required option requires a FIDO key signature attest that the user was verified, e.g. via a PIN. - Neither the touch-required or verify-required options have any effect for other, non-FIDO, public key types.`, - docvalues.ArrayValue{ - Separator: ",", - SubValue: docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - docvalues.CreateEnumString("touch-required"), - docvalues.CreateEnumString("verify-required"), - }, - }, - }, - ), - "PubkeyAuthentication": NewOption(`Specifies whether public key authentication is allowed. The default is yes.`, - BooleanEnumValue, - ), - "RekeyLimit": NewOption(`Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the “TIME FORMATS” section. The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, - docvalues.KeyValueAssignmentValue{ - Separator: " ", - ValueIsOptional: true, - Key: DataAmountValue{}, - Value: TimeFormatValue{}, - }, - ), - "RequiredRSASize": NewOption(`Specifies the minimum RSA key size (in bits) that sshd(8) will accept. User and host-based authentication keys smaller than this limit will be refused. The default is 1024 bits. Note that this limit may only be raised from the default.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "RevokedKeys": NewOption(`Specifies revoked public keys file, or none to not use one. Keys listed in this file will be refused for public key authentication. Note that if this file is not readable, then public key authentication will be refused for all users. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1).`, - docvalues.StringValue{}, - ), - "RDomain": NewOption(`Specifies an explicit routing domain that is applied after authentication has completed. The user session, as well as any forwarded or listening IP sockets, will be bound to this rdomain(4). If the routing domain is set to %D, then the domain in which the incoming connection was received will be applied.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - Values: []docvalues.EnumString{ - { - InsertText: "%D", - DescriptionText: "%D", - Documentation: "The domain in which the incoming connection was received", - }, - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "SecurityKeyProvider": NewOption(`Specifies a path to a library that will be used when loading FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support.`, - docvalues.PathValue{ - RequiredType: docvalues.PathTypeFile, - }, - ), - - "SetEnv": NewOption(`Specifies one or more environment variables to set in child sessions started by sshd(8) as “NAME=VALUE”. The environment value may be quoted (e.g. if it contains whitespace characters). Environment variables set by SetEnv override the default environment and any variables specified by the user via AcceptEnv or PermitUserEnvironment.`, - docvalues.ArrayValue{ - Separator: " ", - DuplicatesExtractor: &SetEnvExtractor, - SubValue: docvalues.KeyValueAssignmentValue{ - ValueIsOptional: false, - Separator: "=", - Key: docvalues.StringValue{}, - Value: docvalues.StringValue{}, - }, - }, - ), - "StreamLocalBindMask": NewOption(`Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. - The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, - docvalues.NumberValue{Min: &ZERO, Max: &MAX_FILE_MODE}, - ), - "StreamLocalBindUnlink": NewOption(`Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. - The argument must be yes or no. The default is no.`, - BooleanEnumValue, - ), - "StrictModes": NewOption(`Specifies whether sshd(8) should check file modes and ownership of the user's files and home directory before accepting login. This is normally desirable because novices sometimes accidentally leave their directory or files world-writable. The default is yes. Note that this does not apply to ChrootDirectory, whose permissions and ownership are checked unconditionally.`, - BooleanEnumValue, - ), - "Subsystem": NewOption(`Configures an external subsystem (e.g. file transfer daemon). Arguments should be a subsystem name and a command (with optional arguments) to execute upon subsystem request. - The command sftp-server implements the SFTP file transfer subsystem. - Alternately the name internal-sftp implements an in- process SFTP server. This may simplify configurations using ChrootDirectory to force a different filesystem root on clients. It accepts the same command line arguments as sftp-server and even though it is in- process, settings such as LogLevel or SyslogFacility do not apply to it and must be set explicitly via command line arguments. - By default no subsystems are defined.`, - docvalues.StringValue{}, - ), - "SyslogFacility": NewOption(`Gives the facility code that is used when logging messages from sshd(8). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.`, - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("DAEMON"), - docvalues.CreateEnumString("USER"), - docvalues.CreateEnumString("AUTH"), - docvalues.CreateEnumString("LOCAL0"), - docvalues.CreateEnumString("LOCAL1"), - docvalues.CreateEnumString("LOCAL2"), - docvalues.CreateEnumString("LOCAL3"), - docvalues.CreateEnumString("LOCAL4"), - docvalues.CreateEnumString("LOCAL5"), - docvalues.CreateEnumString("LOCAL6"), - docvalues.CreateEnumString("LOCAL7"), - }, - }, - ), - "TCPKeepAlive": NewOption(`Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. On the other hand, if TCP keepalives are not sent, sessions may hang indefinitely on the server, leaving "ghost" users and consuming server resources. - The default is yes (to send TCP keepalive messages), and the server will notice if the network goes down or the client host crashes. This avoids infinitely hanging sessions. - To disable TCP keepalive messages, the value should be set to no.`, - BooleanEnumValue, - ), - "TrustedUserCAKeys": NewOption(`Specifies a file containing public keys of certificate authorities that are trusted to sign user certificates for authentication, or none to not use one. Keys are listed one per line; empty lines and comments starting with ‘#’ are allowed. If a certificate is presented for authentication and has its signing CA key listed in this file, then it may be used for authentication for any user listed in the certificate's principals list. Note that certificates that lack a list of principals will not be permitted for authentication using TrustedUserCAKeys. For more details on certificates, see the CERTIFICATES section in ssh-keygen(1).`, - docvalues.StringValue{}, - ), - "UnusedConnectionTimeout": NewOption(`Specifies whether and how quickly sshd(8) should close client connections with no open channels. Open channels include active shell, command execution or subsystem sessions, connected network, socket, agent or X11 forwardings. Forwarding listeners, such as those from the ssh(1) -R flag, are not considered as open channels and do not prevent the timeout. The timeout value is specified in seconds or may use any of the units documented in the “TIME FORMATS” section. - Note that this timeout starts when the client connection completes user authentication but before the client has an opportunity to open any channels. Caution should be used when using short timeout values, as they may not provide sufficient time for the client to request and open its channels before terminating the connection. - The default none is to never expire connections for having no open channels. This option may be useful in conjunction with ChannelTimeout.`, - TimeFormatValue{}, - ), - "UseDNS": NewOption(`Specifies whether sshd(8) should look up the remote host name, and to check that the resolved host name for the remote IP address maps back to the very same IP address. - If this option is set to no (the default) then only addresses and not host names may be used in ~/.ssh/authorized_keys from and sshd_config Match Host directives.`, - BooleanEnumValue, - ), - - "UsePAM": NewOption(`Enables the Pluggable Authentication Module interface. If set to yes this will enable PAM authentication using KbdInteractiveAuthentication and PasswordAuthentication in addition to PAM account and session module processing for all authentication types. - Because PAM keyboard-interactive authentication usually serves an equivalent role to password authentication, you should disable either PasswordAuthentication or KbdInteractiveAuthentication. - If UsePAM is enabled, you will not be able to run sshd(8) as a non-root user. The default is no.`, - BooleanEnumValue, - ), - "VersionAddendum": NewOption(`Optionally specifies additional text to append to the SSH protocol banner sent by the server upon connection. The default is none.`, - docvalues.OrValue{ - Values: []docvalues.Value{ - docvalues.EnumValue{ - EnforceValues: true, - Values: []docvalues.EnumString{ - docvalues.CreateEnumString("none"), - }, - }, - docvalues.StringValue{}, - }, - }, - ), - "X11DisplayOffset": NewOption(`Specifies the first display number available for sshd(8)'s X11 forwarding. This prevents sshd from interfering with real X11 servers. The default is 10.`, - docvalues.NumberValue{Min: &ZERO}, - ), - "X11Forwarding": NewOption(`Specifies whether X11 forwarding is permitted. The argument must be yes or no. The default is no. - When X11 forwarding is enabled, there may be additional exposure to the server and to client displays if the sshd(8) proxy display is configured to listen on the wildcard address (see X11UseLocalhost), though this is not the default. Additionally, the authentication spoofing and authentication data verification and substitution occur on the client side. The security risk of using X11 forwarding is that the client's X11 display server may be exposed to attack when the SSH client requests forwarding (see the warnings for ForwardX11 in ssh_config(5)). A system administrator may have a stance in which they want to protect clients that may expose themselves to attack by unwittingly requesting X11 forwarding, which can warrant a no setting. - Note that disabling X11 forwarding does not prevent users from forwarding X11 traffic, as users can always install their own forwarders.`, - BooleanEnumValue, - ), - "X11UseLocalhost": NewOption(`Specifies whether sshd(8) should bind the X11 forwarding server to the loopback address or to the wildcard address. By default, sshd binds the forwarding server to the loopback address and sets the hostname part of the DISPLAY environment variable to localhost. This prevents remote hosts from connecting to the proxy display. However, some older X11 clients may not function with this configuration. X11UseLocalhost may be set to no to specify that the forwarding server should be bound to the wildcard address. The argument must be yes or no. The default is yes.`, - BooleanEnumValue, - ), - "XAuthLocation": NewOption(`Specifies the full pathname of the xauth(1) program, or none to not use one. The default is /usr/X11R6/bin/xauth.`, - docvalues.StringValue{}, - ), -} diff --git a/handlers/openssh/parser.go b/handlers/openssh/parser.go deleted file mode 100644 index 21a6219..0000000 --- a/handlers/openssh/parser.go +++ /dev/null @@ -1,146 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "regexp" - "strings" -) - -type SimpleConfigPosition struct { - Line uint32 -} - -type SimpleConfigLine struct { - Value string - Separator string - Position SimpleConfigPosition -} - -// Get the character positions of [Option End, Separator End, Value End] -func (l SimpleConfigLine) GetCharacterPositions(optionName string) [3]int { - return [3]int{len(optionName), len(optionName + l.Separator), len(optionName + l.Separator + l.Value)} -} - -type SimpleConfigOptions struct { - Separator regexp.Regexp - IgnorePattern regexp.Regexp - // This is the separator that will be used when adding a new line - IdealSeparator string - AvailableOptions *map[string]Option -} - -type SimpleConfigParser struct { - Lines map[string]SimpleConfigLine - Options SimpleConfigOptions -} - -func (p *SimpleConfigParser) AddLine(line string, lineNumber uint32) (string, error) { - var option string - var separator string - var value string - - re := p.Options.Separator - matches := re.FindStringSubmatch(line) - - if len(matches) == 0 { - return "", docvalues.MalformedLineError{} - } - - optionIndex := re.SubexpIndex("OptionName") - if optionIndex == -1 { - return "", docvalues.MalformedLineError{} - } - option = matches[optionIndex] - - if _, exists := (*p.Options.AvailableOptions)[option]; !exists { - return option, docvalues.OptionUnknownError{} - } - - separatorIndex := re.SubexpIndex("Separator") - if separatorIndex == -1 { - return option, docvalues.MalformedLineError{} - } - separator = matches[separatorIndex] - - valueIndex := re.SubexpIndex("Value") - if valueIndex == -1 { - return option, docvalues.MalformedLineError{} - } - value = matches[valueIndex] - - if _, exists := p.Lines[option]; exists { - return option, docvalues.OptionAlreadyExistsError{ - AlreadyLine: p.Lines[option].Position.Line, - } - } - - p.Lines[option] = SimpleConfigLine{ - Value: value, - Separator: separator, - Position: SimpleConfigPosition{ - Line: lineNumber, - }, - } - - return option, nil - -} - -func (p *SimpleConfigParser) ReplaceOption(option string, value string) { - p.Lines[option] = SimpleConfigLine{ - Value: value, - Position: SimpleConfigPosition{ - Line: p.Lines[option].Position.Line, - }, - } -} - -func (p *SimpleConfigParser) RemoveOption(option string) { - delete(p.Lines, option) -} - -func (p *SimpleConfigParser) GetOption(option string) (SimpleConfigLine, error) { - if _, exists := p.Lines[option]; exists { - return p.Lines[option], nil - } - - return SimpleConfigLine{}, docvalues.OptionUnknownError{} -} - -func (p *SimpleConfigParser) ParseFromFile(content string) []docvalues.OptionError { - lines := strings.Split(content, "\n") - errors := make([]docvalues.OptionError, 0) - - for index, line := range lines { - if p.Options.IgnorePattern.MatchString(line) { - continue - } - - option, err := p.AddLine(line, uint32(index)) - - if err != nil { - errors = append(errors, docvalues.OptionError{ - Line: uint32(index), - ProvidedOption: option, - DocError: err, - }) - } - } - - return errors -} - -func (p *SimpleConfigParser) Clear() { - clear(p.Lines) -} - -// TODO: Use better approach: Store an extra array of lines in order; with references to the SimpleConfigLine -func (p *SimpleConfigParser) FindByLineNumber(lineNumber uint32) (string, SimpleConfigLine, error) { - for option, line := range p.Lines { - if line.Position.Line == lineNumber { - return option, line, nil - } - } - - return "", SimpleConfigLine{Value: "", Position: SimpleConfigPosition{Line: 0}}, docvalues.LineNotFoundError{} -} diff --git a/handlers/openssh/shared.go b/handlers/openssh/shared.go deleted file mode 100644 index 779c937..0000000 --- a/handlers/openssh/shared.go +++ /dev/null @@ -1,19 +0,0 @@ -package openssh - -import ( - "regexp" -) - -func createOpenSSHConfigParser() SimpleConfigParser { - return SimpleConfigParser{ - Lines: make(map[string]SimpleConfigLine), - Options: SimpleConfigOptions{ - Separator: *regexp.MustCompile(`(?m)^\s*(?P\w+)(?P\s*)(?P.*)\s*$`), - IgnorePattern: *regexp.MustCompile(`^(?:#|\s*$)`), - IdealSeparator: " ", - AvailableOptions: &Options, - }, - } -} - -var Parser = createOpenSSHConfigParser() diff --git a/handlers/openssh/text-document-completion.go b/handlers/openssh/text-document-completion.go deleted file mode 100644 index a6cec50..0000000 --- a/handlers/openssh/text-document-completion.go +++ /dev/null @@ -1,62 +0,0 @@ -package openssh - -import ( - docvalues "config-lsp/doc-values" - "errors" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" - "golang.org/x/exp/maps" - - _ "github.com/tliron/commonlog/simple" -) - -func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (interface{}, error) { - optionName, line, err := Parser.FindByLineNumber(uint32(params.Position.Line)) - - if err == nil { - if params.Position.Character < uint32(len(optionName)) { - return getRootCompletions(), nil - } else { - cursor := params.Position.Character - uint32(line.GetCharacterPositions(optionName)[1]) - - return getOptionCompletions(optionName, line.Value, cursor), nil - } - } else if errors.Is(err, docvalues.LineNotFoundError{}) { - return getRootCompletions(), nil - } - - return nil, err -} - -func getRootCompletions() []protocol.CompletionItem { - completions := make([]protocol.CompletionItem, len(Options)) - - optionsKey := maps.Keys(Options) - for index := 0; index < len(maps.Keys(Options)); index++ { - label := optionsKey[index] - option := Options[label] - insertText := label + " " + "${1:value}" - - format := protocol.InsertTextFormatSnippet - kind := protocol.CompletionItemKindField - - completions[index] = protocol.CompletionItem{ - Label: label, - Documentation: GetDocumentation(&option), - InsertText: &insertText, - InsertTextFormat: &format, - Kind: &kind, - } - } - - return completions -} - -func getOptionCompletions(optionName string, line string, cursor uint32) []protocol.CompletionItem { - option := Options[optionName] - - completions := option.Value.FetchCompletions(line, cursor) - - return completions -} diff --git a/handlers/openssh/text-document-did-change.go b/handlers/openssh/text-document-did-change.go deleted file mode 100644 index 652887c..0000000 --- a/handlers/openssh/text-document-did-change.go +++ /dev/null @@ -1,24 +0,0 @@ -package openssh - -import ( - "config-lsp/common" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -// Todo: Implement incremental parsing -func TextDocumentDidChange(context *glsp.Context, params *protocol.DidChangeTextDocumentParams) error { - content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text - - Parser.Clear() - diagnostics := DiagnoseParser(context, params.TextDocument.URI, content) - - if len(diagnostics) > 0 { - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - } else { - common.ClearDiagnostics(context, params.TextDocument.URI) - } - - return nil -} diff --git a/handlers/openssh/text-document-did-open.go b/handlers/openssh/text-document-did-open.go deleted file mode 100644 index 7c533e3..0000000 --- a/handlers/openssh/text-document-did-open.go +++ /dev/null @@ -1,25 +0,0 @@ -package openssh - -import ( - "config-lsp/common" - "os" - - "github.com/tliron/glsp" - protocol "github.com/tliron/glsp/protocol_3_16" -) - -func TextDocumentDidOpen(context *glsp.Context, params *protocol.DidOpenTextDocumentParams) error { - readBytes, err := os.ReadFile(params.TextDocument.URI[len("file://"):]) - - if err != nil { - return err - } - - diagnostics := DiagnoseParser(context, params.TextDocument.URI, string(readBytes)) - - if len(diagnostics) > 0 { - common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) - } - - return nil -} diff --git a/handlers/openssh/utils.go b/handlers/openssh/utils.go deleted file mode 100644 index 9ef0d5f..0000000 --- a/handlers/openssh/utils.go +++ /dev/null @@ -1,5 +0,0 @@ -package openssh - -import "regexp" - -var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) diff --git a/common-documentation/linux-charsets.go b/server/common-documentation/linux-charsets.go similarity index 100% rename from common-documentation/linux-charsets.go rename to server/common-documentation/linux-charsets.go diff --git a/common-documentation/mnt-adfs.go b/server/common-documentation/mnt-adfs.go similarity index 97% rename from common-documentation/mnt-adfs.go rename to server/common-documentation/mnt-adfs.go index cccb4b2..7ce850e 100644 --- a/common-documentation/mnt-adfs.go +++ b/server/common-documentation/mnt-adfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var AdfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var AdfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "Set the owner of the files in the filesystem (default: uid=0).", diff --git a/common-documentation/mnt-affs.go b/server/common-documentation/mnt-affs.go similarity index 99% rename from common-documentation/mnt-affs.go rename to server/common-documentation/mnt-affs.go index 1a0f6e6..398b879 100644 --- a/common-documentation/mnt-affs.go +++ b/server/common-documentation/mnt-affs.go @@ -4,7 +4,7 @@ import docvalues "config-lsp/doc-values" var prefixMaxLength = uint32(30) -var AffsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var AffsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "Set the owner and group of the root of the filesystem (default: uid=gid=0, but with option uid or gid without specified value, the UID and GID of the current process are taken).", diff --git a/common-documentation/mnt-btrfs.go b/server/common-documentation/mnt-btrfs.go similarity index 99% rename from common-documentation/mnt-btrfs.go rename to server/common-documentation/mnt-btrfs.go index 664f946..46a7fbf 100644 --- a/common-documentation/mnt-btrfs.go +++ b/server/common-documentation/mnt-btrfs.go @@ -4,7 +4,7 @@ import docvalues "config-lsp/doc-values" var maxInlineMin = 2048 -var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "check_int_print_mask", "These debugging options control the behavior of the integrity checking module (the BTRFS_FS_CHECK_INTEGRITY config option required). The main goal is to verify that all blocks from a given transaction period are properly linked.", @@ -71,7 +71,7 @@ var BtrfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ "max_inline", "Specify the maximum amount of space, that can be inlined in a metadata b-tree leaf. The value is specified in bytes, optionally with a K suffix (case insensitive). In practice, this value is limited by the filesystem block size (named sectorsize at mkfs time), and memory page size of the system. In case of sectorsize limit, there's some space unavailable due to leaf headers. For example, a 4Ki", ): docvalues.OrValue{ - Values: []docvalues.Value{ + Values: []docvalues.DeprecatedValue{ docvalues.EnumValue{ EnforceValues: true, Values: []docvalues.EnumString{ diff --git a/common-documentation/mnt-debugfs.go b/server/common-documentation/mnt-debugfs.go similarity index 95% rename from common-documentation/mnt-debugfs.go rename to server/common-documentation/mnt-debugfs.go index 8d5ae63..d9f121f 100644 --- a/common-documentation/mnt-debugfs.go +++ b/server/common-documentation/mnt-debugfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var DebugfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var DebugfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "Set the owner of the mountpoint.", diff --git a/common-documentation/mnt-devpts.go b/server/common-documentation/mnt-devpts.go similarity index 99% rename from common-documentation/mnt-devpts.go rename to server/common-documentation/mnt-devpts.go index e2484b5..27eeaf9 100644 --- a/common-documentation/mnt-devpts.go +++ b/server/common-documentation/mnt-devpts.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var DevptsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var DevptsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "This sets the owner or the group of newly created pseudo terminals to the specified values. When nothing is specified, they will be set to the UID and GID of the creating process. For example, if there is a tty group with GID 5, then gid=5 will cause newly created pseudo terminals to belong to the tty group.", diff --git a/common-documentation/mnt-ext2.go b/server/common-documentation/mnt-ext2.go similarity index 99% rename from common-documentation/mnt-ext2.go rename to server/common-documentation/mnt-ext2.go index 7745c63..fa44c76 100644 --- a/common-documentation/mnt-ext2.go +++ b/server/common-documentation/mnt-ext2.go @@ -3,7 +3,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var Ext2DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var Ext2DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "none", "No checking is done at mount time. This is the default. This is fast. It is wise to invoke e2fsck(8) every now and then, e.g. at boot time. The non-default behavior is unsupported (check=normal and check=strict options have been removed). Note that these mount options don't have to be supported if ext4 kernel driver is used for ext2 and ext3 file systems.", diff --git a/common-documentation/mnt-ext3.go b/server/common-documentation/mnt-ext3.go similarity index 99% rename from common-documentation/mnt-ext3.go rename to server/common-documentation/mnt-ext3.go index 955f36a..167d64b 100644 --- a/common-documentation/mnt-ext3.go +++ b/server/common-documentation/mnt-ext3.go @@ -5,7 +5,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var Ext3DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var Ext3DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "journal_dev", "When the external journal device's major/minor numbers have changed, these options allow the user to specify the new journal location. The journal device is identified either through its new major/minor numbers encoded in devnum, or via a path to the device.", diff --git a/common-documentation/mnt-ext4.go b/server/common-documentation/mnt-ext4.go similarity index 99% rename from common-documentation/mnt-ext4.go rename to server/common-documentation/mnt-ext4.go index 6990d55..6f9883a 100644 --- a/common-documentation/mnt-ext4.go +++ b/server/common-documentation/mnt-ext4.go @@ -5,7 +5,7 @@ import docvalues "config-lsp/doc-values" var zero = 0 var maxJournalIOPrio = 7 -var Ext4DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var Ext4DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "inode_readahead_blks", "This tuning parameter controls the maximum number of inode table blocks that ext4's inode table readahead algorithm will pre-read into the buffer cache. The value must be a power of 2. The default value is 32 blocks.", diff --git a/common-documentation/mnt-fat.go b/server/common-documentation/mnt-fat.go similarity index 99% rename from common-documentation/mnt-fat.go rename to server/common-documentation/mnt-fat.go index 4c1e587..432d4ea 100644 --- a/common-documentation/mnt-fat.go +++ b/server/common-documentation/mnt-fat.go @@ -4,7 +4,7 @@ import ( docvalues "config-lsp/doc-values" ) -var FatDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var FatDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "blocksize", "Set blocksize (default 512). This option is obsolete.", diff --git a/common-documentation/mnt-hfs.go b/server/common-documentation/mnt-hfs.go similarity index 98% rename from common-documentation/mnt-hfs.go rename to server/common-documentation/mnt-hfs.go index c3d77e5..99f5935 100644 --- a/common-documentation/mnt-hfs.go +++ b/server/common-documentation/mnt-hfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var HfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var HfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "creator", "Set the creator/type values as shown by the MacOS finder used for creating new files. Default values: '????'.", diff --git a/common-documentation/mnt-hpfs.go b/server/common-documentation/mnt-hpfs.go similarity index 98% rename from common-documentation/mnt-hpfs.go rename to server/common-documentation/mnt-hpfs.go index 0e94cac..9fac6c6 100644 --- a/common-documentation/mnt-hpfs.go +++ b/server/common-documentation/mnt-hpfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var HpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var HpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "Set the owner and group of all files. (Default: the UID and GID of the current process.)", diff --git a/common-documentation/mnt-iso9660.go b/server/common-documentation/mnt-iso9660.go similarity index 99% rename from common-documentation/mnt-iso9660.go rename to server/common-documentation/mnt-iso9660.go index 4aa71cf..233ec98 100644 --- a/common-documentation/mnt-iso9660.go +++ b/server/common-documentation/mnt-iso9660.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var Iso9660DocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var Iso9660DocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "check", "With check=relaxed, a filename is first converted to lower case before doing the lookup. This is probably only meaningful together with norock and map=normal. (Default: check=strict.)", diff --git a/common-documentation/mnt-jfs.go b/server/common-documentation/mnt-jfs.go similarity index 99% rename from common-documentation/mnt-jfs.go rename to server/common-documentation/mnt-jfs.go index 25bf429..f041932 100644 --- a/common-documentation/mnt-jfs.go +++ b/server/common-documentation/mnt-jfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var JfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var JfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "iocharset", "Character set to use for converting from Unicode to ASCII. The default is to do no conversion. Use iocharset=utf8 for UTF8 translations. This requires CONFIG_NLS_UTF8 to be set in the kernel .config file.", diff --git a/common-documentation/mnt-msdos.go b/server/common-documentation/mnt-msdos.go similarity index 100% rename from common-documentation/mnt-msdos.go rename to server/common-documentation/mnt-msdos.go diff --git a/common-documentation/mnt-ncpfs.go b/server/common-documentation/mnt-ncpfs.go similarity index 88% rename from common-documentation/mnt-ncpfs.go rename to server/common-documentation/mnt-ncpfs.go index 193d06c..4a1d66d 100644 --- a/common-documentation/mnt-ncpfs.go +++ b/server/common-documentation/mnt-ncpfs.go @@ -2,6 +2,6 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var NcpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{} +var NcpfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{} var NcpfsDocumentationEnums = []docvalues.EnumString{} diff --git a/common-documentation/mnt-ntfs.go b/server/common-documentation/mnt-ntfs.go similarity index 99% rename from common-documentation/mnt-ntfs.go rename to server/common-documentation/mnt-ntfs.go index b1ae89b..ad2ee6a 100644 --- a/common-documentation/mnt-ntfs.go +++ b/server/common-documentation/mnt-ntfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var NtfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var NtfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "iocharset", "Character set to use when returning file names. Unlike VFAT, NTFS suppresses names that contain nonconvertible characters. Deprecated.", diff --git a/common-documentation/mnt-overlay.go b/server/common-documentation/mnt-overlay.go similarity index 99% rename from common-documentation/mnt-overlay.go rename to server/common-documentation/mnt-overlay.go index c20b04b..1e50203 100644 --- a/common-documentation/mnt-overlay.go +++ b/server/common-documentation/mnt-overlay.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var OverlayDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var OverlayDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "lowerdir", "Any filesystem, does not need to be on a writable filesystem.", diff --git a/common-documentation/mnt-reiserfs.go b/server/common-documentation/mnt-reiserfs.go similarity index 99% rename from common-documentation/mnt-reiserfs.go rename to server/common-documentation/mnt-reiserfs.go index 9f20210..d7ad9c6 100644 --- a/common-documentation/mnt-reiserfs.go +++ b/server/common-documentation/mnt-reiserfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var ReiserfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var ReiserfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "hash", "Choose which hash function reiserfs will use to find files within directories.", diff --git a/common-documentation/mnt-ubifs.go b/server/common-documentation/mnt-ubifs.go similarity index 98% rename from common-documentation/mnt-ubifs.go rename to server/common-documentation/mnt-ubifs.go index f755663..cfc6672 100644 --- a/common-documentation/mnt-ubifs.go +++ b/server/common-documentation/mnt-ubifs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var UbifsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var UbifsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "compr", "Select the default compressor which is used when new files are written. It is still possible to read compressed files if mounted with the none option.", diff --git a/common-documentation/mnt-udf.go b/server/common-documentation/mnt-udf.go similarity index 99% rename from common-documentation/mnt-udf.go rename to server/common-documentation/mnt-udf.go index 973f189..fd79db2 100644 --- a/common-documentation/mnt-udf.go +++ b/server/common-documentation/mnt-udf.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var UdfDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var UdfDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "uid", "Make all files in the filesystem belong to the given user. uid=forget can be specified independently of (or usually in addition to) uid= and results in UDF not storing uids to the media. In fact the recorded uid is the 32-bit overflow uid -1 as defined by the UDF standard. The value is given as either which is a valid user name or the corresponding decimal user id, or the special string 'forget'.", diff --git a/common-documentation/mnt-ufs.go b/server/common-documentation/mnt-ufs.go similarity index 99% rename from common-documentation/mnt-ufs.go rename to server/common-documentation/mnt-ufs.go index 44545bb..b24b0ad 100644 --- a/common-documentation/mnt-ufs.go +++ b/server/common-documentation/mnt-ufs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var UfsDocumentationAssignable = map[docvalues.EnumString]docvalues.Value{ +var UfsDocumentationAssignable = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "ufstype", "UFS is a filesystem widely used in different operating systems. The problem are differences among implementations. Features of some implementations are undocumented, so its hard to recognize the type of ufs automatically. That’s why the user must specify the type of ufs by mount option.", diff --git a/common-documentation/mnt-umsdos.go b/server/common-documentation/mnt-umsdos.go similarity index 93% rename from common-documentation/mnt-umsdos.go rename to server/common-documentation/mnt-umsdos.go index 2322d95..c533bd4 100644 --- a/common-documentation/mnt-umsdos.go +++ b/server/common-documentation/mnt-umsdos.go @@ -5,7 +5,7 @@ import ( "config-lsp/utils" ) -var UmsdosDocumentationAssignable = utils.FilterMap(MsdosDocumentationAssignable, func(key docvalues.EnumString, value docvalues.Value) bool { +var UmsdosDocumentationAssignable = utils.FilterMap(MsdosDocumentationAssignable, func(key docvalues.EnumString, value docvalues.DeprecatedValue) bool { // `dotsOK` is explicitly not supported if key.InsertText == "dotsOK" { return false diff --git a/common-documentation/mnt-usbfs.go b/server/common-documentation/mnt-usbfs.go similarity index 98% rename from common-documentation/mnt-usbfs.go rename to server/common-documentation/mnt-usbfs.go index a1ab6b4..ddcb4ec 100644 --- a/common-documentation/mnt-usbfs.go +++ b/server/common-documentation/mnt-usbfs.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var UsbfsDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.Value{ +var UsbfsDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "devuid", "Set the owner of the device files in the usbfs filesystem (default: uid=gid=0)", diff --git a/common-documentation/mnt-vfat.go b/server/common-documentation/mnt-vfat.go similarity index 99% rename from common-documentation/mnt-vfat.go rename to server/common-documentation/mnt-vfat.go index aed5336..6c4563d 100644 --- a/common-documentation/mnt-vfat.go +++ b/server/common-documentation/mnt-vfat.go @@ -2,7 +2,7 @@ package commondocumentation import docvalues "config-lsp/doc-values" -var VfatDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.Value{ +var VfatDocumentationAssignable = docvalues.MergeKeyEnumAssignmentMaps(FatDocumentationAssignable, map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "shortname", "Defines the behavior for creation and display of filenames which fit into 8.3 characters. If a long name for a file exists, it will always be the preferred one for display", diff --git a/common-documentation/rfc-5322.go b/server/common-documentation/rfc-5322.go similarity index 100% rename from common-documentation/rfc-5322.go rename to server/common-documentation/rfc-5322.go diff --git a/common/PARSER.md b/server/common/PARSER.md similarity index 100% rename from common/PARSER.md rename to server/common/PARSER.md diff --git a/common/diagnostics.go b/server/common/diagnostics.go similarity index 100% rename from common/diagnostics.go rename to server/common/diagnostics.go diff --git a/common/errors.go b/server/common/errors.go similarity index 73% rename from common/errors.go rename to server/common/errors.go index 57fc0b9..bccacea 100644 --- a/common/errors.go +++ b/server/common/errors.go @@ -1,6 +1,8 @@ package common import ( + "config-lsp/utils" + protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -30,3 +32,12 @@ type SyntaxError struct { func (s SyntaxError) Error() string { return s.Message } + +func ErrsToDiagnostics(errs []LSPError) []protocol.Diagnostic { + return utils.Map( + errs, + func(err LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) +} diff --git a/common/fetchers.go b/server/common/fetchers.go similarity index 100% rename from common/fetchers.go rename to server/common/fetchers.go diff --git a/server/common/formatting/formatting.go b/server/common/formatting/formatting.go new file mode 100644 index 0000000..65ad395 --- /dev/null +++ b/server/common/formatting/formatting.go @@ -0,0 +1,119 @@ +package formatting + +import ( + "fmt" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var DefaultFormattingOptions = protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, +} + +type FormatTemplate string + +func (f FormatTemplate) Format( + options protocol.FormattingOptions, + a ...any, +) string { + trimTrailingSpace := true + + if shouldTrim, found := options["trimTrailingWhitespace"]; found { + trimTrailingSpace = shouldTrim.(bool) + } + + value := "" + value = fmt.Sprintf( + string( + f.replace("/t", getTab(options)), + ), + a..., + ) + + if trimTrailingSpace { + value = strings.TrimRight(value, " ") + value = strings.TrimRight(value, "\t") + } + + value = surroundWithQuotes(value) + + return value +} + +func (f FormatTemplate) replace(format string, replacement string) FormatTemplate { + value := string(f) + currentIndex := 0 + + for { + position := strings.Index(value[currentIndex:], format) + + if position == -1 { + break + } + + position = position + currentIndex + currentIndex = position + + if position == 0 || value[position-1] != '\\' { + value = value[:position] + replacement + value[position+len(format):] + } + } + + return FormatTemplate(value) +} + +func surroundWithQuotes(s string) string { + value := s + currentIndex := 0 + + for { + startPosition := strings.Index(value[currentIndex:], "/!'") + + if startPosition == -1 { + break + } + + startPosition = startPosition + currentIndex + 3 + currentIndex = startPosition + + endPosition := strings.Index(value[startPosition:], "/!'") + + if endPosition == -1 { + break + } + + endPosition = endPosition + startPosition + currentIndex = endPosition + + innerValue := value[startPosition:endPosition] + + if innerValue[0] == '"' && innerValue[len(innerValue)-1] == '"' && (len(innerValue) >= 2 || innerValue[len(innerValue)-2] != '\\') { + // Already surrounded + value = value[:startPosition-3] + innerValue + value[endPosition+3:] + } else if strings.Contains(innerValue, " ") { + value = value[:startPosition-3] + "\"" + innerValue + "\"" + value[endPosition+3:] + } else { + value = value[:startPosition-3] + innerValue + value[endPosition+3:] + } + + if endPosition+3 >= len(value) { + break + } + } + + return value +} + +func getTab(options protocol.FormattingOptions) string { + tabSize := options["tabSize"].(float64) + insertSpace := options["insertSpaces"].(bool) + + if insertSpace { + return strings.Repeat(" ", int(tabSize)) + } else { + return "\t" + } +} diff --git a/server/common/formatting/formatting_test.go b/server/common/formatting/formatting_test.go new file mode 100644 index 0000000..7ceba9a --- /dev/null +++ b/server/common/formatting/formatting_test.go @@ -0,0 +1,137 @@ +package formatting + +import ( + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleTabExampleWithTabOptions( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := "PermitRootLogin\tyes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleTabExampleWithSpaceOptions( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": true, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := "PermitRootLogin yes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleExampleWhiteSpaceAtEndShouldTrim( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "yes ") + expected := "PermitRootLogin\tyes" + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSimpleExampleWhiteSpaceAtEndShouldNOTTrim( + t *testing.T, +) { + template := FormatTemplate("%s/t%s") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": false, + } + + result := template.Format(options, "PermitRootLogin", "yes ") + expected := "PermitRootLogin\tyes " + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSurroundWithQuotesExample( + t *testing.T, +) { + template := FormatTemplate("%s /!'%s/!'") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "this is okay") + expected := `PermitRootLogin "this is okay"` + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} +func TestSurroundWithQuotesButNoSpaceExample( + t *testing.T, +) { + template := FormatTemplate("%s /!'%s/!'") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", "yes") + expected := `PermitRootLogin yes` + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} + +func TestSurroundWithQuotesButAlreadySurrounded( + t *testing.T, +) { + template := FormatTemplate("%s /!'%s/!'") + + options := protocol.FormattingOptions{ + "tabSize": float64(4), + "insertSpaces": false, + "trimTrailingWhitespace": true, + } + + result := template.Format(options, "PermitRootLogin", `"Hello World"`) + expected := `PermitRootLogin "Hello World"` + + if result != expected { + t.Errorf("Expected %q but got %q", expected, result) + } +} diff --git a/server/common/location.go b/server/common/location.go new file mode 100644 index 0000000..fc62ca5 --- /dev/null +++ b/server/common/location.go @@ -0,0 +1,216 @@ +package common + +import ( + "fmt" + + "github.com/antlr4-go/antlr/v4" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type Location struct { + Line uint32 + Character uint32 +} + +func (l Location) GetRelativeIndexPosition(i IndexPosition) IndexPosition { + return i - IndexPosition(l.Character) +} + +// LocationRange: Represents a range of characters in a document +// Locations are zero-based, start-inclusive and end-exclusive +// This approach is preferred over using an index-based range, because +// it allows to check very easily for cursor positions, as well as for +// index-based ranges. +type LocationRange struct { + Start Location + End Location +} + +func (l LocationRange) ContainsPosition(p Position) bool { + return l.IsPositionAfterStart(p) && l.IsPositionBeforeEnd(p) +} + +// Check if the given position is after the start of the range +// It's like: Position >= Start +// This checks inclusively +func (l LocationRange) IsPositionAfterStart(p Position) bool { + return p.getValue() >= l.Start.Character +} + +func (l LocationRange) IsPositionBeforeStart(p Position) bool { + return p.getValue() < l.Start.Character +} + +// Check if the given position is before the end of the range +// It's like: Position <= End +// This checks inclusively +func (l LocationRange) IsPositionBeforeEnd(p Position) bool { + switch p.(type) { + case CursorPosition: + return p.getValue() <= l.End.Character + case IndexPosition: + return p.getValue() < l.End.Character + } + + return false +} + +func (l LocationRange) IsPositionAfterEnd(p Position) bool { + switch p.(type) { + case CursorPosition: + return p.getValue() > l.End.Character + case IndexPosition: + return p.getValue() >= l.End.Character + } + + return false +} + +func (l LocationRange) ShiftHorizontal(offset uint32) LocationRange { + return LocationRange{ + Start: Location{ + Line: l.Start.Line, + Character: l.Start.Character + offset, + }, + End: Location{ + Line: l.End.Line, + Character: l.End.Character + offset, + }, + } +} + +func (l LocationRange) String() string { + if l.Start.Line == l.End.Line { + return fmt.Sprintf("%d:%d-%d", l.Start.Line, l.Start.Character, l.End.Character) + } + + return fmt.Sprintf("%d:%d-%d:%d", l.Start.Line, l.Start.Character, l.End.Line, l.End.Character) +} + +var GlobalLocationRange = LocationRange{ + Start: Location{ + Line: 0, + Character: 0, + }, + End: Location{ + Line: 0, + Character: 0, + }, +} + +func (l LocationRange) ToLSPRange() protocol.Range { + return protocol.Range{ + Start: protocol.Position{ + Line: l.Start.Line, + Character: l.Start.Character, + }, + End: protocol.Position{ + Line: l.End.Line, + Character: l.End.Character, + }, + } +} + +func (l *LocationRange) ChangeBothLines(newLine uint32) { + l.Start.Line = newLine + l.End.Line = newLine +} + +func (l LocationRange) ContainsCursorByCharacter(character uint32) bool { + return character >= l.Start.Character && character <= l.End.Character +} + +func CreateFullLineRange(line uint32) LocationRange { + return LocationRange{ + Start: Location{ + Line: line, + Character: 0, + }, + End: Location{ + Line: line, + Character: 999999, + }, + } +} + +func CreateSingleCharRange(line uint32, character uint32) LocationRange { + return LocationRange{ + Start: Location{ + Line: line, + Character: character, + }, + End: Location{ + Line: line, + Character: character, + }, + } +} + +func CharacterRangeFromCtx( + ctx antlr.BaseParserRuleContext, +) LocationRange { + line := uint32(ctx.GetStart().GetLine()) + start := uint32(ctx.GetStart().GetStart()) + end := uint32(ctx.GetStop().GetStop()) + + return LocationRange{ + Start: Location{ + Line: line, + Character: start, + }, + End: Location{ + Line: line, + Character: end + 1, + }, + } +} + +type Position interface { + getValue() uint32 +} + +// Use this type if you want to use a cursor based position +// A cursor based position is a position that represents a cursor +// Given the example: +// "PermitRootLogin yes" +// Taking a look at the first character "P" - the index is 0. +// However, the cursor can either be at: +// +// "|P" - 0 or +// "P|" - 1 +// +// This is used for example for textDocument/completion or textDocument/signature +type CursorPosition uint32 + +func (c CursorPosition) getValue() uint32 { + return uint32(c) +} + +func (c CursorPosition) shiftHorizontal(offset uint32) CursorPosition { + return CursorPosition(uint32(c) + offset) +} + +func LSPCharacterAsCursorPosition(character uint32) CursorPosition { + return CursorPosition(character) +} + +func (c CursorPosition) IsBeforeIndexPosition(i IndexPosition) bool { + // |H[e]llo + return uint32(c) < uint32(i) +} + +func (c CursorPosition) IsAfterIndexPosition(i IndexPosition) bool { + // H[e]|llo + return uint32(c) > uint32(i)+1 +} + +// Use this type if you want to use an index based position +type IndexPosition uint32 + +func (i IndexPosition) getValue() uint32 { + return uint32(i) +} + +func LSPCharacterAsIndexPosition(character uint32) IndexPosition { + return IndexPosition(character) +} diff --git a/server/common/location_test.go b/server/common/location_test.go new file mode 100644 index 0000000..823b6aa --- /dev/null +++ b/server/common/location_test.go @@ -0,0 +1,137 @@ +package common + +import ( + "testing" +) + +func TestCursorPosition( + t *testing.T, +) { + // Contains fictive range for the name "Test" in the code: + // func Test() {} + locationRange := LocationRange{ + Start: Location{ + Line: 0, + Character: 5, + }, + End: Location{ + Line: 0, + Character: 9, + }, + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(5)) == true) { + t.Errorf("Expected 5 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(6)) == true) { + t.Errorf("Expected 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(9)) == true) { + t.Errorf("Expected 9 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(10)) == false) { + t.Errorf("Expected 10 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsCursorPosition(4)) == false) { + t.Errorf("Expected 4 to not be in range, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(0)) == true) { + t.Errorf("Expected 0 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(4)) == true) { + t.Errorf("Expected 5 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(5)) == false) { + t.Errorf("Expected 5 to not be before start, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsCursorPosition(10)) == false) { + t.Errorf("Expected 10 to not be before start, but it was") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(10)) == true) { + t.Errorf("Expected 10 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(11)) == true) { + t.Errorf("Expected 11 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(9)) == false) { + t.Errorf("Expected 9 to not be after end, but it was") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsCursorPosition(5)) == false) { + t.Errorf("Expected 5 to not be after end, but it was") + } +} + +func TestIndexPosition(t *testing.T) { + // Contains fictive range for the name "Test" in the code: + // func Test() {} + locationRange := LocationRange{ + Start: Location{ + Line: 0, + Character: 5, + }, + End: Location{ + Line: 0, + Character: 9, + }, + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(5)) == true) { + t.Errorf("Expected index position 5 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(6)) == true) { + t.Errorf("Expected index position 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(8)) == true) { + t.Errorf("Expected index position 6 to be in range, but it wasn't") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(9)) == false) { + t.Errorf("Expected index position 9 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(10)) == false) { + t.Errorf("Expected index position 10 to not be in range, but it was") + } + + if !(locationRange.ContainsPosition(LSPCharacterAsIndexPosition(4)) == false) { + t.Errorf("Expected index position 4 to not be in range, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(4)) == true) { + t.Errorf("Expected index position 4 to be before start, but it wasn't") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(5)) == false) { + t.Errorf("Expected index position 5 to not be before start, but it was") + } + + if !(locationRange.IsPositionBeforeStart(LSPCharacterAsIndexPosition(10)) == false) { + t.Errorf("Expected index position 10 to not be before start, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(10)) == true) { + t.Errorf("Expected index position 10 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(9)) == true) { + t.Errorf("Expected index position 9 to be after end, but it wasn't") + } + + if !(locationRange.IsPositionAfterEnd(LSPCharacterAsIndexPosition(5)) == false) { + t.Errorf("Expected index position 5 to not be after end, but it was") + } +} diff --git a/server/common/lsp.go b/server/common/lsp.go new file mode 100644 index 0000000..42ec460 --- /dev/null +++ b/server/common/lsp.go @@ -0,0 +1,26 @@ +package common + +import protocol "github.com/tliron/glsp/protocol_3_16" + +// LSPCharacterAsCursorPosition: +// @deprecated +func CursorToCharacterIndex(cursor uint32) uint32 { + return max(1, cursor) - 1 +} + +func DeprecatedImprovedCursorToIndex( + c CursorPosition, + line string, + offset uint32, +) uint32 { + if len(line) == 0 { + return 0 + } + + return min(uint32(len(line)-1), uint32(c)-offset+1) +} + +var SeverityError = protocol.DiagnosticSeverityError +var SeverityWarning = protocol.DiagnosticSeverityWarning +var SeverityInformation = protocol.DiagnosticSeverityInformation +var SeverityHint = protocol.DiagnosticSeverityHint diff --git a/common/parser.go b/server/common/parser.go similarity index 100% rename from common/parser.go rename to server/common/parser.go diff --git a/server/common/parser/strings.go b/server/common/parser/strings.go new file mode 100644 index 0000000..931983f --- /dev/null +++ b/server/common/parser/strings.go @@ -0,0 +1,126 @@ +package parser + +type ParseFeatures struct { + ParseDoubleQuotes bool + ParseEscapedCharacters bool +} + +var FullFeatures = ParseFeatures{ + ParseDoubleQuotes: true, + ParseEscapedCharacters: true, +} + +type ParsedString struct { + Raw string + Value string +} + +func ParseRawString( + raw string, + features ParseFeatures, +) ParsedString { + value := raw + + // Parse double quotes + if features.ParseDoubleQuotes { + value = ParseDoubleQuotes(value) + } + + // Parse escaped characters + if features.ParseEscapedCharacters { + value = ParseEscapedCharacters(value) + } + + return ParsedString{ + Raw: raw, + Value: value, + } +} + +func ParseDoubleQuotes( + raw string, +) string { + value := raw + currentIndex := 0 + + for { + start, found := findNextDoubleQuote(value, currentIndex) + + if found && start < (len(value)-1) { + currentIndex = max(0, start-1) + end, found := findNextDoubleQuote(value, start+1) + + if found { + insideContent := value[start+1 : end] + value = modifyString(value, start, end+1, insideContent) + + continue + } + } + + break + } + + return value +} + +func ParseEscapedCharacters( + raw string, +) string { + value := raw + currentIndex := 0 + + for { + position, found := findNextEscapedCharacter(value, currentIndex) + + if found { + currentIndex = max(0, position-1) + escapedCharacter := value[position+1] + value = modifyString(value, position, position+2, string(escapedCharacter)) + } else { + break + } + } + + return value +} + +func modifyString( + input string, + start int, + end int, + newValue string, +) string { + return input[:start] + newValue + input[end:] +} + +// Find the next non-escaped double quote in [raw] starting from [startIndex] +// When no double quote is found, return -1 +// Return as the second argument whether a double quote was found +func findNextDoubleQuote( + raw string, + startIndex int, +) (int, bool) { + for index := startIndex; index < len(raw); index++ { + if raw[index] == '"' { + if index == 0 || raw[index-1] != '\\' { + return index, true + } + } + } + + return -1, false +} + +func findNextEscapedCharacter( + raw string, + startIndex int, +) (int, bool) { + for index := startIndex; index < len(raw); index++ { + if raw[index] == '\\' && index < len(raw)-1 { + return index, true + } + } + + return -1, false +} diff --git a/server/common/parser/strings_test.go b/server/common/parser/strings_test.go new file mode 100644 index 0000000..e82352f --- /dev/null +++ b/server/common/parser/strings_test.go @@ -0,0 +1,167 @@ +package parser + +import ( + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestStringsSingleWortQuotedFullFeatures( + t *testing.T, +) { + input := `hello "world"` + expected := ParsedString{ + Raw: input, + Value: "hello world", + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsFullyQuotedFullFeatures( + t *testing.T, +) { + input := `"hello world"` + expected := ParsedString{ + Raw: input, + Value: "hello world", + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsMultipleQuotesFullFeatures( + t *testing.T, +) { + input := `hello "world goodbye"` + expected := ParsedString{ + Raw: input, + Value: "hello world goodbye", + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsSimpleEscapedFullFeatures( + t *testing.T, +) { + input := `hello \"world` + expected := ParsedString{ + Raw: input, + Value: `hello "world`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsEscapedQuotesFullFeatures( + t *testing.T, +) { + input := `hello \"world\"` + expected := ParsedString{ + Raw: input, + Value: `hello "world"`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsQuotesAndEscapedFullFeatures( + t *testing.T, +) { + input := `hello "world how\" are you"` + expected := ParsedString{ + Raw: input, + Value: `hello world how" are you`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotesFullFeatures( + t *testing.T, +) { + input := `hello "world` + expected := ParsedString{ + Raw: input, + Value: `hello "world`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuoteEscapedFullFeatures( + t *testing.T, +) { + input := `hello "world\"` + expected := ParsedString{ + Raw: input, + Value: `hello "world"`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotes2FullFeatures( + t *testing.T, +) { + input := `hello "world how" "are you` + expected := ParsedString{ + Raw: input, + Value: `hello world how "are you`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} + +func TestStringsIncompleteQuotes3FullFeatures( + t *testing.T, +) { + input := `hello "world how are you` + expected := ParsedString{ + Raw: input, + Value: `hello "world how are you`, + } + + actual := ParseRawString(input, FullFeatures) + + if !(cmp.Equal(expected, actual)) { + t.Errorf("Expected %v, got %v", expected, actual) + } +} diff --git a/server/common/ssh/query.go b/server/common/ssh/query.go new file mode 100644 index 0000000..8e4cf61 --- /dev/null +++ b/server/common/ssh/query.go @@ -0,0 +1,44 @@ +package ssh + +import ( + "config-lsp/doc-values" + "config-lsp/utils" + "os/exec" + "strings" +) + +var _cachedQueries map[string][]docvalues.EnumString = make(map[string][]docvalues.EnumString) + +func queryValues(query string) ([]string, error) { + cmd := exec.Command("ssh", "-Q", query) + + output, err := cmd.Output() + + if err != nil { + return []string{}, err + } + + return strings.Split(string(output), "\n"), nil +} + +func QueryOpenSSHOptions( + query string, +) ([]docvalues.EnumString, error) { + var availableQueries []docvalues.EnumString + key := query + + if _cachedQueries[key] != nil && len(_cachedQueries[key]) > 0 { + return _cachedQueries[key], nil + } else { + availableRawQueries, err := queryValues(query) + availableQueries = utils.Map(availableRawQueries, docvalues.CreateEnumString) + + if err != nil { + return []docvalues.EnumString{}, err + } + + _cachedQueries[key] = availableQueries + } + + return availableQueries, nil +} diff --git a/doc-values/base-value.go b/server/doc-values/base-value.go similarity index 81% rename from doc-values/base-value.go rename to server/doc-values/base-value.go index 2a2d3d6..c5bba59 100644 --- a/doc-values/base-value.go +++ b/server/doc-values/base-value.go @@ -5,11 +5,11 @@ import ( protocol "github.com/tliron/glsp/protocol_3_16" ) -type Value interface { +type DeprecatedValue interface { GetTypeDescription() []string - CheckIsValid(value string) []*InvalidValue - FetchCompletions(line string, cursor uint32) []protocol.CompletionItem - FetchHoverInfo(line string, cursor uint32) []string + DeprecatedCheckIsValid(value string) []*InvalidValue + DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem + DeprecatedFetchHoverInfo(line string, cursor uint32) []string } type InvalidValue struct { @@ -31,7 +31,7 @@ func (v *InvalidValue) GetRange(line uint32, characterStart uint32) protocol.Ran }, End: protocol.Position{ Line: line, - Character: characterStart + v.End, + Character: characterStart + v.End + 1, }, } } diff --git a/doc-values/errors.go b/server/doc-values/errors.go similarity index 98% rename from doc-values/errors.go rename to server/doc-values/errors.go index c9a6d69..8c2bc37 100644 --- a/doc-values/errors.go +++ b/server/doc-values/errors.go @@ -68,7 +68,7 @@ func (e ValueError) GetPublishDiagnosticsParams() protocol.Diagnostic { } } func (e ValueError) Error() string { - return "Value error" + return "DeprecatedValue error" } type OptionAlreadyExistsError struct { diff --git a/doc-values/extra-values.go b/server/doc-values/extra-values.go similarity index 82% rename from doc-values/extra-values.go rename to server/doc-values/extra-values.go index dcf82d3..8daed43 100644 --- a/doc-values/extra-values.go +++ b/server/doc-values/extra-values.go @@ -6,11 +6,11 @@ import ( "regexp" ) -// UserValue returns a Value that fetches user names from /etc/passwd +// UserValue returns a DeprecatedValue that fetches user names from /etc/passwd // if `separatorForMultiple` is not empty, it will return an ArrayValue -func UserValue(separatorForMultiple string, enforceValues bool) Value { +func UserValue(separatorForMultiple string, enforceValues bool) DeprecatedValue { return CustomValue{ - FetchValue: func(context CustomValueContext) Value { + FetchValue: func(context CustomValueContext) DeprecatedValue { infos, err := common.FetchPasswdInfo() if err != nil { @@ -37,9 +37,9 @@ func UserValue(separatorForMultiple string, enforceValues bool) Value { } } -func GroupValue(separatorForMultiple string, enforceValues bool) Value { +func GroupValue(separatorForMultiple string, enforceValues bool) DeprecatedValue { return CustomValue{ - FetchValue: func(context CustomValueContext) Value { + FetchValue: func(context CustomValueContext) DeprecatedValue { infos, err := common.FetchGroupInfo() if err != nil { @@ -66,14 +66,14 @@ func GroupValue(separatorForMultiple string, enforceValues bool) Value { } } -func PositiveNumberValue() Value { +func PositiveNumberValue() DeprecatedValue { zero := 0 return NumberValue{ Min: &zero, } } -func MaskValue() Value { +func MaskValue() DeprecatedValue { min := 0 max := 777 return NumberValue{Min: &min, Max: &max} @@ -88,7 +88,7 @@ func SingleEnumValue(value string) EnumValue { } } -func DomainValue() Value { +func DomainValue() DeprecatedValue { return RegexValue{ Regex: *regexp.MustCompile(`^.+?\..+$`), } diff --git a/doc-values/utils.go b/server/doc-values/utils.go similarity index 83% rename from doc-values/utils.go rename to server/doc-values/utils.go index 8d5a403..2e3c719 100644 --- a/doc-values/utils.go +++ b/server/doc-values/utils.go @@ -20,9 +20,9 @@ func GenerateBase10Completions(prefix string) []protocol.CompletionItem { ) } -func MergeKeyEnumAssignmentMaps(maps ...map[EnumString]Value) map[EnumString]Value { +func MergeKeyEnumAssignmentMaps(maps ...map[EnumString]DeprecatedValue) map[EnumString]DeprecatedValue { existingEnums := make(map[string]interface{}) - result := make(map[EnumString]Value) + result := make(map[EnumString]DeprecatedValue) slices.Reverse(maps) diff --git a/doc-values/value-array.go b/server/doc-values/value-array.go similarity index 75% rename from doc-values/value-array.go rename to server/doc-values/value-array.go index 0f200d0..0bb9f48 100644 --- a/doc-values/value-array.go +++ b/server/doc-values/value-array.go @@ -35,7 +35,7 @@ var ExtractKeyDuplicatesExtractor = func(separator string) func(string) string { var DuplicatesAllowedExtractor func(string) string = nil type ArrayValue struct { - SubValue Value + SubValue DeprecatedValue Separator string // If this function is nil, no duplicate check is done. // (value) => Extracted value @@ -45,7 +45,7 @@ type ArrayValue struct { } func (v ArrayValue) GetTypeDescription() []string { - subValue := v.SubValue.(Value) + subValue := v.SubValue.(DeprecatedValue) return append( []string{fmt.Sprintf("An Array separated by '%s' of:", v.Separator)}, @@ -53,7 +53,7 @@ func (v ArrayValue) GetTypeDescription() []string { ) } -func (v ArrayValue) CheckIsValid(value string) []*InvalidValue { +func (v ArrayValue) DeprecatedCheckIsValid(value string) []*InvalidValue { errors := []*InvalidValue{} values := strings.Split(value, v.Separator) @@ -100,7 +100,7 @@ func (v ArrayValue) CheckIsValid(value string) []*InvalidValue { currentIndex := uint32(0) for _, subValue := range values { - newErrors := v.SubValue.CheckIsValid(subValue) + newErrors := v.SubValue.DeprecatedCheckIsValid(subValue) if len(newErrors) > 0 { ShiftInvalidValues(currentIndex, newErrors) @@ -119,24 +119,34 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32) return line, cursor } + MIN := uint32(0) + MAX := uint32(len(line) - 1) + var start uint32 var end uint32 + // hello,w[o]rld,and,more + // [h]ello,world + // hello,[w]orld + // hell[o],world + // hello,worl[d] + // hello,world[,] + // hello[,]world,how,are,you + relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - // defaults - min(len(line)-1, int(cursor)), + int(cursor), ) if found { - // +1 to skip the separator + // + 1 to skip the separator start = min( - min(uint32(len(line)), uint32(relativePosition+1)), - uint32(relativePosition+1), + MAX, + uint32(relativePosition)+1, ) } else { - start = 0 + start = MIN } relativePosition, found = utils.FindNextCharacter( @@ -146,26 +156,31 @@ func (v ArrayValue) getCurrentValue(line string, cursor uint32) (string, uint32) ) if found { - // -1 to skip the separator - end = min( - min(uint32(len(line)), uint32(relativePosition)), - cursor, + // - 1 to skip the separator + end = max( + MIN, + uint32(relativePosition)-1, ) } else { - end = uint32(len(line)) + end = MAX } - return line[start:end], cursor - start + if cursor > end { + // The user is typing a new (yet empty) value + return "", 0 + } + + return line[start : end+1], cursor - start } -func (v ArrayValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v ArrayValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { value, cursor := v.getCurrentValue(line, cursor) - return v.SubValue.FetchCompletions(value, cursor) + return v.SubValue.DeprecatedFetchCompletions(value, cursor) } -func (v ArrayValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v ArrayValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { value, cursor := v.getCurrentValue(line, cursor) - return v.SubValue.FetchHoverInfo(value, cursor) + return v.SubValue.DeprecatedFetchHoverInfo(value, cursor) } diff --git a/server/doc-values/value-custom.go b/server/doc-values/value-custom.go new file mode 100644 index 0000000..0bb5802 --- /dev/null +++ b/server/doc-values/value-custom.go @@ -0,0 +1,37 @@ +package docvalues + +import ( + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type CustomValueContext interface { + GetIsContext() bool +} + +type EmptyValueContext struct{} + +func (EmptyValueContext) GetIsContext() bool { + return true +} + +var EmptyValueContextInstance = EmptyValueContext{} + +type CustomValue struct { + FetchValue func(context CustomValueContext) DeprecatedValue +} + +func (v CustomValue) GetTypeDescription() []string { + return v.FetchValue(EmptyValueContextInstance).GetTypeDescription() +} + +func (v CustomValue) DeprecatedCheckIsValid(value string) []*InvalidValue { + return v.FetchValue(EmptyValueContextInstance).DeprecatedCheckIsValid(value) +} + +func (v CustomValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + return v.FetchValue(EmptyValueContextInstance).DeprecatedFetchCompletions(line, cursor) +} + +func (v CustomValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { + return v.FetchValue(EmptyValueContextInstance).DeprecatedFetchHoverInfo(line, cursor) +} diff --git a/handlers/openssh/value-data-amount-value.go b/server/doc-values/value-data-amount-value.go similarity index 82% rename from handlers/openssh/value-data-amount-value.go rename to server/doc-values/value-data-amount-value.go index 4e90811..145315b 100644 --- a/handlers/openssh/value-data-amount-value.go +++ b/server/doc-values/value-data-amount-value.go @@ -1,7 +1,6 @@ -package openssh +package docvalues import ( - docvalues "config-lsp/doc-values" "fmt" "regexp" "strconv" @@ -23,9 +22,9 @@ func (v DataAmountValue) GetTypeDescription() []string { return []string{"Data amount"} } -func (v DataAmountValue) CheckIsValid(value string) []*docvalues.InvalidValue { +func (v DataAmountValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !dataAmountCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ + return []*InvalidValue{ { Err: InvalidDataAmountError{}, Start: 0, @@ -56,7 +55,7 @@ func calculateLineToKilobyte(value string, unit string) string { } } -func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v DataAmountValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { completions := make([]protocol.CompletionItem, 0) if line != "" && !dataAmountCheckPattern.MatchString(line) { @@ -85,13 +84,13 @@ func (v DataAmountValue) FetchCompletions(line string, cursor uint32) []protocol if line == "" || isJustDigitsPattern.MatchString(line) { completions = append( completions, - docvalues.GenerateBase10Completions(line)..., + GenerateBase10Completions(line)..., ) } return completions } -func (v DataAmountValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v DataAmountValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/server/doc-values/value-documentation.go b/server/doc-values/value-documentation.go new file mode 100644 index 0000000..6b085c4 --- /dev/null +++ b/server/doc-values/value-documentation.go @@ -0,0 +1,28 @@ +package docvalues + +import ( + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type DocumentationValue struct { + Documentation string + Value DeprecatedValue +} + +func (v DocumentationValue) GetTypeDescription() []string { + return v.Value.GetTypeDescription() +} + +func (v DocumentationValue) DeprecatedCheckIsValid(value string) []*InvalidValue { + return v.Value.DeprecatedCheckIsValid(value) +} + +func (v DocumentationValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + return v.Value.DeprecatedFetchCompletions(line, cursor) +} + +func (v DocumentationValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { + return strings.Split(v.Documentation, "\n") +} diff --git a/doc-values/value-enum.go b/server/doc-values/value-enum.go similarity index 91% rename from doc-values/value-enum.go rename to server/doc-values/value-enum.go index 9457008..875f5f5 100644 --- a/doc-values/value-enum.go +++ b/server/doc-values/value-enum.go @@ -78,7 +78,7 @@ func (v EnumValue) GetTypeDescription() []string { return lines } -func (v EnumValue) CheckIsValid(value string) []*InvalidValue { +func (v EnumValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !v.EnforceValues { return nil } @@ -101,7 +101,7 @@ func (v EnumValue) CheckIsValid(value string) []*InvalidValue { }, } } -func (v EnumValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v EnumValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { completions := make([]protocol.CompletionItem, len(v.Values)) for index, value := range v.Values { @@ -118,7 +118,7 @@ func (v EnumValue) FetchCompletions(line string, cursor uint32) []protocol.Compl return completions } -func (v EnumValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v EnumValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { for _, value := range v.Values { if value.InsertText == line { return []string{ diff --git a/doc-values/value-gid.go b/server/doc-values/value-gid.go similarity index 91% rename from doc-values/value-gid.go rename to server/doc-values/value-gid.go index 103592c..cb3d5ed 100644 --- a/doc-values/value-gid.go +++ b/server/doc-values/value-gid.go @@ -35,7 +35,7 @@ func (v GIDValue) GetTypeDescription() []string { return []string{"Group ID"} } -func (v GIDValue) CheckIsValid(value string) []*InvalidValue { +func (v GIDValue) DeprecatedCheckIsValid(value string) []*InvalidValue { uid, err := strconv.Atoi(value) if err != nil { @@ -90,7 +90,7 @@ var defaultGIDsExplanation = []EnumString{ }, } -func (v GIDValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v GIDValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { infos, err := common.FetchGroupInfo() if err != nil { @@ -128,7 +128,7 @@ func (v GIDValue) FetchCompletions(line string, cursor uint32) []protocol.Comple return completions } -func (v GIDValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v GIDValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { uid, err := strconv.Atoi(line) if err != nil { diff --git a/doc-values/value-ip-address.go b/server/doc-values/value-ip-address.go similarity index 94% rename from doc-values/value-ip-address.go rename to server/doc-values/value-ip-address.go index 8c2bca4..0f0daf4 100644 --- a/doc-values/value-ip-address.go +++ b/server/doc-values/value-ip-address.go @@ -66,7 +66,7 @@ func (v IPAddressValue) GetTypeDescription() []string { return []string{"An IP Address"} } -func (v IPAddressValue) CheckIsValid(value string) []*InvalidValue { +func (v IPAddressValue) DeprecatedCheckIsValid(value string) []*InvalidValue { var ip net.Prefix if v.AllowRange { @@ -151,7 +151,7 @@ func (v IPAddressValue) CheckIsValid(value string) []*InvalidValue { } } -func (v IPAddressValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v IPAddressValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { if v.AllowedIPs != nil && len(*v.AllowedIPs) != 0 { kind := protocol.CompletionItemKindValue @@ -184,7 +184,7 @@ func (v IPAddressValue) FetchCompletions(line string, cursor uint32) []protocol. return []protocol.CompletionItem{} } -func (v IPAddressValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v IPAddressValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { if v.AllowRange { ip, err := net.ParsePrefix(line) diff --git a/doc-values/value-key-enum-assignment.go b/server/doc-values/value-key-enum-assignment.go similarity index 84% rename from doc-values/value-key-enum-assignment.go rename to server/doc-values/value-key-enum-assignment.go index 2f27a60..b39127a 100644 --- a/doc-values/value-key-enum-assignment.go +++ b/server/doc-values/value-key-enum-assignment.go @@ -9,7 +9,7 @@ import ( ) type KeyEnumAssignmentValue struct { - Values map[EnumString]Value + Values map[EnumString]DeprecatedValue Separator string ValueIsOptional bool } @@ -21,7 +21,7 @@ func (v KeyEnumAssignmentValue) GetTypeDescription() []string { if len(valueDescription) == 1 { return []string{ - fmt.Sprintf("Key-Value pair in form of '<%s>%s<%s>'", firstKey.DescriptionText, v.Separator, valueDescription[0]), + fmt.Sprintf("Key-DeprecatedValue pair in form of '<%s>%s<%s>'", firstKey.DescriptionText, v.Separator, valueDescription[0]), } } } @@ -33,11 +33,11 @@ func (v KeyEnumAssignmentValue) GetTypeDescription() []string { } return append([]string{ - "Key-Value pair in form of 'key%svalue'", v.Separator, + "Key-DeprecatedValue pair in form of 'key%svalue'", v.Separator, }, result...) } -func (v KeyEnumAssignmentValue) getValue(findKey string) (*Value, bool) { +func (v KeyEnumAssignmentValue) getValue(findKey string) (*DeprecatedValue, bool) { for key, value := range v.Values { if key.InsertText == findKey { switch value.(type) { @@ -59,7 +59,7 @@ func (v KeyEnumAssignmentValue) getValue(findKey string) (*Value, bool) { return nil, false } -func (v KeyEnumAssignmentValue) CheckIsValid(value string) []*InvalidValue { +func (v KeyEnumAssignmentValue) DeprecatedCheckIsValid(value string) []*InvalidValue { parts := strings.Split(value, v.Separator) if len(parts) == 0 || parts[0] == "" { @@ -96,7 +96,7 @@ func (v KeyEnumAssignmentValue) CheckIsValid(value string) []*InvalidValue { } } - errors := (*checkValue).CheckIsValid(parts[1]) + errors := (*checkValue).DeprecatedCheckIsValid(parts[1]) if len(errors) > 0 { ShiftInvalidValues(uint32(len(parts[0])+len(v.Separator)), errors) @@ -147,7 +147,7 @@ func (v KeyEnumAssignmentValue) getValueAtCursor(line string, cursor uint32) (st relativePosition, found := utils.FindPreviousCharacter(line, v.Separator, int(cursor)) if found { - // Value found + // DeprecatedValue found selected := valueSelected return line[uint32(relativePosition+1):], &selected, cursor - uint32(relativePosition) } @@ -165,7 +165,7 @@ func (v KeyEnumAssignmentValue) getValueAtCursor(line string, cursor uint32) (st return line, &selected, cursor } -func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v KeyEnumAssignmentValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { if cursor == 0 { return v.FetchEnumCompletions() } @@ -173,7 +173,7 @@ func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []p relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - max(0, int(cursor-1)), + int(cursor), ) if found { @@ -188,14 +188,14 @@ func (v KeyEnumAssignmentValue) FetchCompletions(line string, cursor uint32) []p return v.FetchEnumCompletions() } - return (*keyValue).FetchCompletions(line, cursor) + return (*keyValue).DeprecatedFetchCompletions(line, cursor) } else { return v.FetchEnumCompletions() } } -func (v KeyEnumAssignmentValue) FetchHoverInfo(line string, cursor uint32) []string { - if len(v.CheckIsValid(line)) != 0 { +func (v KeyEnumAssignmentValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { + if len(v.DeprecatedCheckIsValid(line)) != 0 { return []string{} } @@ -228,7 +228,7 @@ func (v KeyEnumAssignmentValue) FetchHoverInfo(line string, cursor uint32) []str return []string{} } - info := (*checkValue).FetchHoverInfo(value, cursor) + info := (*checkValue).DeprecatedFetchHoverInfo(value, cursor) return append( []string{ diff --git a/doc-values/value-key-value-assignment.go b/server/doc-values/value-key-value-assignment.go similarity index 69% rename from doc-values/value-key-value-assignment.go rename to server/doc-values/value-key-value-assignment.go index ec37ca7..5a2efe7 100644 --- a/doc-values/value-key-value-assignment.go +++ b/server/doc-values/value-key-value-assignment.go @@ -23,9 +23,9 @@ func (KeyValueAssignmentContext) GetIsContext() bool { } type KeyValueAssignmentValue struct { - Key Value + Key DeprecatedValue // If this is a `CustomValue`, it will receive a `KeyValueAssignmentContext` - Value Value + Value DeprecatedValue ValueIsOptional bool Separator string } @@ -36,18 +36,18 @@ func (v KeyValueAssignmentValue) GetTypeDescription() []string { if len(keyDescription) == 1 && len(valueDescription) == 1 { return []string{ - fmt.Sprintf("Key-Value pair in form of '<%s>%s<%s>'", keyDescription[0], v.Separator, valueDescription[0]), + fmt.Sprintf("Key-DeprecatedValue pair in form of '<%s>%s<%s>'", keyDescription[0], v.Separator, valueDescription[0]), } } else { return []string{ - fmt.Sprintf("Key-Value pair in form of 'key%svalue'", v.Separator), + fmt.Sprintf("Key-DeprecatedValue pair in form of 'key%svalue'", v.Separator), fmt.Sprintf("#### Key\n%s", strings.Join(v.Key.GetTypeDescription(), "\n")), - fmt.Sprintf("#### Value:\n%s", strings.Join(v.Value.GetTypeDescription(), "\n")), + fmt.Sprintf("#### DeprecatedValue:\n%s", strings.Join(v.Value.GetTypeDescription(), "\n")), } } } -func (v KeyValueAssignmentValue) getValue(selectedKey string) Value { +func (v KeyValueAssignmentValue) getValue(selectedKey string) DeprecatedValue { switch v.Value.(type) { case CustomValue: { @@ -65,7 +65,7 @@ func (v KeyValueAssignmentValue) getValue(selectedKey string) Value { } } -func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue { +func (v KeyValueAssignmentValue) DeprecatedCheckIsValid(value string) []*InvalidValue { parts := strings.Split(value, v.Separator) if len(parts) == 0 || parts[0] == "" { @@ -73,7 +73,7 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue { return nil } - err := v.Key.CheckIsValid(parts[0]) + err := v.Key.DeprecatedCheckIsValid(parts[0]) if err != nil { return err @@ -93,7 +93,7 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue { } } - errors := v.getValue(parts[0]).CheckIsValid(parts[1]) + errors := v.getValue(parts[0]).DeprecatedCheckIsValid(parts[1]) if len(errors) > 0 { ShiftInvalidValues(uint32(len(parts[0])+len(v.Separator)), errors) @@ -103,15 +103,15 @@ func (v KeyValueAssignmentValue) CheckIsValid(value string) []*InvalidValue { return nil } -func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { - if cursor == 0 { - return v.Key.FetchCompletions(line, cursor) +func (v KeyValueAssignmentValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + if cursor == 0 || line == "" { + return v.Key.DeprecatedFetchCompletions(line, cursor) } relativePosition, found := utils.FindPreviousCharacter( line, v.Separator, - max(0, int(cursor-1)), + int(cursor), ) if found { @@ -119,9 +119,9 @@ func (v KeyValueAssignmentValue) FetchCompletions(line string, cursor uint32) [] line = line[uint32(relativePosition+len(v.Separator)):] cursor -= uint32(relativePosition) - return v.getValue(selectedKey).FetchCompletions(line, cursor) + return v.getValue(selectedKey).DeprecatedFetchCompletions(line, cursor) } else { - return v.Key.FetchCompletions(line, cursor) + return v.Key.DeprecatedFetchCompletions(line, cursor) } } @@ -129,7 +129,7 @@ func (v KeyValueAssignmentValue) getValueAtCursor(line string, cursor uint32) (s relativePosition, found := utils.FindPreviousCharacter(line, v.Separator, int(cursor)) if found { - // Value found + // DeprecatedValue found selected := valueSelected return line[:uint32(relativePosition)], &selected, cursor - uint32(relativePosition) } @@ -147,8 +147,8 @@ func (v KeyValueAssignmentValue) getValueAtCursor(line string, cursor uint32) (s return line, &selected, cursor } -func (v KeyValueAssignmentValue) FetchHoverInfo(line string, cursor uint32) []string { - if len(v.CheckIsValid(line)) != 0 { +func (v KeyValueAssignmentValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { + if len(v.DeprecatedCheckIsValid(line)) != 0 { return []string{} } @@ -160,12 +160,12 @@ func (v KeyValueAssignmentValue) FetchHoverInfo(line string, cursor uint32) []st if *selected == keySelected { // Get key documentation - return v.Key.FetchHoverInfo(value, cursor) + return v.Key.DeprecatedFetchHoverInfo(value, cursor) } else if *selected == valueSelected { // Get for value documentation key := strings.SplitN(line, v.Separator, 2)[0] - return v.getValue(key).FetchHoverInfo(value, cursor) + return v.getValue(key).DeprecatedFetchHoverInfo(value, cursor) } return []string{} diff --git a/doc-values/value-mask-mode.go b/server/doc-values/value-mask-mode.go similarity index 92% rename from doc-values/value-mask-mode.go rename to server/doc-values/value-mask-mode.go index 85de36a..308804d 100644 --- a/doc-values/value-mask-mode.go +++ b/server/doc-values/value-mask-mode.go @@ -29,7 +29,7 @@ func (v MaskModeValue) GetTypeDescription() []string { var maskModePattern = regexp.MustCompile("^[0-7]{4}$") -func (v MaskModeValue) CheckIsValid(value string) []*InvalidValue { +func (v MaskModeValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !maskModePattern.MatchString(value) { return []*InvalidValue{{ Err: MaskModeInvalidError{}, @@ -41,7 +41,7 @@ func (v MaskModeValue) CheckIsValid(value string) []*InvalidValue { return []*InvalidValue{} } -func (v MaskModeValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v MaskModeValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { kind := protocol.CompletionItemKindValue perm0644 := "0644" @@ -147,7 +147,7 @@ func getMaskRepresentation(digit uint8) string { return "" } -func (v MaskModeValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v MaskModeValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { if !maskModePattern.MatchString(line) { return []string{} } diff --git a/doc-values/value-number.go b/server/doc-values/value-number.go similarity index 84% rename from doc-values/value-number.go rename to server/doc-values/value-number.go index 9133db5..1d03b88 100644 --- a/doc-values/value-number.go +++ b/server/doc-values/value-number.go @@ -48,7 +48,7 @@ func (v NumberValue) GetTypeDescription() []string { return []string{"A number"} } -func (v NumberValue) CheckIsValid(value string) []*InvalidValue { +func (v NumberValue) DeprecatedCheckIsValid(value string) []*InvalidValue { number, err := strconv.Atoi(value) if err != nil { @@ -73,10 +73,10 @@ func (v NumberValue) CheckIsValid(value string) []*InvalidValue { return nil } -func (v NumberValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v NumberValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { return []protocol.CompletionItem{} } -func (v NumberValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v NumberValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/doc-values/value-or.go b/server/doc-values/value-or.go similarity index 68% rename from doc-values/value-or.go rename to server/doc-values/value-or.go index 8f9e681..9ca9b36 100644 --- a/doc-values/value-or.go +++ b/server/doc-values/value-or.go @@ -8,14 +8,14 @@ import ( ) type OrValue struct { - Values []Value + Values []DeprecatedValue } func (v OrValue) GetTypeDescription() []string { lines := make([]string, 0) for _, subValueRaw := range v.Values { - subValue := subValueRaw.(Value) + subValue := subValueRaw.(DeprecatedValue) subLines := subValue.GetTypeDescription() for index, line := range subLines { @@ -34,11 +34,11 @@ func (v OrValue) GetTypeDescription() []string { lines..., ) } -func (v OrValue) CheckIsValid(value string) []*InvalidValue { +func (v OrValue) DeprecatedCheckIsValid(value string) []*InvalidValue { errors := make([]*InvalidValue, 0) for _, subValue := range v.Values { - valueErrors := subValue.CheckIsValid(value) + valueErrors := subValue.DeprecatedCheckIsValid(value) if len(valueErrors) == 0 { return nil @@ -49,7 +49,7 @@ func (v OrValue) CheckIsValid(value string) []*InvalidValue { return errors } -func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v OrValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { // Check for special cases if len(v.Values) == 2 { switch v.Values[0].(type) { @@ -63,11 +63,11 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet _, found := utils.FindPreviousCharacter( line, keyEnumValue.Separator, - max(0, int(cursor-1)), + int(cursor), ) if found { - return keyEnumValue.FetchCompletions(line, cursor) + return keyEnumValue.DeprecatedFetchCompletions(line, cursor) } } } @@ -76,19 +76,19 @@ func (v OrValue) FetchCompletions(line string, cursor uint32) []protocol.Complet completions := make([]protocol.CompletionItem, 0) for _, subValue := range v.Values { - completions = append(completions, subValue.FetchCompletions(line, cursor)...) + completions = append(completions, subValue.DeprecatedFetchCompletions(line, cursor)...) } return completions } -func (v OrValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v OrValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { for _, subValue := range v.Values { - valueErrors := subValue.CheckIsValid(line) + valueErrors := subValue.DeprecatedCheckIsValid(line) if len(valueErrors) == 0 { // Found - return subValue.FetchHoverInfo(line, cursor) + return subValue.DeprecatedFetchHoverInfo(line, cursor) } } diff --git a/doc-values/value-path.go b/server/doc-values/value-path.go similarity index 85% rename from doc-values/value-path.go rename to server/doc-values/value-path.go index 32a689d..fa7d5df 100644 --- a/doc-values/value-path.go +++ b/server/doc-values/value-path.go @@ -46,7 +46,7 @@ func (v PathValue) GetTypeDescription() []string { return []string{strings.Join(hints, ", ")} } -func (v PathValue) CheckIsValid(value string) []*InvalidValue { +func (v PathValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !utils.DoesPathExist(value) { return []*InvalidValue{{ Err: PathDoesNotExistError{}, @@ -78,10 +78,10 @@ func (v PathValue) CheckIsValid(value string) []*InvalidValue { } } -func (v PathValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v PathValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { return []protocol.CompletionItem{} } -func (v PathValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v PathValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/doc-values/value-power-of-two.go b/server/doc-values/value-power-of-two.go similarity index 83% rename from doc-values/value-power-of-two.go rename to server/doc-values/value-power-of-two.go index 110e5a5..60eb48a 100644 --- a/doc-values/value-power-of-two.go +++ b/server/doc-values/value-power-of-two.go @@ -34,7 +34,7 @@ func isPowerOfTwo(number int) bool { return true } -func (v PowerOfTwoValue) CheckIsValid(value string) []*InvalidValue { +func (v PowerOfTwoValue) DeprecatedCheckIsValid(value string) []*InvalidValue { number, err := strconv.Atoi(value) if err != nil { @@ -60,7 +60,7 @@ func (v PowerOfTwoValue) CheckIsValid(value string) []*InvalidValue { var powers = []int{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536} -func (v PowerOfTwoValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v PowerOfTwoValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { textFormat := protocol.InsertTextFormatPlainText kind := protocol.CompletionItemKindValue @@ -76,6 +76,6 @@ func (v PowerOfTwoValue) FetchCompletions(line string, cursor uint32) []protocol ) } -func (v PowerOfTwoValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v PowerOfTwoValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/server/doc-values/value-prefix.go b/server/doc-values/value-prefix.go new file mode 100644 index 0000000..35ef7cd --- /dev/null +++ b/server/doc-values/value-prefix.go @@ -0,0 +1,85 @@ +package docvalues + +import ( + "config-lsp/utils" + "fmt" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type Prefix struct { + Prefix string + Meaning string +} +type PrefixWithMeaningValue struct { + Prefixes []Prefix + SubValue DeprecatedValue +} + +func (v PrefixWithMeaningValue) GetTypeDescription() []string { + subDescription := v.SubValue.GetTypeDescription() + + prefixDescription := utils.Map(v.Prefixes, func(prefix Prefix) string { + return fmt.Sprintf("_%s_ -> %s", prefix.Prefix, prefix.Meaning) + }) + + return append(subDescription, + append( + []string{"The following prefixes are allowed:"}, + prefixDescription..., + )..., + ) +} + +func (v PrefixWithMeaningValue) DeprecatedCheckIsValid(value string) []*InvalidValue { + for _, prefix := range v.Prefixes { + if strings.HasPrefix(value, prefix.Prefix) { + return v.SubValue.DeprecatedCheckIsValid(value[len(prefix.Prefix):]) + } + } + + return v.SubValue.DeprecatedCheckIsValid(value) +} + +func (v PrefixWithMeaningValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { + textFormat := protocol.InsertTextFormatPlainText + kind := protocol.CompletionItemKindText + + // Check if the line starts with a prefix + startsWithPrefix := false + for _, prefix := range v.Prefixes { + if strings.HasPrefix(line, prefix.Prefix) { + startsWithPrefix = true + break + } + } + + var prefixCompletions []protocol.CompletionItem + if !startsWithPrefix { + prefixCompletions = utils.Map(v.Prefixes, func(prefix Prefix) protocol.CompletionItem { + return protocol.CompletionItem{ + Label: prefix.Prefix, + Detail: &prefix.Meaning, + InsertTextFormat: &textFormat, + Kind: &kind, + } + }) + } + + return append(prefixCompletions, v.SubValue.DeprecatedFetchCompletions(line, cursor)...) +} + +func (v PrefixWithMeaningValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { + for _, prefix := range v.Prefixes { + if strings.HasPrefix(line, prefix.Prefix) { + return append([]string{ + fmt.Sprintf("Prefix: _%s_ -> %s", prefix.Prefix, prefix.Meaning), + }, + v.SubValue.DeprecatedFetchHoverInfo(line[1:], cursor)..., + ) + } + } + + return v.SubValue.DeprecatedFetchHoverInfo(line[1:], cursor) +} diff --git a/doc-values/value-regex.go b/server/doc-values/value-regex.go similarity index 75% rename from doc-values/value-regex.go rename to server/doc-values/value-regex.go index 1209953..d72ee47 100644 --- a/doc-values/value-regex.go +++ b/server/doc-values/value-regex.go @@ -25,7 +25,7 @@ func (v RegexValue) GetTypeDescription() []string { } } -func (v RegexValue) CheckIsValid(value string) []*InvalidValue { +func (v RegexValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !v.Regex.MatchString(value) { return []*InvalidValue{{ Err: RegexInvalidError{Regex: v.Regex.String()}, @@ -37,11 +37,11 @@ func (v RegexValue) CheckIsValid(value string) []*InvalidValue { return []*InvalidValue{} } -func (v RegexValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v RegexValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { return []protocol.CompletionItem{} } -func (v RegexValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v RegexValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{ fmt.Sprintf("Pattern: `%s`", v.Regex.String()), } diff --git a/doc-values/value-string.go b/server/doc-values/value-string.go similarity index 75% rename from doc-values/value-string.go rename to server/doc-values/value-string.go index ccfbca8..71d359a 100644 --- a/doc-values/value-string.go +++ b/server/doc-values/value-string.go @@ -24,7 +24,7 @@ func (v StringValue) GetTypeDescription() []string { return []string{"String"} } -func (v StringValue) CheckIsValid(value string) []*InvalidValue { +func (v StringValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if value == "" { return []*InvalidValue{{ Err: EmptyStringError{}, @@ -45,10 +45,10 @@ func (v StringValue) CheckIsValid(value string) []*InvalidValue { return nil } -func (v StringValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v StringValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { return []protocol.CompletionItem{} } -func (v StringValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v StringValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/doc-values/value-suffix.go b/server/doc-values/value-suffix.go similarity index 64% rename from doc-values/value-suffix.go rename to server/doc-values/value-suffix.go index 4b5feb7..573cdf0 100644 --- a/doc-values/value-suffix.go +++ b/server/doc-values/value-suffix.go @@ -15,7 +15,7 @@ type Suffix struct { type SuffixWithMeaningValue struct { Suffixes []Suffix - SubValue Value + SubValue DeprecatedValue } func (v SuffixWithMeaningValue) GetTypeDescription() []string { @@ -33,17 +33,17 @@ func (v SuffixWithMeaningValue) GetTypeDescription() []string { ) } -func (v SuffixWithMeaningValue) CheckIsValid(value string) []*InvalidValue { +func (v SuffixWithMeaningValue) DeprecatedCheckIsValid(value string) []*InvalidValue { for _, suffix := range v.Suffixes { if strings.HasSuffix(value, suffix.Suffix) { - return v.SubValue.CheckIsValid(value[:len(value)-len(suffix.Suffix)]) + return v.SubValue.DeprecatedCheckIsValid(value[:len(value)-len(suffix.Suffix)]) } } - return v.SubValue.CheckIsValid(value) + return v.SubValue.DeprecatedCheckIsValid(value) } -func (v SuffixWithMeaningValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v SuffixWithMeaningValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { textFormat := protocol.InsertTextFormatPlainText kind := protocol.CompletionItemKindText @@ -56,19 +56,19 @@ func (v SuffixWithMeaningValue) FetchCompletions(line string, cursor uint32) []p } }) - return append(suffixCompletions, v.SubValue.FetchCompletions(line, cursor)...) + return append(suffixCompletions, v.SubValue.DeprecatedFetchCompletions(line, cursor)...) } -func (v SuffixWithMeaningValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v SuffixWithMeaningValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { for _, suffix := range v.Suffixes { if strings.HasSuffix(line, suffix.Suffix) { return append([]string{ fmt.Sprintf("Suffix: _%s_ -> %s", suffix.Suffix, suffix.Meaning), }, - v.SubValue.FetchHoverInfo(line[:len(line)-len(suffix.Suffix)], cursor)..., + v.SubValue.DeprecatedFetchHoverInfo(line[:len(line)-len(suffix.Suffix)], cursor)..., ) } } - return v.SubValue.FetchHoverInfo(line, cursor) + return v.SubValue.DeprecatedFetchHoverInfo(line, cursor) } diff --git a/handlers/openssh/value-time-format.go b/server/doc-values/value-time-format.go similarity index 83% rename from handlers/openssh/value-time-format.go rename to server/doc-values/value-time-format.go index b2f3554..4670aa9 100644 --- a/handlers/openssh/value-time-format.go +++ b/server/doc-values/value-time-format.go @@ -1,7 +1,6 @@ -package openssh +package docvalues import ( - docvalues "config-lsp/doc-values" "config-lsp/utils" "fmt" "regexp" @@ -12,6 +11,7 @@ import ( var timeFormatCompletionsPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw])$`) var timeFormatCheckPattern = regexp.MustCompile(`(?i)^(\d+)([smhdw]?)$`) +var isJustDigitsPattern = regexp.MustCompile(`^\d+$`) type InvalidTimeFormatError struct{} @@ -25,9 +25,9 @@ func (v TimeFormatValue) GetTypeDescription() []string { return []string{"Time value"} } -func (v TimeFormatValue) CheckIsValid(value string) []*docvalues.InvalidValue { +func (v TimeFormatValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !timeFormatCheckPattern.MatchString(value) { - return []*docvalues.InvalidValue{ + return []*InvalidValue{ { Err: InvalidTimeFormatError{}, Start: 0, @@ -56,7 +56,7 @@ func calculateInSeconds(value int, unit string) int { } } -func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v TimeFormatValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { completions := make([]protocol.CompletionItem, 0) if line != "" && !timeFormatCompletionsPattern.MatchString(line) { @@ -99,13 +99,13 @@ func (v TimeFormatValue) FetchCompletions(line string, cursor uint32) []protocol if line == "" || isJustDigitsPattern.MatchString(line) { completions = append( completions, - docvalues.GenerateBase10Completions(line)..., + GenerateBase10Completions(line)..., ) } return completions } -func (v TimeFormatValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v TimeFormatValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/doc-values/value-uid.go b/server/doc-values/value-uid.go similarity index 91% rename from doc-values/value-uid.go rename to server/doc-values/value-uid.go index bcbf7a4..c6c1fe9 100644 --- a/doc-values/value-uid.go +++ b/server/doc-values/value-uid.go @@ -35,7 +35,7 @@ func (v UIDValue) GetTypeDescription() []string { return []string{"User ID"} } -func (v UIDValue) CheckIsValid(value string) []*InvalidValue { +func (v UIDValue) DeprecatedCheckIsValid(value string) []*InvalidValue { uid, err := strconv.Atoi(value) if err != nil { @@ -90,7 +90,7 @@ var defaultUIDsExplanation = []EnumString{ }, } -func (v UIDValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v UIDValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { infos, err := common.FetchPasswdInfo() if err != nil { @@ -129,7 +129,7 @@ func (v UIDValue) FetchCompletions(line string, cursor uint32) []protocol.Comple return completions } -func (v UIDValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v UIDValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { uid, err := strconv.Atoi(line) if err != nil { diff --git a/doc-values/value-umask.go b/server/doc-values/value-umask.go similarity index 90% rename from doc-values/value-umask.go rename to server/doc-values/value-umask.go index fc44e2c..f9c3d72 100644 --- a/doc-values/value-umask.go +++ b/server/doc-values/value-umask.go @@ -28,7 +28,7 @@ func (v UmaskValue) GetTypeDescription() []string { var umaskPattern = regexp.MustCompile("^[0-7]{4}$") -func (v UmaskValue) CheckIsValid(value string) []*InvalidValue { +func (v UmaskValue) DeprecatedCheckIsValid(value string) []*InvalidValue { if !umaskPattern.MatchString(value) { return []*InvalidValue{{ Err: UmaskInvalidError{}, @@ -40,7 +40,7 @@ func (v UmaskValue) CheckIsValid(value string) []*InvalidValue { return []*InvalidValue{} } -func (v UmaskValue) FetchCompletions(line string, cursor uint32) []protocol.CompletionItem { +func (v UmaskValue) DeprecatedFetchCompletions(line string, cursor uint32) []protocol.CompletionItem { kind := protocol.CompletionItemKindValue return []protocol.CompletionItem{ @@ -111,6 +111,6 @@ func (v UmaskValue) FetchCompletions(line string, cursor uint32) []protocol.Comp } } -func (v UmaskValue) FetchHoverInfo(line string, cursor uint32) []string { +func (v UmaskValue) DeprecatedFetchHoverInfo(line string, cursor uint32) []string { return []string{} } diff --git a/go.mod b/server/go.mod similarity index 96% rename from go.mod rename to server/go.mod index 661cc9a..8c84359 100644 --- a/go.mod +++ b/server/go.mod @@ -11,6 +11,7 @@ require ( github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect + github.com/google/go-cmp v0.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/iancoleman/strcase v0.3.0 // indirect github.com/k0kubun/pp v3.0.1+incompatible // indirect diff --git a/go.sum b/server/go.sum similarity index 96% rename from go.sum rename to server/go.sum index 60c2e89..100a1f7 100644 --- a/go.sum +++ b/server/go.sum @@ -4,6 +4,8 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= diff --git a/handlers/aliases/Aliases.g4 b/server/handlers/aliases/Aliases.g4 similarity index 100% rename from handlers/aliases/Aliases.g4 rename to server/handlers/aliases/Aliases.g4 diff --git a/handlers/aliases/analyzer/analyzer.go b/server/handlers/aliases/analyzer/analyzer.go similarity index 100% rename from handlers/aliases/analyzer/analyzer.go rename to server/handlers/aliases/analyzer/analyzer.go diff --git a/handlers/aliases/analyzer/double_keys.go b/server/handlers/aliases/analyzer/double_keys.go similarity index 100% rename from handlers/aliases/analyzer/double_keys.go rename to server/handlers/aliases/analyzer/double_keys.go diff --git a/handlers/aliases/analyzer/double_keys_test.go b/server/handlers/aliases/analyzer/double_keys_test.go similarity index 100% rename from handlers/aliases/analyzer/double_keys_test.go rename to server/handlers/aliases/analyzer/double_keys_test.go diff --git a/handlers/aliases/analyzer/double_values.go b/server/handlers/aliases/analyzer/double_values.go similarity index 100% rename from handlers/aliases/analyzer/double_values.go rename to server/handlers/aliases/analyzer/double_values.go diff --git a/handlers/aliases/analyzer/double_values_test.go b/server/handlers/aliases/analyzer/double_values_test.go similarity index 100% rename from handlers/aliases/analyzer/double_values_test.go rename to server/handlers/aliases/analyzer/double_values_test.go diff --git a/handlers/aliases/analyzer/required_keys.go b/server/handlers/aliases/analyzer/required_keys.go similarity index 100% rename from handlers/aliases/analyzer/required_keys.go rename to server/handlers/aliases/analyzer/required_keys.go diff --git a/handlers/aliases/analyzer/value_valid.go b/server/handlers/aliases/analyzer/value_valid.go similarity index 100% rename from handlers/aliases/analyzer/value_valid.go rename to server/handlers/aliases/analyzer/value_valid.go diff --git a/handlers/aliases/ast/aliases.go b/server/handlers/aliases/ast/aliases.go similarity index 100% rename from handlers/aliases/ast/aliases.go rename to server/handlers/aliases/ast/aliases.go diff --git a/handlers/aliases/ast/listener.go b/server/handlers/aliases/ast/listener.go similarity index 99% rename from handlers/aliases/ast/listener.go rename to server/handlers/aliases/ast/listener.go index 0ccd6b9..3a5c112 100644 --- a/handlers/aliases/ast/listener.go +++ b/server/handlers/aliases/ast/listener.go @@ -2,7 +2,7 @@ package ast import ( "config-lsp/common" - "config-lsp/handlers/aliases/parser" + "config-lsp/handlers/aliases/ast/parser" "github.com/antlr4-go/antlr/v4" ) diff --git a/handlers/aliases/ast/parser.go b/server/handlers/aliases/ast/parser.go similarity index 95% rename from handlers/aliases/ast/parser.go rename to server/handlers/aliases/ast/parser.go index 2abe986..44bcdec 100644 --- a/handlers/aliases/ast/parser.go +++ b/server/handlers/aliases/ast/parser.go @@ -2,7 +2,7 @@ package ast import ( "config-lsp/common" - "config-lsp/handlers/aliases/parser" + "config-lsp/handlers/aliases/ast/parser" "config-lsp/utils" "regexp" @@ -77,6 +77,7 @@ func (p *AliasesParser) parseStatement( errors := lexerErrorListener.Errors errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) return errors } diff --git a/handlers/aliases/parser/Aliases.interp b/server/handlers/aliases/ast/parser/Aliases.interp similarity index 100% rename from handlers/aliases/parser/Aliases.interp rename to server/handlers/aliases/ast/parser/Aliases.interp diff --git a/handlers/aliases/parser/Aliases.tokens b/server/handlers/aliases/ast/parser/Aliases.tokens similarity index 100% rename from handlers/aliases/parser/Aliases.tokens rename to server/handlers/aliases/ast/parser/Aliases.tokens diff --git a/handlers/aliases/parser/AliasesLexer.interp b/server/handlers/aliases/ast/parser/AliasesLexer.interp similarity index 100% rename from handlers/aliases/parser/AliasesLexer.interp rename to server/handlers/aliases/ast/parser/AliasesLexer.interp diff --git a/handlers/aliases/parser/AliasesLexer.tokens b/server/handlers/aliases/ast/parser/AliasesLexer.tokens similarity index 100% rename from handlers/aliases/parser/AliasesLexer.tokens rename to server/handlers/aliases/ast/parser/AliasesLexer.tokens diff --git a/handlers/aliases/parser/aliases_base_listener.go b/server/handlers/aliases/ast/parser/aliases_base_listener.go similarity index 100% rename from handlers/aliases/parser/aliases_base_listener.go rename to server/handlers/aliases/ast/parser/aliases_base_listener.go diff --git a/handlers/aliases/parser/aliases_lexer.go b/server/handlers/aliases/ast/parser/aliases_lexer.go similarity index 100% rename from handlers/aliases/parser/aliases_lexer.go rename to server/handlers/aliases/ast/parser/aliases_lexer.go diff --git a/handlers/aliases/parser/aliases_listener.go b/server/handlers/aliases/ast/parser/aliases_listener.go similarity index 100% rename from handlers/aliases/parser/aliases_listener.go rename to server/handlers/aliases/ast/parser/aliases_listener.go diff --git a/handlers/aliases/parser/aliases_parser.go b/server/handlers/aliases/ast/parser/aliases_parser.go similarity index 100% rename from handlers/aliases/parser/aliases_parser.go rename to server/handlers/aliases/ast/parser/aliases_parser.go diff --git a/handlers/aliases/ast/parser_test.go b/server/handlers/aliases/ast/parser_test.go similarity index 100% rename from handlers/aliases/ast/parser_test.go rename to server/handlers/aliases/ast/parser_test.go diff --git a/handlers/aliases/ast/values.go b/server/handlers/aliases/ast/values.go similarity index 95% rename from handlers/aliases/ast/values.go rename to server/handlers/aliases/ast/values.go index accc7ab..a01c76c 100644 --- a/handlers/aliases/ast/values.go +++ b/server/handlers/aliases/ast/values.go @@ -71,7 +71,7 @@ type AliasValueInclude struct { func (a AliasValueInclude) CheckIsValid() []common.LSPError { return utils.Map( - fields.PathField.CheckIsValid(string(a.Path.Path)), + fields.PathField.DeprecatedCheckIsValid(string(a.Path.Path)), func(invalidValue *docvalues.InvalidValue) common.LSPError { return docvalues.LSPErrorFromInvalidValue(a.Location.Start.Line, *invalidValue) }, @@ -88,7 +88,7 @@ type AliasValueEmail struct { func (a AliasValueEmail) CheckIsValid() []common.LSPError { return utils.Map( - fields.PathField.CheckIsValid(a.Value), + fields.PathField.DeprecatedCheckIsValid(a.Value), func(invalidValue *docvalues.InvalidValue) common.LSPError { return docvalues.LSPErrorFromInvalidValue(a.Location.Start.Line, *invalidValue) }, diff --git a/server/handlers/aliases/commands/aliases-command.go b/server/handlers/aliases/commands/aliases-command.go new file mode 100644 index 0000000..7ad9475 --- /dev/null +++ b/server/handlers/aliases/commands/aliases-command.go @@ -0,0 +1,45 @@ +package commands + +import ( + "os/exec" + "strings" +) + +func IsNewAliasesCommandAvailable() bool { + _, err := exec.LookPath("newaliases") + + return err == nil +} + +func IsSendmailCommandAvailable() bool { + _, err := exec.LookPath("sendmail") + + return err == nil +} + +func IsPostfixCommandAvailable() bool { + _, err := exec.LookPath("postfix") + + return err == nil +} + +func CanSendTestMails() bool { + return IsSendmailCommandAvailable() && IsPostfixCommandAvailable() +} + +func UpdateAliasesDatabase() error { + cmd := exec.Command("newaliases") + + err := cmd.Run() + + return err +} + +func SendTestMail(address string, content string) error { + cmd := exec.Command("sendmail", address) + cmd.Stdin = strings.NewReader(content) + + err := cmd.Run() + + return err +} diff --git a/server/handlers/aliases/commands/aliases-commands_test.go b/server/handlers/aliases/commands/aliases-commands_test.go new file mode 100644 index 0000000..fee1097 --- /dev/null +++ b/server/handlers/aliases/commands/aliases-commands_test.go @@ -0,0 +1,11 @@ +package commands + +import "testing" + +func TestAreAliasesCommandsAvailable( + t *testing.T, +) { + if !IsNewAliasesCommandAvailable() { + t.Skip("Aliases tools not available") + } +} diff --git a/handlers/aliases/fetchers/values.go b/server/handlers/aliases/fetchers/values.go similarity index 100% rename from handlers/aliases/fetchers/values.go rename to server/handlers/aliases/fetchers/values.go diff --git a/handlers/aliases/fields/fields.go b/server/handlers/aliases/fields/fields.go similarity index 100% rename from handlers/aliases/fields/fields.go rename to server/handlers/aliases/fields/fields.go diff --git a/server/handlers/aliases/handlers/code-actions.go b/server/handlers/aliases/handlers/code-actions.go new file mode 100644 index 0000000..a8eedd4 --- /dev/null +++ b/server/handlers/aliases/handlers/code-actions.go @@ -0,0 +1,51 @@ +package handlers + +import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/commands" + "fmt" + "time" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type CodeActionName string + +const ( + CodeActionSendTestMail CodeActionName = "sendTestMail" +) + +type CodeAction interface { + RunCommand(*aliases.AliasesDocument) (*protocol.ApplyWorkspaceEditParams, error) +} + +type CodeActionArgs interface{} + +type CodeActionSendTestMailArgs struct { + URI protocol.DocumentUri + User string +} + +func CodeActionSendTestMailArgsFromArguments(arguments map[string]interface{}) CodeActionSendTestMailArgs { + return CodeActionSendTestMailArgs{ + URI: arguments["URI"].(protocol.DocumentUri), + User: arguments["User"].(string), + } +} + +func (args CodeActionSendTestMailArgs) RunCommand(d *aliases.AliasesDocument) (*protocol.ApplyWorkspaceEditParams, error) { + content := fmt.Sprintf( + `Subject: Test mail from %s + +This is a test mail from config-lsp. +It is intended for the user %s. +`, + time.Now().Format(time.RFC1123), + args.User, + ) + + address := fmt.Sprintf("%s@localhost.localdomain", args.User) + commands.SendTestMail(address, content) + + return &protocol.ApplyWorkspaceEditParams{}, nil +} diff --git a/handlers/aliases/handlers/completions.go b/server/handlers/aliases/handlers/completions.go similarity index 92% rename from handlers/aliases/handlers/completions.go rename to server/handlers/aliases/handlers/completions.go index 246c219..b7d43a7 100644 --- a/handlers/aliases/handlers/completions.go +++ b/server/handlers/aliases/handlers/completions.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/analyzer" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/fetchers" @@ -38,7 +39,7 @@ func GetAliasesCompletions( } func GetCompletionsForEntry( - cursor uint32, + cursor common.CursorPosition, entry *ast.AliasEntry, i *indexes.AliasesIndexes, ) ([]protocol.CompletionItem, error) { @@ -48,8 +49,7 @@ func GetCompletionsForEntry( return completions, nil } - value := GetValueAtCursor(cursor, entry) - relativeCursor := cursor - entry.Key.Location.Start.Character + value := GetValueAtPosition(cursor, entry) excludedUsers := getUsersFromEntry(entry) @@ -61,8 +61,6 @@ func GetCompletionsForEntry( completions = append(completions, getUserCompletions( i, excludedUsers, - "", - 0, )...) return completions, nil @@ -70,21 +68,17 @@ func GetCompletionsForEntry( switch (*value).(type) { case ast.AliasValueUser: - userValue := (*value).(ast.AliasValueUser) - return getUserCompletions( i, excludedUsers, - userValue.Value, - relativeCursor, ), nil case ast.AliasValueError: errorValue := (*value).(ast.AliasValueError) isAtErrorCode := errorValue.Code == nil && - relativeCursor >= errorValue.Location.Start.Character && + errorValue.Location.IsPositionAfterStart(cursor) && (errorValue.Message == nil || - relativeCursor <= errorValue.Message.Location.Start.Character) + errorValue.Message.Location.IsPositionBeforeEnd(cursor)) if isAtErrorCode { kind := protocol.CompletionItemKindValue @@ -160,8 +154,6 @@ func getErrorCompletion() protocol.CompletionItem { func getUserCompletions( i *indexes.AliasesIndexes, excluded map[string]struct{}, - line string, - cursor uint32, ) []protocol.CompletionItem { users := fetchers.GetAvailableUserValues(i) diff --git a/server/handlers/aliases/handlers/fetch-code-actions.go b/server/handlers/aliases/handlers/fetch-code-actions.go new file mode 100644 index 0000000..5a76437 --- /dev/null +++ b/server/handlers/aliases/handlers/fetch-code-actions.go @@ -0,0 +1,59 @@ +package handlers + +import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/ast" + "config-lsp/handlers/aliases/commands" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type disabledExplanation struct { + Reason string +} + +func FetchCodeActions( + d *aliases.AliasesDocument, + params *protocol.CodeActionParams, +) []protocol.CodeAction { + line := params.Range.Start.Line + + rawEntry, found := d.Parser.Aliases.Get(line) + + if !found { + return nil + } + + entry := rawEntry.(*ast.AliasEntry) + + if entry.Key != nil { + address := fmt.Sprintf("%s@localhost.localdomain", entry.Key.Value) + + commandID := "aliases." + CodeActionSendTestMail + command := protocol.Command{ + Title: fmt.Sprintf("Send a test mail to %s", address), + Command: string(commandID), + Arguments: []any{ + CodeActionSendTestMailArgs{ + URI: params.TextDocument.URI, + User: entry.Key.Value, + }, + }, + } + codeAction := &protocol.CodeAction{ + Title: fmt.Sprintf("Send a test mail to %s", address), + Command: &command, + } + + if !commands.CanSendTestMails() { + codeAction.Disabled.Reason = "postfix is required to send test mails" + } + + return []protocol.CodeAction{ + *codeAction, + } + } + + return nil +} diff --git a/handlers/aliases/handlers/get-value.go b/server/handlers/aliases/handlers/get-value.go similarity index 56% rename from handlers/aliases/handlers/get-value.go rename to server/handlers/aliases/handlers/get-value.go index 3e2347b..ce6219b 100644 --- a/handlers/aliases/handlers/get-value.go +++ b/server/handlers/aliases/handlers/get-value.go @@ -1,12 +1,13 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/ast" "slices" ) -func GetValueAtCursor( - cursor uint32, +func GetValueAtPosition( + position common.Position, entry *ast.AliasEntry, ) *ast.AliasValueInterface { if entry.Values == nil || len(entry.Values.Values) == 0 { @@ -15,15 +16,15 @@ func GetValueAtCursor( index, found := slices.BinarySearchFunc( entry.Values.Values, - cursor, - func(entry ast.AliasValueInterface, pos uint32) int { - value := entry.GetAliasValue() + position, + func(rawCurrent ast.AliasValueInterface, target common.Position) int { + current := rawCurrent.GetAliasValue() - if pos > value.Location.End.Character { + if current.Location.IsPositionAfterEnd(target) { return -1 } - if pos < value.Location.Start.Character { + if current.Location.IsPositionBeforeStart(target) { return 1 } diff --git a/handlers/aliases/handlers/go_to_definition.go b/server/handlers/aliases/handlers/go_to_definition.go similarity index 100% rename from handlers/aliases/handlers/go_to_definition.go rename to server/handlers/aliases/handlers/go_to_definition.go diff --git a/handlers/aliases/handlers/go_to_definition_test.go b/server/handlers/aliases/handlers/go_to_definition_test.go similarity index 100% rename from handlers/aliases/handlers/go_to_definition_test.go rename to server/handlers/aliases/handlers/go_to_definition_test.go diff --git a/handlers/aliases/handlers/hover.go b/server/handlers/aliases/handlers/hover.go similarity index 98% rename from handlers/aliases/handlers/hover.go rename to server/handlers/aliases/handlers/hover.go index 8cd5a8e..bb34661 100644 --- a/handlers/aliases/handlers/hover.go +++ b/server/handlers/aliases/handlers/hover.go @@ -96,7 +96,6 @@ func GetAliasValueHoverInfo( func GetAliasValueTypeInfo( value ast.AliasValueInterface, ) []string { - println(fmt.Sprintf("value: %v, value type: %T", value, value)) switch value.(type) { case ast.AliasValueUser: return []string{ diff --git a/handlers/aliases/handlers/rename.go b/server/handlers/aliases/handlers/rename.go similarity index 58% rename from handlers/aliases/handlers/rename.go rename to server/handlers/aliases/handlers/rename.go index 9b1cfab..7a29537 100644 --- a/handlers/aliases/handlers/rename.go +++ b/server/handlers/aliases/handlers/rename.go @@ -1,7 +1,6 @@ package handlers import ( - "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/indexes" protocol "github.com/tliron/glsp/protocol_3_16" @@ -9,17 +8,22 @@ import ( func RenameAlias( i indexes.AliasesIndexes, - oldEntry *ast.AliasEntry, + oldName string, newName string, ) []protocol.TextEdit { - occurrences := i.UserOccurrences[indexes.NormalizeKey(oldEntry.Key.Value)] + normalizedName := indexes.NormalizeKey(oldName) + definitionEntry := i.Keys[normalizedName] + occurrences := i.UserOccurrences[normalizedName] + changes := make([]protocol.TextEdit, 0, len(occurrences)) - // Own rename - changes = append(changes, protocol.TextEdit{ - Range: oldEntry.Key.Location.ToLSPRange(), - NewText: newName, - }) + if definitionEntry != nil { + // Own rename + changes = append(changes, protocol.TextEdit{ + Range: definitionEntry.Key.Location.ToLSPRange(), + NewText: newName, + }) + } // Other AliasValueUser occurrences for _, value := range occurrences { diff --git a/handlers/aliases/handlers/rename_test.go b/server/handlers/aliases/handlers/rename_test.go similarity index 55% rename from handlers/aliases/handlers/rename_test.go rename to server/handlers/aliases/handlers/rename_test.go index eb6606a..9a07d32 100644 --- a/handlers/aliases/handlers/rename_test.go +++ b/server/handlers/aliases/handlers/rename_test.go @@ -28,7 +28,7 @@ support: alice, bob t.Fatalf("Expected no errors, but got: %v", errors) } - edits := RenameAlias(i, i.Keys["alice"], "amelie") + edits := RenameAlias(i, "alice", "amelie") if !(len(edits) == 3) { t.Errorf("Expected 2 edits, but got %v", len(edits)) @@ -46,3 +46,38 @@ support: alice, bob t.Errorf("Unexpected edit: %v", edits[2]) } } + +func TestRenameWithoutDefinitionEntry( + t *testing.T, +) { + input := utils.Dedent(` +bob: root +support: root, bob +`) + parser := ast.NewAliasesParser() + errors := parser.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Unexpected errors: %v", errors) + } + + i, errors := indexes.CreateIndexes(parser) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, but got: %v", errors) + } + + edits := RenameAlias(i, "root", "amelie") + + if !(len(edits) == 2) { + t.Errorf("Expected 2 edits, but got %v", len(edits)) + } + + if !(edits[0].Range.Start.Line == 0 && edits[0].Range.Start.Character == 5 && edits[0].Range.End.Line == 0 && edits[0].Range.End.Character == 9) { + t.Errorf("Unexpected edit: %v", edits[0]) + } + + if !(edits[1].Range.Start.Line == 1 && edits[1].Range.Start.Character == 9 && edits[1].Range.End.Line == 1 && edits[1].Range.End.Character == 13) { + t.Errorf("Unexpected edit: %v", edits[1]) + } +} diff --git a/handlers/aliases/handlers/signature_help.go b/server/handlers/aliases/handlers/signature_help.go similarity index 94% rename from handlers/aliases/handlers/signature_help.go rename to server/handlers/aliases/handlers/signature_help.go index 7da7f06..b85bf73 100644 --- a/handlers/aliases/handlers/signature_help.go +++ b/server/handlers/aliases/handlers/signature_help.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/aliases/ast" "strings" @@ -125,8 +126,8 @@ func GetAllValuesSignatureHelp() *protocol.SignatureHelp { } func GetValueSignatureHelp( + cursor common.CursorPosition, value ast.AliasValueInterface, - cursor uint32, ) *protocol.SignatureHelp { switch value.(type) { case ast.AliasValueUser: @@ -166,7 +167,8 @@ func GetValueSignatureHelp( }, } case ast.AliasValueEmail: - isBeforeAtSymbol := cursor <= uint32(strings.Index(value.GetAliasValue().Value, "@")) + indexPosition := common.LSPCharacterAsIndexPosition(uint32(strings.Index(value.GetAliasValue().Value, "@"))) + isBeforeAtSymbol := cursor.IsBeforeIndexPosition(indexPosition) var index uint32 @@ -269,7 +271,7 @@ func GetValueSignatureHelp( errorValue := value.(ast.AliasValueError) var index uint32 - if errorValue.Code == nil || cursor <= errorValue.Code.Location.End.Character { + if errorValue.Code == nil || errorValue.Code.Location.IsPositionBeforeEnd(cursor) { index = 1 } else { index = 2 diff --git a/handlers/aliases/indexes/indexes.go b/server/handlers/aliases/indexes/indexes.go similarity index 100% rename from handlers/aliases/indexes/indexes.go rename to server/handlers/aliases/indexes/indexes.go diff --git a/handlers/aliases/indexes/indexes_test.go b/server/handlers/aliases/indexes/indexes_test.go similarity index 100% rename from handlers/aliases/indexes/indexes_test.go rename to server/handlers/aliases/indexes/indexes_test.go diff --git a/handlers/aliases/lsp/text-document-code-action.go b/server/handlers/aliases/lsp/text-document-code-action.go similarity index 52% rename from handlers/aliases/lsp/text-document-code-action.go rename to server/handlers/aliases/lsp/text-document-code-action.go index 37950bd..ba73911 100644 --- a/handlers/aliases/lsp/text-document-code-action.go +++ b/server/handlers/aliases/lsp/text-document-code-action.go @@ -1,14 +1,16 @@ package lsp import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/handlers" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func TextDocumentCodeAction(context *glsp.Context, params *protocol.CodeActionParams) ([]protocol.CodeAction, error) { - // document := hosts.DocumentParserMap[params.TextDocument.URI] - // - // actions := make([]protocol.CodeAction, 0, 1) + d := aliases.DocumentParserMap[params.TextDocument.URI] + actions := handlers.FetchCodeActions(d, params) - return nil, nil + return actions, nil } diff --git a/handlers/aliases/lsp/text-document-completion.go b/server/handlers/aliases/lsp/text-document-completion.go similarity index 77% rename from handlers/aliases/lsp/text-document-completion.go rename to server/handlers/aliases/lsp/text-document-completion.go index 0240c8f..1d5d429 100644 --- a/handlers/aliases/lsp/text-document-completion.go +++ b/server/handlers/aliases/lsp/text-document-completion.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - cursor := params.Position.Character + cursor := common.LSPCharacterAsCursorPosition(params.Position.Character) line := params.Position.Line if _, found := d.Parser.CommentLines[line]; found { @@ -31,15 +32,15 @@ func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionPa return handlers.GetAliasesCompletions(d.Indexes), nil } - if cursor >= entry.Key.Location.Start.Character && cursor <= entry.Key.Location.End.Character { + if entry.Key.Location.ContainsPosition(cursor) { return handlers.GetAliasesCompletions(d.Indexes), nil } - if entry.Separator == nil && cursor > entry.Key.Location.End.Character { + if entry.Separator == nil && entry.Key.Location.IsPositionBeforeEnd(cursor) { return nil, nil } - if cursor > entry.Separator.End.Character { + if entry.Separator.IsPositionBeforeEnd(cursor) { return handlers.GetCompletionsForEntry( cursor, entry, diff --git a/handlers/aliases/lsp/text-document-definition.go b/server/handlers/aliases/lsp/text-document-definition.go similarity index 75% rename from handlers/aliases/lsp/text-document-definition.go rename to server/handlers/aliases/lsp/text-document-definition.go index 4798e16..5976f5d 100644 --- a/handlers/aliases/lsp/text-document-definition.go +++ b/server/handlers/aliases/lsp/text-document-definition.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -22,8 +23,8 @@ func TextDocumentDefinition(context *glsp.Context, params *protocol.DefinitionPa entry := rawEntry.(*ast.AliasEntry) - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-did-change.go b/server/handlers/aliases/lsp/text-document-did-change.go similarity index 100% rename from handlers/aliases/lsp/text-document-did-change.go rename to server/handlers/aliases/lsp/text-document-did-change.go diff --git a/handlers/hosts/lsp/text-document-did-close.go b/server/handlers/aliases/lsp/text-document-did-close.go similarity index 70% rename from handlers/hosts/lsp/text-document-did-close.go rename to server/handlers/aliases/lsp/text-document-did-close.go index 3283aad..7eb4a5f 100644 --- a/handlers/hosts/lsp/text-document-did-close.go +++ b/server/handlers/aliases/lsp/text-document-did-close.go @@ -1,13 +1,13 @@ package lsp import ( - "config-lsp/handlers/hosts" + "config-lsp/handlers/aliases" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { - delete(hosts.DocumentParserMap, params.TextDocument.URI) + delete(aliases.DocumentParserMap, params.TextDocument.URI) return nil } diff --git a/handlers/aliases/lsp/text-document-did-open.go b/server/handlers/aliases/lsp/text-document-did-open.go similarity index 100% rename from handlers/aliases/lsp/text-document-did-open.go rename to server/handlers/aliases/lsp/text-document-did-open.go diff --git a/handlers/aliases/lsp/text-document-hover.go b/server/handlers/aliases/lsp/text-document-hover.go similarity index 77% rename from handlers/aliases/lsp/text-document-hover.go rename to server/handlers/aliases/lsp/text-document-hover.go index 51acd2c..a1c97fd 100644 --- a/handlers/aliases/lsp/text-document-hover.go +++ b/server/handlers/aliases/lsp/text-document-hover.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -17,7 +18,7 @@ func TextDocumentHover( document := aliases.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) if _, found := document.Parser.CommentLines[line]; found { // Comment @@ -32,7 +33,7 @@ func TextDocumentHover( entry := rawEntry.(*ast.AliasEntry) - if entry.Key != nil && character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key != nil && entry.Key.Location.ContainsPosition(index) { text := handlers.GetAliasHoverInfo(*document.Indexes, *entry) return &protocol.Hover{ @@ -40,8 +41,8 @@ func TextDocumentHover( }, nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - value := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + value := handlers.GetValueAtPosition(index, entry) if value == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-prepare-rename.go b/server/handlers/aliases/lsp/text-document-prepare-rename.go similarity index 70% rename from handlers/aliases/lsp/text-document-prepare-rename.go rename to server/handlers/aliases/lsp/text-document-prepare-rename.go index 2b2d03e..56e2dd1 100644 --- a/handlers/aliases/lsp/text-document-prepare-rename.go +++ b/server/handlers/aliases/lsp/text-document-prepare-rename.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -11,7 +12,7 @@ import ( func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRenameParams) (any, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -22,12 +23,12 @@ func TextDocumentPrepareRename(context *glsp.Context, params *protocol.PrepareRe entry := rawEntry.(*ast.AliasEntry) - if character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key.Location.ContainsPosition(index) { return entry.Key.Location.ToLSPRange(), nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil diff --git a/handlers/aliases/lsp/text-document-rename.go b/server/handlers/aliases/lsp/text-document-rename.go similarity index 62% rename from handlers/aliases/lsp/text-document-rename.go rename to server/handlers/aliases/lsp/text-document-rename.go index be529ed..d51f092 100644 --- a/handlers/aliases/lsp/text-document-rename.go +++ b/server/handlers/aliases/lsp/text-document-rename.go @@ -1,10 +1,10 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" - "config-lsp/handlers/aliases/indexes" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -12,7 +12,7 @@ import ( func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (*protocol.WorkspaceEdit, error) { d := aliases.DocumentParserMap[params.TextDocument.URI] - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) line := params.Position.Line rawEntry, found := d.Parser.Aliases.Get(line) @@ -23,8 +23,12 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* entry := rawEntry.(*ast.AliasEntry) - if character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { - changes := handlers.RenameAlias(*d.Indexes, entry, params.NewName) + if entry.Key.Location.ContainsPosition(index) { + changes := handlers.RenameAlias( + *d.Indexes, + entry.Key.Value, + params.NewName, + ) return &protocol.WorkspaceEdit{ Changes: map[protocol.DocumentUri][]protocol.TextEdit{ @@ -33,8 +37,8 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* }, nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - rawValue := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(index) { + rawValue := handlers.GetValueAtPosition(index, entry) if rawValue == nil { return nil, nil @@ -44,9 +48,11 @@ func TextDocumentRename(context *glsp.Context, params *protocol.RenameParams) (* case ast.AliasValueUser: userValue := (*rawValue).(ast.AliasValueUser) - definitionEntry := d.Indexes.Keys[indexes.NormalizeKey(userValue.Value)] - - changes := handlers.RenameAlias(*d.Indexes, definitionEntry, params.NewName) + changes := handlers.RenameAlias( + *d.Indexes, + userValue.Value, + params.NewName, + ) return &protocol.WorkspaceEdit{ Changes: map[protocol.DocumentUri][]protocol.TextEdit{ diff --git a/handlers/aliases/lsp/text-document-signature-help.go b/server/handlers/aliases/lsp/text-document-signature-help.go similarity index 72% rename from handlers/aliases/lsp/text-document-signature-help.go rename to server/handlers/aliases/lsp/text-document-signature-help.go index ce3a9b0..913fe62 100644 --- a/handlers/aliases/lsp/text-document-signature-help.go +++ b/server/handlers/aliases/lsp/text-document-signature-help.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/aliases" "config-lsp/handlers/aliases/ast" "config-lsp/handlers/aliases/handlers" @@ -13,7 +14,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature document := aliases.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + cursor := common.LSPCharacterAsCursorPosition(common.CursorToCharacterIndex(params.Position.Character)) if _, found := document.Parser.CommentLines[line]; found { // Comment @@ -28,12 +29,12 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature entry := rawEntry.(*ast.AliasEntry) - if entry.Key != nil && character >= entry.Key.Location.Start.Character && character <= entry.Key.Location.End.Character { + if entry.Key != nil && entry.Key.Location.ContainsPosition(cursor) { return handlers.GetRootSignatureHelp(0), nil } - if entry.Values != nil && character >= entry.Values.Location.Start.Character && character <= entry.Values.Location.End.Character { - value := handlers.GetValueAtCursor(character, entry) + if entry.Values != nil && entry.Values.Location.ContainsPosition(cursor) { + value := handlers.GetValueAtPosition(cursor, entry) if value == nil { // For some reason, this does not really work, @@ -45,7 +46,7 @@ func TextDocumentSignatureHelp(context *glsp.Context, params *protocol.Signature return nil, nil } - return handlers.GetValueSignatureHelp(*value, character), nil + return handlers.GetValueSignatureHelp(cursor, *value), nil } return nil, nil diff --git a/server/handlers/aliases/lsp/workspace-execute-command.go b/server/handlers/aliases/lsp/workspace-execute-command.go new file mode 100644 index 0000000..8cad016 --- /dev/null +++ b/server/handlers/aliases/lsp/workspace-execute-command.go @@ -0,0 +1,25 @@ +package lsp + +import ( + "config-lsp/handlers/aliases" + "config-lsp/handlers/aliases/handlers" + "strings" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func WorkspaceExecuteCommand(context *glsp.Context, params *protocol.ExecuteCommandParams) (*protocol.ApplyWorkspaceEditParams, error) { + _, command, _ := strings.Cut(params.Command, ".") + + switch command { + case string(handlers.CodeActionSendTestMail): + args := handlers.CodeActionSendTestMailArgsFromArguments(params.Arguments[0].(map[string]any)) + + d := aliases.DocumentParserMap[args.URI] + + return args.RunCommand(d) + } + + return nil, nil +} diff --git a/handlers/aliases/shared.go b/server/handlers/aliases/shared.go similarity index 100% rename from handlers/aliases/shared.go rename to server/handlers/aliases/shared.go diff --git a/handlers/aliases/shared/errors.go b/server/handlers/aliases/shared/errors.go similarity index 100% rename from handlers/aliases/shared/errors.go rename to server/handlers/aliases/shared/errors.go diff --git a/handlers/fstab/documentation/documentation-freq.go b/server/handlers/fstab/documentation/documentation-freq.go similarity index 100% rename from handlers/fstab/documentation/documentation-freq.go rename to server/handlers/fstab/documentation/documentation-freq.go diff --git a/handlers/fstab/documentation/documentation-mount-point.go b/server/handlers/fstab/documentation/documentation-mount-point.go similarity index 91% rename from handlers/fstab/documentation/documentation-mount-point.go rename to server/handlers/fstab/documentation/documentation-mount-point.go index 958d80d..9de4c6d 100644 --- a/handlers/fstab/documentation/documentation-mount-point.go +++ b/server/handlers/fstab/documentation/documentation-mount-point.go @@ -6,7 +6,7 @@ import ( ) var MountPointField = docvalues.OrValue{ - Values: []docvalues.Value{ + Values: []docvalues.DeprecatedValue{ docvalues.EnumValue{ Values: []docvalues.EnumString{ { diff --git a/handlers/fstab/documentation/documentation-mountoptions.go b/server/handlers/fstab/documentation/documentation-mountoptions.go similarity index 97% rename from handlers/fstab/documentation/documentation-mountoptions.go rename to server/handlers/fstab/documentation/documentation-mountoptions.go index 019dd22..8c26b5f 100644 --- a/handlers/fstab/documentation/documentation-mountoptions.go +++ b/server/handlers/fstab/documentation/documentation-mountoptions.go @@ -195,10 +195,10 @@ var defaultOptions = []docvalues.EnumString{ type assignOption struct { Documentation string - Handler func(context docvalues.KeyValueAssignmentContext) docvalues.Value + Handler func(context docvalues.KeyValueAssignmentContext) docvalues.DeprecatedValue } -var defaultAssignOptions = map[docvalues.EnumString]docvalues.Value{ +var defaultAssignOptions = map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumStringWithDoc( "context", "The context= option is useful when mounting filesystems that do not support extended attributes, such as a floppy or hard disk formatted with VFAT, or systems that are not normally running under SELinux, such as an ext3 or ext4 formatted disk from a non-SELinux workstation. You can also use context= on filesystems you do not trust, such as a floppy. It also helps in compatibility with xattr-supporting filesystems on earlier 2.4. kernel versions. Even where xattrs are supported, you can save time not having to label every file by assigning the entire disk one security context. A commonly used option for removable media is context=\"system_u:object_r:removable_t\".", @@ -219,15 +219,15 @@ var defaultAssignOptions = map[docvalues.EnumString]docvalues.Value{ func createMountOptionField( options []docvalues.EnumString, - assignOption map[docvalues.EnumString]docvalues.Value, -) docvalues.Value { + assignOption map[docvalues.EnumString]docvalues.DeprecatedValue, +) docvalues.DeprecatedValue { dynamicOptions := docvalues.MergeKeyEnumAssignmentMaps(defaultAssignOptions, assignOption) return docvalues.ArrayValue{ Separator: ",", DuplicatesExtractor: &mountOptionsExtractor, SubValue: docvalues.OrValue{ - Values: []docvalues.Value{ + Values: []docvalues.DeprecatedValue{ docvalues.KeyEnumAssignmentValue{ Values: dynamicOptions, ValueIsOptional: false, @@ -242,9 +242,9 @@ func createMountOptionField( } } -var DefaultMountOptionsField = createMountOptionField([]docvalues.EnumString{}, map[docvalues.EnumString]docvalues.Value{}) +var DefaultMountOptionsField = createMountOptionField([]docvalues.EnumString{}, map[docvalues.EnumString]docvalues.DeprecatedValue{}) -var MountOptionsMapField = map[string]docvalues.Value{ +var MountOptionsMapField = map[string]docvalues.DeprecatedValue{ "adfs": createMountOptionField( commondocumentation.AdfsDocumentationEnums, commondocumentation.AdfsDocumentationAssignable, diff --git a/handlers/fstab/documentation/documentation-pass.go b/server/handlers/fstab/documentation/documentation-pass.go similarity index 94% rename from handlers/fstab/documentation/documentation-pass.go rename to server/handlers/fstab/documentation/documentation-pass.go index 9be2e39..6163c3b 100644 --- a/handlers/fstab/documentation/documentation-pass.go +++ b/server/handlers/fstab/documentation/documentation-pass.go @@ -3,7 +3,7 @@ package fstabdocumentation import docvalues "config-lsp/doc-values" var PassField = docvalues.OrValue{ - Values: []docvalues.Value{ + Values: []docvalues.DeprecatedValue{ docvalues.EnumValue{ EnforceValues: false, Values: []docvalues.EnumString{ diff --git a/handlers/fstab/documentation/documentation-spec.go b/server/handlers/fstab/documentation/documentation-spec.go similarity index 88% rename from handlers/fstab/documentation/documentation-spec.go rename to server/handlers/fstab/documentation/documentation-spec.go index 26a0901..f3087f5 100644 --- a/handlers/fstab/documentation/documentation-spec.go +++ b/server/handlers/fstab/documentation/documentation-spec.go @@ -13,14 +13,14 @@ var LabelField = docvalues.RegexValue{ } var SpecField = docvalues.OrValue{ - Values: []docvalues.Value{ + Values: []docvalues.DeprecatedValue{ // docvalues.PathValue{ // RequiredType: docvalues.PathTypeFile & docvalues.PathTypeExistenceOptional, // }, docvalues.KeyEnumAssignmentValue{ Separator: "=", ValueIsOptional: false, - Values: map[docvalues.EnumString]docvalues.Value{ + Values: map[docvalues.EnumString]docvalues.DeprecatedValue{ docvalues.CreateEnumString("UUID"): UuidField, docvalues.CreateEnumString("PARTUUID"): UuidField, docvalues.CreateEnumString("LABEL"): LabelField, diff --git a/handlers/fstab/documentation/documentation-type.go b/server/handlers/fstab/documentation/documentation-type.go similarity index 100% rename from handlers/fstab/documentation/documentation-type.go rename to server/handlers/fstab/documentation/documentation-type.go diff --git a/handlers/fstab/fstab_test.go b/server/handlers/fstab/fstab_test.go similarity index 58% rename from handlers/fstab/fstab_test.go rename to server/handlers/fstab/fstab_test.go index 4e6d47d..da39d0c 100644 --- a/handlers/fstab/fstab_test.go +++ b/server/handlers/fstab/fstab_test.go @@ -2,68 +2,65 @@ package fstab import ( fstabdocumentation "config-lsp/handlers/fstab/documentation" + handlers "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" "config-lsp/utils" "testing" ) -var sampleValidBasicExample = ` -LABEL=test /mnt/test ext4 defaults 0 0 -` -var sampleInvalidOptionsExample = ` -LABEL=test /mnt/test btrfs subvol=backup,fat=32 0 0 -` - -// TODO: Improve `entries`, sometimes the indexes seem -// to be wrong. Use a treemap instead of a map. func TestValidBasicExample(t *testing.T) { - // Arrange - parser := FstabParser{} + input := utils.Dedent(` +LABEL=test /mnt/test ext4 defaults 0 0 +`) + p := parser.FstabParser{} + p.Clear() - errors := parser.ParseFromContent(sampleValidBasicExample) + errors := p.ParseFromContent(input) if len(errors) > 0 { t.Fatal("ParseFromContent failed with error", errors) } // Get hover for first field - entry := parser.entries[0] + rawEntry, _ := p.Entries.Get(uint32(0)) + entry := rawEntry.(parser.FstabEntry) println("Getting hover info") { - hover, err := getHoverInfo(&entry, uint32(0)) + hover, err := handlers.GetHoverInfo(&entry, uint32(0)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != SpecHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", SpecHoverField.Contents) + if hover.Contents != handlers.SpecHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.SpecHoverField.Contents) } // Get hover for second field - hover, err = getHoverInfo(&entry, uint32(11)) + hover, err = handlers.GetHoverInfo(&entry, uint32(11)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != MountPointHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", MountPointHoverField.Contents) + if hover.Contents != handlers.MountPointHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.MountPointHoverField.Contents) } - hover, err = getHoverInfo(&entry, uint32(20)) + hover, err = handlers.GetHoverInfo(&entry, uint32(20)) if err != nil { t.Fatal("getHoverInfo failed with error", err) } - if hover.Contents != MountPointHoverField.Contents { - t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", MountPointHoverField.Contents) + if hover.Contents != handlers.MountPointHoverField.Contents { + t.Fatal("getHoverInfo failed to return correct hover content. Got:", hover.Contents, "but expected:", handlers.MountPointHoverField.Contents) } } println("Getting completions") { - completions, err := getCompletion(entry.Line, uint32(0)) + completions, err := handlers.GetCompletion(entry.Line, uint32(0)) if err != nil { t.Fatal("getCompletion failed with error", err) @@ -73,13 +70,16 @@ func TestValidBasicExample(t *testing.T) { t.Fatal("getCompletion failed to return correct number of completions. Got:", len(completions), "but expected:", 4) } - if completions[0].Label != "UUID" && completions[0].Label != "PARTUID" { - t.Fatal("getCompletion failed to return correct label. Got:", completions[0].Label, "but expected:", "UUID") + if !(completions[0].Label == "LABEL" || + completions[1].Label == "LABEL" || + completions[2].Label == "LABEL" || + completions[3].Label == "LABEL") { + t.Fatal("getCompletion failed to return correct label. Got:", completions[0].Label, "but expected:", "LABEL") } } { - completions, err := getCompletion(entry.Line, uint32(21)) + completions, err := handlers.GetCompletion(entry.Line, uint32(21)) if err != nil { t.Fatal("getCompletion failed with error", err) @@ -93,7 +93,7 @@ func TestValidBasicExample(t *testing.T) { println("Checking values") { - diagnostics := parser.AnalyzeValues() + diagnostics := p.AnalyzeValues() if len(diagnostics) > 0 { t.Fatal("AnalyzeValues failed with error", diagnostics) @@ -102,10 +102,13 @@ func TestValidBasicExample(t *testing.T) { } func TestInvalidOptionsExample(t *testing.T) { - // Arrange - parser := FstabParser{} + input := utils.Dedent(` +LABEL=test /mnt/test btrfs subvol=backup,fat=32 0 0 +`) + p := parser.FstabParser{} + p.Clear() - errors := parser.ParseFromContent(sampleInvalidOptionsExample) + errors := p.ParseFromContent(input) if len(errors) > 0 { t.Fatal("ParseFromContent returned error", errors) @@ -114,7 +117,7 @@ func TestInvalidOptionsExample(t *testing.T) { // Get hover for first field println("Checking values") { - diagnostics := parser.AnalyzeValues() + diagnostics := p.AnalyzeValues() if len(diagnostics) == 0 { t.Fatal("AnalyzeValues should have returned error") diff --git a/server/handlers/fstab/handlers/completions.go b/server/handlers/fstab/handlers/completions.go new file mode 100644 index 0000000..35b79e2 --- /dev/null +++ b/server/handlers/fstab/handlers/completions.go @@ -0,0 +1,88 @@ +package handlers + +import ( + "config-lsp/doc-values" + "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/parser" + "github.com/tliron/glsp/protocol_3_16" +) + +func GetCompletion( + line parser.FstabLine, + cursor uint32, +) ([]protocol.CompletionItem, error) { + targetField := line.GetFieldAtPosition(cursor) + + switch targetField { + case parser.FstabFieldSpec: + value, cursor := GetFieldSafely(line.Fields.Spec, cursor) + + return fstabdocumentation.SpecField.DeprecatedFetchCompletions( + value, + cursor, + ), nil + case parser.FstabFieldMountPoint: + value, cursor := GetFieldSafely(line.Fields.MountPoint, cursor) + + return fstabdocumentation.MountPointField.DeprecatedFetchCompletions( + value, + cursor, + ), nil + case parser.FstabFieldFileSystemType: + value, cursor := GetFieldSafely(line.Fields.FilesystemType, cursor) + + return fstabdocumentation.FileSystemTypeField.DeprecatedFetchCompletions( + value, + cursor, + ), nil + case parser.FstabFieldOptions: + fileSystemType := line.Fields.FilesystemType.Value + + var optionsField docvalues.DeprecatedValue + + if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found { + optionsField = foundField + } else { + optionsField = fstabdocumentation.DefaultMountOptionsField + } + + value, cursor := GetFieldSafely(line.Fields.Options, cursor) + + completions := optionsField.DeprecatedFetchCompletions( + value, + cursor, + ) + + return completions, nil + case parser.FstabFieldFreq: + value, cursor := GetFieldSafely(line.Fields.Freq, cursor) + + return fstabdocumentation.FreqField.DeprecatedFetchCompletions( + value, + cursor, + ), nil + case parser.FstabFieldPass: + value, cursor := GetFieldSafely(line.Fields.Pass, cursor) + + return fstabdocumentation.PassField.DeprecatedFetchCompletions( + value, + cursor, + ), nil + } + + return nil, nil +} + +// Safely get value and new cursor position +// If field is nil, return empty string and 0 +func GetFieldSafely(field *parser.Field, character uint32) (string, uint32) { + if field == nil { + return "", 0 + } + + if field.Value == "" { + return "", 0 + } + + return field.Value, character - field.Start +} diff --git a/handlers/fstab/hover-fields.go b/server/handlers/fstab/handlers/hover-fields.go similarity index 99% rename from handlers/fstab/hover-fields.go rename to server/handlers/fstab/handlers/hover-fields.go index 38a5aec..4310b52 100644 --- a/handlers/fstab/hover-fields.go +++ b/server/handlers/fstab/handlers/hover-fields.go @@ -1,4 +1,4 @@ -package fstab +package handlers import protocol "github.com/tliron/glsp/protocol_3_16" diff --git a/server/handlers/fstab/handlers/hover.go b/server/handlers/fstab/handlers/hover.go new file mode 100644 index 0000000..33fd213 --- /dev/null +++ b/server/handlers/fstab/handlers/hover.go @@ -0,0 +1,50 @@ +package handlers + +import ( + "config-lsp/doc-values" + "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/parser" + "github.com/tliron/glsp/protocol_3_16" + "strings" +) + +func GetHoverInfo(entry *parser.FstabEntry, cursor uint32) (*protocol.Hover, error) { + line := entry.Line + targetField := line.GetFieldAtPosition(cursor) + + switch targetField { + case parser.FstabFieldSpec: + return &SpecHoverField, nil + case parser.FstabFieldMountPoint: + return &MountPointHoverField, nil + case parser.FstabFieldFileSystemType: + return &FileSystemTypeField, nil + case parser.FstabFieldOptions: + fileSystemType := line.Fields.FilesystemType.Value + var optionsField docvalues.DeprecatedValue + + if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found { + optionsField = foundField + } else { + optionsField = fstabdocumentation.DefaultMountOptionsField + } + + relativeCursor := cursor - line.Fields.Options.Start + fieldInfo := optionsField.DeprecatedFetchHoverInfo(line.Fields.Options.Value, relativeCursor) + + hover := protocol.Hover{ + Contents: protocol.MarkupContent{ + Kind: protocol.MarkupKindMarkdown, + Value: strings.Join(fieldInfo, "\n"), + }, + } + + return &hover, nil + case parser.FstabFieldFreq: + return &FreqHoverField, nil + case parser.FstabFieldPass: + return &PassHoverField, nil + } + + return nil, nil +} diff --git a/server/handlers/fstab/lsp/text-document-completion.go b/server/handlers/fstab/lsp/text-document-completion.go new file mode 100644 index 0000000..55b585f --- /dev/null +++ b/server/handlers/fstab/lsp/text-document-completion.go @@ -0,0 +1,34 @@ +package lsp + +import ( + fstabdocumentation "config-lsp/handlers/fstab/documentation" + "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentCompletion(context *glsp.Context, params *protocol.CompletionParams) (any, error) { + p := shared.DocumentParserMap[params.TextDocument.URI] + + entry, found := p.GetEntry(params.Position.Line) + + if !found { + // Empty line, return spec completions + return fstabdocumentation.SpecField.DeprecatedFetchCompletions( + "", + params.Position.Character, + ), nil + } + + if entry.Type == parser.FstabEntryTypeComment { + return nil, nil + } + + cursor := params.Position.Character + line := entry.Line + + return handlers.GetCompletion(line, cursor) +} diff --git a/handlers/fstab/text-document-did-change.go b/server/handlers/fstab/lsp/text-document-did-change.go similarity index 76% rename from handlers/fstab/text-document-did-change.go rename to server/handlers/fstab/lsp/text-document-did-change.go index 8b465b3..2864e19 100644 --- a/handlers/fstab/text-document-did-change.go +++ b/server/handlers/fstab/lsp/text-document-did-change.go @@ -1,7 +1,8 @@ -package fstab +package lsp import ( "config-lsp/common" + "config-lsp/handlers/fstab/shared" "config-lsp/utils" "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" @@ -14,11 +15,11 @@ func TextDocumentDidChange( content := params.ContentChanges[0].(protocol.TextDocumentContentChangeEventWhole).Text common.ClearDiagnostics(context, params.TextDocument.URI) - parser := documentParserMap[params.TextDocument.URI] - parser.Clear() + p := shared.DocumentParserMap[params.TextDocument.URI] + p.Clear() diagnostics := make([]protocol.Diagnostic, 0) - errors := parser.ParseFromContent(content) + errors := p.ParseFromContent(content) if len(errors) > 0 { diagnostics = append(diagnostics, utils.Map( @@ -27,10 +28,10 @@ func TextDocumentDidChange( return err.ToDiagnostic() }, )...) + } else { + diagnostics = append(diagnostics, p.AnalyzeValues()...) } - diagnostics = append(diagnostics, parser.AnalyzeValues()...) - if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) } diff --git a/server/handlers/fstab/lsp/text-document-did-close.go b/server/handlers/fstab/lsp/text-document-did-close.go new file mode 100644 index 0000000..a602a65 --- /dev/null +++ b/server/handlers/fstab/lsp/text-document-did-close.go @@ -0,0 +1,13 @@ +package lsp + +import ( + shared "config-lsp/handlers/fstab/shared" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidClose(context *glsp.Context, params *protocol.DidCloseTextDocumentParams) error { + delete(shared.DocumentParserMap, params.TextDocument.URI) + + return nil +} diff --git a/server/handlers/fstab/lsp/text-document-did-open.go b/server/handlers/fstab/lsp/text-document-did-open.go new file mode 100644 index 0000000..6658b21 --- /dev/null +++ b/server/handlers/fstab/lsp/text-document-did-open.go @@ -0,0 +1,43 @@ +package lsp + +import ( + "config-lsp/common" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + "config-lsp/utils" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentDidOpen( + context *glsp.Context, + params *protocol.DidOpenTextDocumentParams, +) error { + common.ClearDiagnostics(context, params.TextDocument.URI) + + p := parser.FstabParser{} + p.Clear() + shared.DocumentParserMap[params.TextDocument.URI] = &p + + content := params.TextDocument.Text + + diagnostics := make([]protocol.Diagnostic, 0) + errors := p.ParseFromContent(content) + + if len(errors) > 0 { + diagnostics = append(diagnostics, utils.Map( + errors, + func(err common.ParseError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + )...) + } else { + diagnostics = append(diagnostics, p.AnalyzeValues()...) + } + + if len(diagnostics) > 0 { + common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) + } + + return nil +} diff --git a/server/handlers/fstab/lsp/text-document-hover.go b/server/handlers/fstab/lsp/text-document-hover.go new file mode 100644 index 0000000..310706e --- /dev/null +++ b/server/handlers/fstab/lsp/text-document-hover.go @@ -0,0 +1,29 @@ +package lsp + +import ( + "config-lsp/handlers/fstab/handlers" + "config-lsp/handlers/fstab/parser" + "config-lsp/handlers/fstab/shared" + "github.com/tliron/glsp" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TextDocumentHover(context *glsp.Context, params *protocol.HoverParams) (*protocol.Hover, error) { + cursor := params.Position.Character + + p := shared.DocumentParserMap[params.TextDocument.URI] + + entry, found := p.GetEntry(params.Position.Line) + + // Empty line + if !found { + return nil, nil + } + + // Comment line + if entry.Type == parser.FstabEntryTypeComment { + return nil, nil + } + + return handlers.GetHoverInfo(entry, cursor) +} diff --git a/handlers/fstab/parser.go b/server/handlers/fstab/parser/parser.go similarity index 87% rename from handlers/fstab/parser.go rename to server/handlers/fstab/parser/parser.go index 782f346..a57165a 100644 --- a/handlers/fstab/parser.go +++ b/server/handlers/fstab/parser/parser.go @@ -1,4 +1,4 @@ -package fstab +package parser import ( "config-lsp/common" @@ -6,10 +6,12 @@ import ( fstabdocumentation "config-lsp/handlers/fstab/documentation" "fmt" "regexp" - "slices" "strings" + "github.com/emirpasic/gods/maps/treemap" protocol "github.com/tliron/glsp/protocol_3_16" + + gods "github.com/emirpasic/gods/utils" ) var commentPattern = regexp.MustCompile(`^\s*#`) @@ -86,7 +88,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { diagnostics := make([]protocol.Diagnostic, 0) if e.Fields.Spec != nil { - errors := fstabdocumentation.SpecField.CheckIsValid(e.Fields.Spec.Value) + errors := fstabdocumentation.SpecField.DeprecatedCheckIsValid(e.Fields.Spec.Value) if len(errors) > 0 { diagnostics = append( @@ -97,7 +99,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { } if e.Fields.MountPoint != nil { - errors := fstabdocumentation.MountPointField.CheckIsValid(e.Fields.MountPoint.Value) + errors := fstabdocumentation.MountPointField.DeprecatedCheckIsValid(e.Fields.MountPoint.Value) if len(errors) > 0 { diagnostics = append( @@ -110,7 +112,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { var fileSystemType string = "" if e.Fields.FilesystemType != nil { - errors := fstabdocumentation.FileSystemTypeField.CheckIsValid(e.Fields.FilesystemType.Value) + errors := fstabdocumentation.FileSystemTypeField.DeprecatedCheckIsValid(e.Fields.FilesystemType.Value) if len(errors) > 0 { diagnostics = append( @@ -123,7 +125,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { } if e.Fields.Options != nil && fileSystemType != "" { - var optionsField docvalues.Value + var optionsField docvalues.DeprecatedValue if foundField, found := fstabdocumentation.MountOptionsMapField[fileSystemType]; found { optionsField = foundField @@ -131,7 +133,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { optionsField = fstabdocumentation.DefaultMountOptionsField } - errors := optionsField.CheckIsValid(e.Fields.Options.Value) + errors := optionsField.DeprecatedCheckIsValid(e.Fields.Options.Value) if len(errors) > 0 { diagnostics = append( @@ -142,7 +144,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { } if e.Fields.Freq != nil { - errors := fstabdocumentation.FreqField.CheckIsValid(e.Fields.Freq.Value) + errors := fstabdocumentation.FreqField.DeprecatedCheckIsValid(e.Fields.Freq.Value) if len(errors) > 0 { diagnostics = append( @@ -153,7 +155,7 @@ func (e *FstabLine) CheckIsValid() []protocol.Diagnostic { } if e.Fields.Pass != nil { - errors := fstabdocumentation.PassField.CheckIsValid(e.Fields.Pass.Value) + errors := fstabdocumentation.PassField.DeprecatedCheckIsValid(e.Fields.Pass.Value) if len(errors) > 0 { diagnostics = append( @@ -203,7 +205,8 @@ type FstabEntry struct { } type FstabParser struct { - entries []FstabEntry + // [uint32]FstabEntry - line number to entry mapping + Entries *treemap.Map } func (p *FstabParser) AddLine(line string, lineNumber int) error { @@ -302,7 +305,7 @@ func (p *FstabParser) AddLine(line string, lineNumber int) error { }, }, } - p.entries = append(p.entries, entry) + p.Entries.Put(entry.Line.Line, entry) return nil } @@ -311,7 +314,7 @@ func (p *FstabParser) AddCommentLine(line string, lineNumber int) { entry := FstabLine{ Line: uint32(lineNumber), } - p.entries = append(p.entries, FstabEntry{ + p.Entries.Put(entry.Line, FstabEntry{ Type: FstabEntryTypeComment, Line: entry, }) @@ -345,33 +348,29 @@ func (p *FstabParser) ParseFromContent(content string) []common.ParseError { } func (p *FstabParser) GetEntry(line uint32) (*FstabEntry, bool) { - index, found := slices.BinarySearchFunc(p.entries, line, func(entry FstabEntry, line uint32) int { - if entry.Line.Line < line { - return -1 - } - - if entry.Line.Line > line { - return 1 - } - - return 0 - }) + rawEntry, found := p.Entries.Get(line) if !found { return nil, false } - return &p.entries[index], true + entry := rawEntry.(FstabEntry) + + return &entry, true } func (p *FstabParser) Clear() { - p.entries = []FstabEntry{} + p.Entries = treemap.NewWith(gods.UInt32Comparator) } func (p *FstabParser) AnalyzeValues() []protocol.Diagnostic { diagnostics := []protocol.Diagnostic{} - for _, entry := range p.entries { + it := p.Entries.Iterator() + + for it.Next() { + entry := it.Value().(FstabEntry) + switch entry.Type { case FstabEntryTypeLine: newDiagnostics := entry.Line.CheckIsValid() diff --git a/server/handlers/fstab/shared/document.go b/server/handlers/fstab/shared/document.go new file mode 100644 index 0000000..e25de3b --- /dev/null +++ b/server/handlers/fstab/shared/document.go @@ -0,0 +1,8 @@ +package shared + +import ( + "config-lsp/handlers/fstab/parser" + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var DocumentParserMap = map[protocol.DocumentUri]*parser.FstabParser{} diff --git a/handlers/hosts/Hosts.g4 b/server/handlers/hosts/Hosts.g4 similarity index 75% rename from handlers/hosts/Hosts.g4 rename to server/handlers/hosts/Hosts.g4 index 7690ee3..236674b 100644 --- a/handlers/hosts/Hosts.g4 +++ b/server/handlers/hosts/Hosts.g4 @@ -13,7 +13,7 @@ aliases ; alias - : DOMAIN + : domain ; hostname @@ -21,17 +21,26 @@ hostname ; domain - : DOMAIN + : (STRING)+ (DOT STRING*)* ; ipAddress : (ipv4Address | ipv6Address) ; +ipv4Address + : (STRING DOT)+ STRING (ipRange? | ipPort?) + ; + +ipv6Address + : (((STRING COLON)+ STRING) | (STRING? COLON COLON STRING)) (ipRange? | ipPort?) + ; + +/* ipv4Address : singleIPv4Address // Allow optional range to tell user ranges are not allowed - ipRange? + (ipRange? | ipPort?) ; singleIPv4Address @@ -42,7 +51,7 @@ singleIPv4Address ipv6Address : singleIPv6Address // Allow optional range to tell user ranges are not allowed - ipRange? + (ipRange? | ipPort?) ; singleIPv6Address @@ -50,19 +59,24 @@ singleIPv6Address ; ipv4Digit - : DIGITS + : STRING ; ipv6Octet - : OCTETS + : STRING ; +*/ ipRange : SLASH ipRangeBits ; ipRangeBits - : DIGITS + : STRING + ; + +ipPort + : COLON STRING ; comment @@ -101,26 +115,6 @@ NEWLINE : [\r]? [\n] ; -DIGITS - : DIGIT+ - ; - -fragment DIGIT - : [0-9] - ; - -OCTETS - : OCTET+ - ; - -fragment OCTET - : [0-9a-fA-F] - ; - -DOMAIN - : ((STRING)+ (DOT [a-zA-Z]+)*) - ; - -fragment STRING - : ~(' ' | '\t' | '\n' | '\r' | '#' | '.') +STRING + : [a-zA-Z0-9_\-]+ ; diff --git a/handlers/hosts/analyzer/analyzer.go b/server/handlers/hosts/analyzer/analyzer.go similarity index 100% rename from handlers/hosts/analyzer/analyzer.go rename to server/handlers/hosts/analyzer/analyzer.go diff --git a/handlers/hosts/analyzer/double_ips.go b/server/handlers/hosts/analyzer/double_ips.go similarity index 74% rename from handlers/hosts/analyzer/double_ips.go rename to server/handlers/hosts/analyzer/double_ips.go index 4fcd2f4..8ad1bbf 100644 --- a/handlers/hosts/analyzer/double_ips.go +++ b/server/handlers/hosts/analyzer/double_ips.go @@ -3,10 +3,9 @@ package analyzer import ( "config-lsp/common" "config-lsp/handlers/hosts" + "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/shared" - "config-lsp/utils" "net" - "slices" ) func ipToString(ip net.IPAddr) string { @@ -19,14 +18,11 @@ func analyzeDoubleIPs(d *hosts.HostsDocument) []common.LSPError { d.Indexes.DoubleIPs = make(map[uint32]shared.DuplicateIPDeclaration) - // TODO: `range` does not seem to properly - // iterate in a sorted way. - // Instead, use a treemap - lines := utils.KeysOfMap(d.Parser.Tree.Entries) - slices.Sort(lines) + it := d.Parser.Tree.Entries.Iterator() - for _, lineNumber := range lines { - entry := d.Parser.Tree.Entries[lineNumber] + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) if entry.IPAddress != nil { key := ipToString(entry.IPAddress.Value) diff --git a/handlers/hosts/analyzer/double_ips_test.go b/server/handlers/hosts/analyzer/double_ips_test.go similarity index 100% rename from handlers/hosts/analyzer/double_ips_test.go rename to server/handlers/hosts/analyzer/double_ips_test.go diff --git a/server/handlers/hosts/analyzer/handler_test.go b/server/handlers/hosts/analyzer/handler_test.go new file mode 100644 index 0000000..b7182a2 --- /dev/null +++ b/server/handlers/hosts/analyzer/handler_test.go @@ -0,0 +1,151 @@ +package analyzer + +import ( + "config-lsp/handlers/hosts/ast" + "config-lsp/utils" + "net" + "testing" +) + +func TestValidSimpleExampleWorks( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4 hello.com + `) + + parser := ast.NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(parser.Tree.Entries.Size() == 1) { + t.Errorf("Expected 1 entry, but got %v", parser.Tree.Entries.Size()) + } + + rawEntry, found := parser.Tree.Entries.Get(uint32(0)) + if !found { + t.Fatalf("Expected IP address to be present, but got nil") + } + + entry := rawEntry.(*ast.HostsEntry) + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) + } + + if !(entry.Hostname.Value == "hello.com") { + t.Errorf("Expected hostname to be hello.com, but got %v", entry.Hostname.Value) + } + + if !(entry.Aliases == nil) { + t.Errorf("Expected no aliases, but got %v", entry.Aliases) + } + + if !(entry.Location.Start.Line == 0) { + t.Errorf("Expected line to be 1, but got %v", entry.Location.Start.Line) + } + + if !(entry.Location.Start.Character == 0) { + t.Errorf("Expected start to be 0, but got %v", entry.Location.Start) + } + + if !(entry.Location.End.Character == 17) { + t.Errorf("Expected end to be 17, but got %v", entry.Location.End.Character) + } + + if !(entry.IPAddress.Location.Start.Line == 0) { + t.Errorf("Expected IP address line to be 1, but got %v", entry.IPAddress.Location.Start.Line) + } + + if !(entry.IPAddress.Location.Start.Character == 0) { + t.Errorf("Expected IP address start to be 0, but got %v", entry.IPAddress.Location.Start.Character) + } + + if !(entry.IPAddress.Location.End.Character == 7) { + t.Errorf("Expected IP address end to be 7, but got %v", entry.IPAddress.Location.End.Character) + } + + if !(len(parser.CommentLines) == 0) { + t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines)) + } +} + +func TestValidComplexExampleWorks( + t *testing.T, +) { + input := utils.Dedent(` + +# This is a comment +1.2.3.4 hello.com test.com # This is another comment +5.5.5.5 test.com +1.2.3.4 example.com check.com +`) + + parser := ast.NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(parser.Tree.Entries.Size() == 3) { + t.Fatalf("Expected 3 entries, but got %v", parser.Tree.Entries.Size()) + } + + rawEntry, _ := parser.Tree.Entries.Get(uint32(2)) + entry := rawEntry.(*ast.HostsEntry) + if entry.IPAddress == nil { + t.Errorf("Expected IP address to be present, but got nil") + } + + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) + } + + if !(len(parser.CommentLines) == 1) { + t.Errorf("Expected 1 comment line, but got %v", len(parser.CommentLines)) + } + + if !(utils.KeyExists(parser.CommentLines, 1)) { + t.Errorf("Expected comment line 2 to exist, but it does not") + } +} + +func TestInvalidExampleWorks( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4 + `) + + parser := ast.NewHostsParser() + errors := parser.Parse(input) + + if len(errors) == 0 { + t.Fatalf("Expected errors, but got none") + } + + if !(parser.Tree.Entries.Size() == 1) { + t.Errorf("Expected 1 entries, but got %v", parser.Tree.Entries.Size()) + } + + if !(len(parser.CommentLines) == 0) { + t.Errorf("Expected no comment lines, but got %v", len(parser.CommentLines)) + } + + rawEntry, _ := parser.Tree.Entries.Get(uint32(0)) + entry := rawEntry.(*ast.HostsEntry) + if !(entry.IPAddress.Value.String() == net.ParseIP("1.2.3.4").String()) { + t.Errorf("Expected IP address to be nil, but got %v", entry.IPAddress) + } + + if !(entry.Hostname == nil) { + t.Errorf("Expected hostname to be nil, but got %v", entry.Hostname) + } + + if !(entry.Aliases == nil) { + t.Errorf("Expected aliases to be nil, but got %v", entry.Aliases) + } +} diff --git a/handlers/hosts/analyzer/resolve.go b/server/handlers/hosts/analyzer/resolver.go similarity index 73% rename from handlers/hosts/analyzer/resolve.go rename to server/handlers/hosts/analyzer/resolver.go index 846af98..bedbfe5 100644 --- a/handlers/hosts/analyzer/resolve.go +++ b/server/handlers/hosts/analyzer/resolver.go @@ -19,9 +19,9 @@ func createEntry( } if ipv4 := ip.To4(); ipv4 != nil { - entry.IPv4Address = ipv4 + entry.IPv4Address = &ipv4 } else if ipv6 := ip.To16(); ipv6 != nil { - entry.IPv6Address = ipv6 + entry.IPv6Address = &ipv6 } return entry @@ -35,10 +35,15 @@ type hostnameEntry struct { func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSPError) { errors := make([]common.LSPError, 0) resolver := indexes.Resolver{ - Entries: make(map[string]indexes.ResolverEntry), + Entries: make(map[string]*indexes.ResolverEntry), } - for lineNumber, entry := range p.Tree.Entries { + it := p.Tree.Entries.Iterator() + + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) + if entry.IPAddress != nil && entry.Hostname != nil { hostNames := append( []hostnameEntry{ @@ -59,12 +64,22 @@ func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSP ) for _, hostName := range hostNames { - entry := createEntry( + newResolv := createEntry( lineNumber, entry.IPAddress.Value.IP, ) if resolv, found := resolver.Entries[hostName.HostName]; found { + if resolv.IPv4Address == nil && newResolv.IPv4Address != nil { + resolv.IPv4Address = newResolv.IPv4Address + continue + } + + if resolv.IPv6Address == nil && newResolv.IPv6Address != nil { + resolv.IPv6Address = newResolv.IPv6Address + continue + } + errors = append( errors, common.LSPError{ @@ -75,9 +90,10 @@ func createResolverFromParser(p ast.HostsParser) (indexes.Resolver, []common.LSP }, }, ) - } else { - resolver.Entries[hostName.HostName] = entry + continue } + + resolver.Entries[hostName.HostName] = &newResolv } } } diff --git a/handlers/hosts/analyzer/resolver_test.go b/server/handlers/hosts/analyzer/resolver_test.go similarity index 75% rename from handlers/hosts/analyzer/resolver_test.go rename to server/handlers/hosts/analyzer/resolver_test.go index df720e7..d4deb2f 100644 --- a/handlers/hosts/analyzer/resolver_test.go +++ b/server/handlers/hosts/analyzer/resolver_test.go @@ -96,7 +96,7 @@ func TestResolverEntriesWithComplexOverlapping( resolver, errors := createResolverFromParser(parser) if !(len(errors) == 1) { - t.Errorf("Expected 1 error, but got %v", len(errors)) + t.Fatalf("Expected 1 error, but got %v", len(errors)) } if len(resolver.Entries) != 3 { @@ -115,3 +115,36 @@ func TestResolverEntriesWithComplexOverlapping( t.Errorf("Expected test.com to have no IPv4 address, but got %v", resolver.Entries["test.com"].IPv4Address) } } + +func TestResolverEntriesWithDoubleHostNameButDifferentIPs( + t *testing.T, +) { + input := utils.Dedent(` +127.0.0.1 hello.com +::1 hello.com +`) + parser := ast.NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("PARER FAILED! Expected no errors, but got %v", errors) + } + + resolver, errors := createResolverFromParser(parser) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if len(resolver.Entries) != 1 { + t.Errorf("Expected 1 entry, but got %v", len(resolver.Entries)) + } + + if !(resolver.Entries["hello.com"].IPv4Address.String() == "127.0.0.1") { + t.Errorf("Expected hello.com's ipv4 address to be 127.0.0.1, but got %v", resolver.Entries["hello.com"].IPv4Address) + } + + if !(resolver.Entries["hello.com"].IPv6Address.String() == "::1") { + t.Errorf("Expected hello.com's ipv6 address to be ::1, but got %v", resolver.Entries["hello.com"].IPv6Address) + } +} diff --git a/handlers/hosts/analyzer/values.go b/server/handlers/hosts/analyzer/values.go similarity index 77% rename from handlers/hosts/analyzer/values.go rename to server/handlers/hosts/analyzer/values.go index e6da88e..8dfadcb 100644 --- a/handlers/hosts/analyzer/values.go +++ b/server/handlers/hosts/analyzer/values.go @@ -14,7 +14,12 @@ func analyzeEntriesSetCorrectly( ) []common.LSPError { err := make([]common.LSPError, 0) - for lineNumber, entry := range parser.Tree.Entries { + it := parser.Tree.Entries.Iterator() + + for it.Next() { + lineNumber := it.Key().(uint32) + entry := it.Value().(*ast.HostsEntry) + if entry.IPAddress == nil { err = append(err, common.LSPError{ Range: common.CreateFullLineRange(lineNumber), @@ -40,11 +45,15 @@ func analyzeEntriesAreValid( ) []common.LSPError { err := make([]common.LSPError, 0) - for _, entry := range parser.Tree.Entries { + it := parser.Tree.Entries.Iterator() + + for it.Next() { + entry := it.Value().(*ast.HostsEntry) + err = append( err, utils.Map( - fields.IPAddressField.CheckIsValid(entry.IPAddress.Value.String()), + fields.IPAddressField.DeprecatedCheckIsValid(entry.IPAddress.Value.String()), func(val *docvalues.InvalidValue) common.LSPError { return common.LSPError{ Range: entry.IPAddress.Location, @@ -57,7 +66,7 @@ func analyzeEntriesAreValid( err = append( err, utils.Map( - fields.HostnameField.CheckIsValid(entry.Hostname.Value), + fields.HostnameField.DeprecatedCheckIsValid(entry.Hostname.Value), func(val *docvalues.InvalidValue) common.LSPError { return common.LSPError{ Range: entry.Hostname.Location, @@ -71,7 +80,7 @@ func analyzeEntriesAreValid( err = append( err, utils.Map( - fields.HostnameField.CheckIsValid(alias.Value), + fields.HostnameField.DeprecatedCheckIsValid(alias.Value), func(val *docvalues.InvalidValue) common.LSPError { return common.LSPError{ Range: alias.Location, diff --git a/handlers/hosts/ast/hosts.go b/server/handlers/hosts/ast/hosts.go similarity index 92% rename from handlers/hosts/ast/hosts.go rename to server/handlers/hosts/ast/hosts.go index 5f28219..99b8fa0 100644 --- a/handlers/hosts/ast/hosts.go +++ b/server/handlers/hosts/ast/hosts.go @@ -4,6 +4,8 @@ import ( "config-lsp/common" "fmt" "net" + + "github.com/emirpasic/gods/maps/treemap" ) type HostsParser struct { @@ -13,7 +15,7 @@ type HostsParser struct { type HostsTree struct { // [line]entry - Entries map[uint32]*HostsEntry + Entries *treemap.Map } type HostsEntry struct { diff --git a/handlers/hosts/ast/listener.go b/server/handlers/hosts/ast/listener.go similarity index 77% rename from handlers/hosts/ast/listener.go rename to server/handlers/hosts/ast/listener.go index dd26bb6..6bcf3f1 100644 --- a/handlers/hosts/ast/listener.go +++ b/server/handlers/hosts/ast/listener.go @@ -4,7 +4,9 @@ import ( "config-lsp/common" docvalues "config-lsp/doc-values" parser2 "config-lsp/handlers/hosts/ast/parser" + "errors" "net" + "regexp" "github.com/antlr4-go/antlr/v4" ) @@ -21,7 +23,7 @@ type hostsParserListener struct { } func (s *hostsParserListener) EnterComment(ctx *parser2.CommentContext) { - line := uint32(s.hostsContext.line) + line := s.hostsContext.line s.Parser.CommentLines[line] = struct{}{} } @@ -29,11 +31,13 @@ func (s *hostsParserListener) EnterEntry(ctx *parser2.EntryContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - s.Parser.Tree.Entries[location.Start.Line] = &HostsEntry{ + s.Parser.Tree.Entries.Put(location.Start.Line, &HostsEntry{ Location: location, - } + }) } +var containsPortPattern = regexp.MustCompile(`:[0-9]+$`) + func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) @@ -41,10 +45,18 @@ func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { ip := net.ParseIP(ctx.GetText()) if ip == nil { - s.Errors = append(s.Errors, common.LSPError{ - Range: location, - Err: docvalues.InvalidIPAddress{}, - }) + if containsPortPattern.MatchString(ctx.GetText()) { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: errors.New("Port numbers are not allowed in IP addresses"), + }) + } else { + s.Errors = append(s.Errors, common.LSPError{ + Range: location, + Err: docvalues.InvalidIPAddress{}, + }) + } + return } @@ -57,7 +69,8 @@ func (s *hostsParserListener) EnterIpAddress(ctx *parser2.IpAddressContext) { }) } - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) entry.IPAddress = &HostsIPAddress{ Location: location, @@ -69,21 +82,21 @@ func (s *hostsParserListener) EnterHostname(ctx *parser2.HostnameContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) entry.Hostname = &HostsHostname{ Location: location, Value: ctx.GetText(), } - - s.Parser.Tree.Entries[location.Start.Line] = entry } func (s *hostsParserListener) EnterAliases(ctx *parser2.AliasesContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) aliases := make([]*HostsHostname, 0) @@ -94,7 +107,8 @@ func (s *hostsParserListener) EnterAlias(ctx *parser2.AliasContext) { location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) location.ChangeBothLines(s.hostsContext.line) - entry := s.Parser.Tree.Entries[location.Start.Line] + rawEntry, _ := s.Parser.Tree.Entries.Get(location.Start.Line) + entry := rawEntry.(*HostsEntry) alias := HostsHostname{ Location: location, diff --git a/handlers/hosts/ast/parser.go b/server/handlers/hosts/ast/parser.go similarity index 90% rename from handlers/hosts/ast/parser.go rename to server/handlers/hosts/ast/parser.go index bfdcf82..99b760c 100644 --- a/handlers/hosts/ast/parser.go +++ b/server/handlers/hosts/ast/parser.go @@ -7,11 +7,14 @@ import ( "regexp" "github.com/antlr4-go/antlr/v4" + "github.com/emirpasic/gods/maps/treemap" + + gods "github.com/emirpasic/gods/utils" ) func (p *HostsParser) Clear() { p.Tree = HostsTree{ - Entries: make(map[uint32]*HostsEntry), + Entries: treemap.NewWith(gods.UInt32Comparator), } p.CommentLines = make(map[uint32]struct{}) } @@ -44,6 +47,7 @@ func (p *HostsParser) parseStatement( antlrParser.LineStatement(), ) + errors = append(errors, listener.Errors...) errors = append(errors, errorListener.Errors...) return errors diff --git a/server/handlers/hosts/ast/parser/Hosts.interp b/server/handlers/hosts/ast/parser/Hosts.interp new file mode 100644 index 0000000..61da0c5 --- /dev/null +++ b/server/handlers/hosts/ast/parser/Hosts.interp @@ -0,0 +1,41 @@ +token literal names: +null +null +'/' +'.' +':' +'#' +null +null +null + +token symbolic names: +null +COMMENTLINE +SLASH +DOT +COLON +HASHTAG +SEPARATOR +NEWLINE +STRING + +rule names: +lineStatement +entry +aliases +alias +hostname +domain +ipAddress +ipv4Address +ipv6Address +ipRange +ipRangeBits +ipPort +comment +leadingComment + + +atn: +[4, 1, 8, 131, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 1, 0, 3, 0, 30, 8, 0, 1, 0, 1, 0, 3, 0, 34, 8, 0, 1, 0, 3, 0, 37, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 46, 8, 1, 1, 2, 1, 2, 3, 2, 50, 8, 2, 4, 2, 52, 8, 2, 11, 2, 12, 2, 53, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 61, 8, 5, 11, 5, 12, 5, 62, 1, 5, 1, 5, 5, 5, 67, 8, 5, 10, 5, 12, 5, 70, 9, 5, 5, 5, 72, 8, 5, 10, 5, 12, 5, 75, 9, 5, 1, 6, 1, 6, 3, 6, 79, 8, 6, 1, 7, 1, 7, 4, 7, 83, 8, 7, 11, 7, 12, 7, 84, 1, 7, 1, 7, 3, 7, 89, 8, 7, 1, 7, 3, 7, 92, 8, 7, 3, 7, 94, 8, 7, 1, 8, 1, 8, 4, 8, 98, 8, 8, 11, 8, 12, 8, 99, 1, 8, 1, 8, 3, 8, 104, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 109, 8, 8, 1, 8, 3, 8, 112, 8, 8, 1, 8, 3, 8, 115, 8, 8, 3, 8, 117, 8, 8, 1, 9, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 0, 0, 14, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 0, 0, 136, 0, 29, 1, 0, 0, 0, 2, 40, 1, 0, 0, 0, 4, 51, 1, 0, 0, 0, 6, 55, 1, 0, 0, 0, 8, 57, 1, 0, 0, 0, 10, 60, 1, 0, 0, 0, 12, 78, 1, 0, 0, 0, 14, 82, 1, 0, 0, 0, 16, 108, 1, 0, 0, 0, 18, 118, 1, 0, 0, 0, 20, 121, 1, 0, 0, 0, 22, 123, 1, 0, 0, 0, 24, 126, 1, 0, 0, 0, 26, 128, 1, 0, 0, 0, 28, 30, 5, 6, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 3, 2, 1, 0, 32, 34, 5, 6, 0, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 26, 13, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 5, 0, 0, 1, 39, 1, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 42, 5, 6, 0, 0, 42, 45, 3, 8, 4, 0, 43, 44, 5, 6, 0, 0, 44, 46, 3, 4, 2, 0, 45, 43, 1, 0, 0, 0, 45, 46, 1, 0, 0, 0, 46, 3, 1, 0, 0, 0, 47, 49, 3, 6, 3, 0, 48, 50, 5, 6, 0, 0, 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 52, 1, 0, 0, 0, 51, 47, 1, 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, 5, 1, 0, 0, 0, 55, 56, 3, 10, 5, 0, 56, 7, 1, 0, 0, 0, 57, 58, 3, 10, 5, 0, 58, 9, 1, 0, 0, 0, 59, 61, 5, 8, 0, 0, 60, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 73, 1, 0, 0, 0, 64, 68, 5, 3, 0, 0, 65, 67, 5, 8, 0, 0, 66, 65, 1, 0, 0, 0, 67, 70, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 72, 1, 0, 0, 0, 70, 68, 1, 0, 0, 0, 71, 64, 1, 0, 0, 0, 72, 75, 1, 0, 0, 0, 73, 71, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 11, 1, 0, 0, 0, 75, 73, 1, 0, 0, 0, 76, 79, 3, 14, 7, 0, 77, 79, 3, 16, 8, 0, 78, 76, 1, 0, 0, 0, 78, 77, 1, 0, 0, 0, 79, 13, 1, 0, 0, 0, 80, 81, 5, 8, 0, 0, 81, 83, 5, 3, 0, 0, 82, 80, 1, 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 82, 1, 0, 0, 0, 84, 85, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 93, 5, 8, 0, 0, 87, 89, 3, 18, 9, 0, 88, 87, 1, 0, 0, 0, 88, 89, 1, 0, 0, 0, 89, 94, 1, 0, 0, 0, 90, 92, 3, 22, 11, 0, 91, 90, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 94, 1, 0, 0, 0, 93, 88, 1, 0, 0, 0, 93, 91, 1, 0, 0, 0, 94, 15, 1, 0, 0, 0, 95, 96, 5, 8, 0, 0, 96, 98, 5, 4, 0, 0, 97, 95, 1, 0, 0, 0, 98, 99, 1, 0, 0, 0, 99, 97, 1, 0, 0, 0, 99, 100, 1, 0, 0, 0, 100, 101, 1, 0, 0, 0, 101, 109, 5, 8, 0, 0, 102, 104, 5, 8, 0, 0, 103, 102, 1, 0, 0, 0, 103, 104, 1, 0, 0, 0, 104, 105, 1, 0, 0, 0, 105, 106, 5, 4, 0, 0, 106, 107, 5, 4, 0, 0, 107, 109, 5, 8, 0, 0, 108, 97, 1, 0, 0, 0, 108, 103, 1, 0, 0, 0, 109, 116, 1, 0, 0, 0, 110, 112, 3, 18, 9, 0, 111, 110, 1, 0, 0, 0, 111, 112, 1, 0, 0, 0, 112, 117, 1, 0, 0, 0, 113, 115, 3, 22, 11, 0, 114, 113, 1, 0, 0, 0, 114, 115, 1, 0, 0, 0, 115, 117, 1, 0, 0, 0, 116, 111, 1, 0, 0, 0, 116, 114, 1, 0, 0, 0, 117, 17, 1, 0, 0, 0, 118, 119, 5, 2, 0, 0, 119, 120, 3, 20, 10, 0, 120, 19, 1, 0, 0, 0, 121, 122, 5, 8, 0, 0, 122, 21, 1, 0, 0, 0, 123, 124, 5, 4, 0, 0, 124, 125, 5, 8, 0, 0, 125, 23, 1, 0, 0, 0, 126, 127, 5, 1, 0, 0, 127, 25, 1, 0, 0, 0, 128, 129, 5, 1, 0, 0, 129, 27, 1, 0, 0, 0, 20, 29, 33, 36, 45, 49, 53, 62, 68, 73, 78, 84, 88, 91, 93, 99, 103, 108, 111, 114, 116] \ No newline at end of file diff --git a/handlers/hosts/ast/parser/Hosts.tokens b/server/handlers/hosts/ast/parser/Hosts.tokens similarity index 76% rename from handlers/hosts/ast/parser/Hosts.tokens rename to server/handlers/hosts/ast/parser/Hosts.tokens index c20b3c1..d53da5d 100644 --- a/handlers/hosts/ast/parser/Hosts.tokens +++ b/server/handlers/hosts/ast/parser/Hosts.tokens @@ -5,9 +5,7 @@ COLON=4 HASHTAG=5 SEPARATOR=6 NEWLINE=7 -DIGITS=8 -OCTETS=9 -DOMAIN=10 +STRING=8 '/'=2 '.'=3 ':'=4 diff --git a/server/handlers/hosts/ast/parser/HostsLexer.interp b/server/handlers/hosts/ast/parser/HostsLexer.interp new file mode 100644 index 0000000..624bd70 --- /dev/null +++ b/server/handlers/hosts/ast/parser/HostsLexer.interp @@ -0,0 +1,41 @@ +token literal names: +null +null +'/' +'.' +':' +'#' +null +null +null + +token symbolic names: +null +COMMENTLINE +SLASH +DOT +COLON +HASHTAG +SEPARATOR +NEWLINE +STRING + +rule names: +COMMENTLINE +SLASH +DOT +COLON +HASHTAG +SEPARATOR +NEWLINE +STRING + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 8, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 1, 0, 1, 0, 4, 0, 20, 8, 0, 11, 0, 12, 0, 21, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 33, 8, 5, 11, 5, 12, 5, 34, 1, 6, 3, 6, 38, 8, 6, 1, 6, 1, 6, 1, 7, 4, 7, 43, 8, 7, 11, 7, 12, 7, 44, 0, 0, 8, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8, 1, 0, 5, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 5, 0, 45, 45, 48, 57, 65, 90, 95, 95, 97, 122, 49, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 1, 17, 1, 0, 0, 0, 3, 23, 1, 0, 0, 0, 5, 25, 1, 0, 0, 0, 7, 27, 1, 0, 0, 0, 9, 29, 1, 0, 0, 0, 11, 32, 1, 0, 0, 0, 13, 37, 1, 0, 0, 0, 15, 42, 1, 0, 0, 0, 17, 19, 3, 9, 4, 0, 18, 20, 8, 0, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 2, 1, 0, 0, 0, 23, 24, 5, 47, 0, 0, 24, 4, 1, 0, 0, 0, 25, 26, 5, 46, 0, 0, 26, 6, 1, 0, 0, 0, 27, 28, 5, 58, 0, 0, 28, 8, 1, 0, 0, 0, 29, 30, 5, 35, 0, 0, 30, 10, 1, 0, 0, 0, 31, 33, 7, 1, 0, 0, 32, 31, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 32, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 12, 1, 0, 0, 0, 36, 38, 7, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 1, 0, 0, 0, 39, 40, 7, 3, 0, 0, 40, 14, 1, 0, 0, 0, 41, 43, 7, 4, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 16, 1, 0, 0, 0, 5, 0, 21, 34, 37, 44, 0] \ No newline at end of file diff --git a/handlers/hosts/ast/parser/HostsLexer.tokens b/server/handlers/hosts/ast/parser/HostsLexer.tokens similarity index 76% rename from handlers/hosts/ast/parser/HostsLexer.tokens rename to server/handlers/hosts/ast/parser/HostsLexer.tokens index c20b3c1..d53da5d 100644 --- a/handlers/hosts/ast/parser/HostsLexer.tokens +++ b/server/handlers/hosts/ast/parser/HostsLexer.tokens @@ -5,9 +5,7 @@ COLON=4 HASHTAG=5 SEPARATOR=6 NEWLINE=7 -DIGITS=8 -OCTETS=9 -DOMAIN=10 +STRING=8 '/'=2 '.'=3 ':'=4 diff --git a/handlers/hosts/ast/parser/hosts_base_listener.go b/server/handlers/hosts/ast/parser/hosts_base_listener.go similarity index 78% rename from handlers/hosts/ast/parser/hosts_base_listener.go rename to server/handlers/hosts/ast/parser/hosts_base_listener.go index 01d1e3a..d9ddba3 100644 --- a/handlers/hosts/ast/parser/hosts_base_listener.go +++ b/server/handlers/hosts/ast/parser/hosts_base_listener.go @@ -69,36 +69,12 @@ func (s *BaseHostsListener) EnterIpv4Address(ctx *Ipv4AddressContext) {} // ExitIpv4Address is called when production ipv4Address is exited. func (s *BaseHostsListener) ExitIpv4Address(ctx *Ipv4AddressContext) {} -// EnterSingleIPv4Address is called when production singleIPv4Address is entered. -func (s *BaseHostsListener) EnterSingleIPv4Address(ctx *SingleIPv4AddressContext) {} - -// ExitSingleIPv4Address is called when production singleIPv4Address is exited. -func (s *BaseHostsListener) ExitSingleIPv4Address(ctx *SingleIPv4AddressContext) {} - // EnterIpv6Address is called when production ipv6Address is entered. func (s *BaseHostsListener) EnterIpv6Address(ctx *Ipv6AddressContext) {} // ExitIpv6Address is called when production ipv6Address is exited. func (s *BaseHostsListener) ExitIpv6Address(ctx *Ipv6AddressContext) {} -// EnterSingleIPv6Address is called when production singleIPv6Address is entered. -func (s *BaseHostsListener) EnterSingleIPv6Address(ctx *SingleIPv6AddressContext) {} - -// ExitSingleIPv6Address is called when production singleIPv6Address is exited. -func (s *BaseHostsListener) ExitSingleIPv6Address(ctx *SingleIPv6AddressContext) {} - -// EnterIpv4Digit is called when production ipv4Digit is entered. -func (s *BaseHostsListener) EnterIpv4Digit(ctx *Ipv4DigitContext) {} - -// ExitIpv4Digit is called when production ipv4Digit is exited. -func (s *BaseHostsListener) ExitIpv4Digit(ctx *Ipv4DigitContext) {} - -// EnterIpv6Octet is called when production ipv6Octet is entered. -func (s *BaseHostsListener) EnterIpv6Octet(ctx *Ipv6OctetContext) {} - -// ExitIpv6Octet is called when production ipv6Octet is exited. -func (s *BaseHostsListener) ExitIpv6Octet(ctx *Ipv6OctetContext) {} - // EnterIpRange is called when production ipRange is entered. func (s *BaseHostsListener) EnterIpRange(ctx *IpRangeContext) {} @@ -111,6 +87,12 @@ func (s *BaseHostsListener) EnterIpRangeBits(ctx *IpRangeBitsContext) {} // ExitIpRangeBits is called when production ipRangeBits is exited. func (s *BaseHostsListener) ExitIpRangeBits(ctx *IpRangeBitsContext) {} +// EnterIpPort is called when production ipPort is entered. +func (s *BaseHostsListener) EnterIpPort(ctx *IpPortContext) {} + +// ExitIpPort is called when production ipPort is exited. +func (s *BaseHostsListener) ExitIpPort(ctx *IpPortContext) {} + // EnterComment is called when production comment is entered. func (s *BaseHostsListener) EnterComment(ctx *CommentContext) {} diff --git a/handlers/hosts/ast/parser/hosts_lexer.go b/server/handlers/hosts/ast/parser/hosts_lexer.go similarity index 52% rename from handlers/hosts/ast/parser/hosts_lexer.go rename to server/handlers/hosts/ast/parser/hosts_lexer.go index db0d9e1..2540abe 100644 --- a/handlers/hosts/ast/parser/hosts_lexer.go +++ b/server/handlers/hosts/ast/parser/hosts_lexer.go @@ -47,51 +47,35 @@ func hostslexerLexerInit() { } staticData.SymbolicNames = []string{ "", "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", - "NEWLINE", "DIGITS", "OCTETS", "DOMAIN", + "NEWLINE", "STRING", } staticData.RuleNames = []string{ "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", "NEWLINE", - "DIGITS", "DIGIT", "OCTETS", "OCTET", "DOMAIN", "STRING", + "STRING", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 0, 10, 83, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, - 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, - 10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 1, 0, 1, 0, 4, 0, 30, 8, 0, 11, - 0, 12, 0, 31, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, - 5, 43, 8, 5, 11, 5, 12, 5, 44, 1, 6, 3, 6, 48, 8, 6, 1, 6, 1, 6, 1, 7, - 4, 7, 53, 8, 7, 11, 7, 12, 7, 54, 1, 8, 1, 8, 1, 9, 4, 9, 60, 8, 9, 11, - 9, 12, 9, 61, 1, 10, 1, 10, 1, 11, 4, 11, 67, 8, 11, 11, 11, 12, 11, 68, - 1, 11, 1, 11, 4, 11, 73, 8, 11, 11, 11, 12, 11, 74, 5, 11, 77, 8, 11, 10, - 11, 12, 11, 80, 9, 11, 1, 12, 1, 12, 0, 0, 13, 1, 1, 3, 2, 5, 3, 7, 4, - 9, 5, 11, 6, 13, 7, 15, 8, 17, 0, 19, 9, 21, 0, 23, 10, 25, 0, 1, 0, 8, - 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, 32, 1, 0, 13, 13, 1, 0, 10, 10, 1, - 0, 48, 57, 3, 0, 48, 57, 65, 70, 97, 102, 2, 0, 65, 90, 97, 122, 5, 0, - 9, 10, 13, 13, 32, 32, 35, 35, 46, 46, 87, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, - 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, - 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0, 23, 1, - 0, 0, 0, 1, 27, 1, 0, 0, 0, 3, 33, 1, 0, 0, 0, 5, 35, 1, 0, 0, 0, 7, 37, - 1, 0, 0, 0, 9, 39, 1, 0, 0, 0, 11, 42, 1, 0, 0, 0, 13, 47, 1, 0, 0, 0, - 15, 52, 1, 0, 0, 0, 17, 56, 1, 0, 0, 0, 19, 59, 1, 0, 0, 0, 21, 63, 1, - 0, 0, 0, 23, 66, 1, 0, 0, 0, 25, 81, 1, 0, 0, 0, 27, 29, 3, 9, 4, 0, 28, - 30, 8, 0, 0, 0, 29, 28, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 29, 1, 0, 0, - 0, 31, 32, 1, 0, 0, 0, 32, 2, 1, 0, 0, 0, 33, 34, 5, 47, 0, 0, 34, 4, 1, - 0, 0, 0, 35, 36, 5, 46, 0, 0, 36, 6, 1, 0, 0, 0, 37, 38, 5, 58, 0, 0, 38, - 8, 1, 0, 0, 0, 39, 40, 5, 35, 0, 0, 40, 10, 1, 0, 0, 0, 41, 43, 7, 1, 0, + 4, 0, 8, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 1, 0, 1, 0, 4, 0, 20, 8, 0, + 11, 0, 12, 0, 21, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, + 4, 5, 33, 8, 5, 11, 5, 12, 5, 34, 1, 6, 3, 6, 38, 8, 6, 1, 6, 1, 6, 1, + 7, 4, 7, 43, 8, 7, 11, 7, 12, 7, 44, 0, 0, 8, 1, 1, 3, 2, 5, 3, 7, 4, 9, + 5, 11, 6, 13, 7, 15, 8, 1, 0, 5, 2, 0, 10, 10, 13, 13, 2, 0, 9, 9, 32, + 32, 1, 0, 13, 13, 1, 0, 10, 10, 5, 0, 45, 45, 48, 57, 65, 90, 95, 95, 97, + 122, 49, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, + 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13, 1, 0, 0, 0, 0, 15, + 1, 0, 0, 0, 1, 17, 1, 0, 0, 0, 3, 23, 1, 0, 0, 0, 5, 25, 1, 0, 0, 0, 7, + 27, 1, 0, 0, 0, 9, 29, 1, 0, 0, 0, 11, 32, 1, 0, 0, 0, 13, 37, 1, 0, 0, + 0, 15, 42, 1, 0, 0, 0, 17, 19, 3, 9, 4, 0, 18, 20, 8, 0, 0, 0, 19, 18, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, + 22, 2, 1, 0, 0, 0, 23, 24, 5, 47, 0, 0, 24, 4, 1, 0, 0, 0, 25, 26, 5, 46, + 0, 0, 26, 6, 1, 0, 0, 0, 27, 28, 5, 58, 0, 0, 28, 8, 1, 0, 0, 0, 29, 30, + 5, 35, 0, 0, 30, 10, 1, 0, 0, 0, 31, 33, 7, 1, 0, 0, 32, 31, 1, 0, 0, 0, + 33, 34, 1, 0, 0, 0, 34, 32, 1, 0, 0, 0, 34, 35, 1, 0, 0, 0, 35, 12, 1, + 0, 0, 0, 36, 38, 7, 2, 0, 0, 37, 36, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, + 39, 1, 0, 0, 0, 39, 40, 7, 3, 0, 0, 40, 14, 1, 0, 0, 0, 41, 43, 7, 4, 0, 0, 42, 41, 1, 0, 0, 0, 43, 44, 1, 0, 0, 0, 44, 42, 1, 0, 0, 0, 44, 45, - 1, 0, 0, 0, 45, 12, 1, 0, 0, 0, 46, 48, 7, 2, 0, 0, 47, 46, 1, 0, 0, 0, - 47, 48, 1, 0, 0, 0, 48, 49, 1, 0, 0, 0, 49, 50, 7, 3, 0, 0, 50, 14, 1, - 0, 0, 0, 51, 53, 3, 17, 8, 0, 52, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, - 52, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 16, 1, 0, 0, 0, 56, 57, 7, 4, 0, - 0, 57, 18, 1, 0, 0, 0, 58, 60, 3, 21, 10, 0, 59, 58, 1, 0, 0, 0, 60, 61, - 1, 0, 0, 0, 61, 59, 1, 0, 0, 0, 61, 62, 1, 0, 0, 0, 62, 20, 1, 0, 0, 0, - 63, 64, 7, 5, 0, 0, 64, 22, 1, 0, 0, 0, 65, 67, 3, 25, 12, 0, 66, 65, 1, - 0, 0, 0, 67, 68, 1, 0, 0, 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, - 78, 1, 0, 0, 0, 70, 72, 3, 5, 2, 0, 71, 73, 7, 6, 0, 0, 72, 71, 1, 0, 0, - 0, 73, 74, 1, 0, 0, 0, 74, 72, 1, 0, 0, 0, 74, 75, 1, 0, 0, 0, 75, 77, - 1, 0, 0, 0, 76, 70, 1, 0, 0, 0, 77, 80, 1, 0, 0, 0, 78, 76, 1, 0, 0, 0, - 78, 79, 1, 0, 0, 0, 79, 24, 1, 0, 0, 0, 80, 78, 1, 0, 0, 0, 81, 82, 8, - 7, 0, 0, 82, 26, 1, 0, 0, 0, 9, 0, 31, 44, 47, 54, 61, 68, 74, 78, 0, + 1, 0, 0, 0, 45, 16, 1, 0, 0, 0, 5, 0, 21, 34, 37, 44, 0, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -139,7 +123,5 @@ const ( HostsLexerHASHTAG = 5 HostsLexerSEPARATOR = 6 HostsLexerNEWLINE = 7 - HostsLexerDIGITS = 8 - HostsLexerOCTETS = 9 - HostsLexerDOMAIN = 10 + HostsLexerSTRING = 8 ) diff --git a/handlers/hosts/ast/parser/hosts_listener.go b/server/handlers/hosts/ast/parser/hosts_listener.go similarity index 75% rename from handlers/hosts/ast/parser/hosts_listener.go rename to server/handlers/hosts/ast/parser/hosts_listener.go index fbf964f..8e66aac 100644 --- a/handlers/hosts/ast/parser/hosts_listener.go +++ b/server/handlers/hosts/ast/parser/hosts_listener.go @@ -32,27 +32,18 @@ type HostsListener interface { // EnterIpv4Address is called when entering the ipv4Address production. EnterIpv4Address(c *Ipv4AddressContext) - // EnterSingleIPv4Address is called when entering the singleIPv4Address production. - EnterSingleIPv4Address(c *SingleIPv4AddressContext) - // EnterIpv6Address is called when entering the ipv6Address production. EnterIpv6Address(c *Ipv6AddressContext) - // EnterSingleIPv6Address is called when entering the singleIPv6Address production. - EnterSingleIPv6Address(c *SingleIPv6AddressContext) - - // EnterIpv4Digit is called when entering the ipv4Digit production. - EnterIpv4Digit(c *Ipv4DigitContext) - - // EnterIpv6Octet is called when entering the ipv6Octet production. - EnterIpv6Octet(c *Ipv6OctetContext) - // EnterIpRange is called when entering the ipRange production. EnterIpRange(c *IpRangeContext) // EnterIpRangeBits is called when entering the ipRangeBits production. EnterIpRangeBits(c *IpRangeBitsContext) + // EnterIpPort is called when entering the ipPort production. + EnterIpPort(c *IpPortContext) + // EnterComment is called when entering the comment production. EnterComment(c *CommentContext) @@ -83,27 +74,18 @@ type HostsListener interface { // ExitIpv4Address is called when exiting the ipv4Address production. ExitIpv4Address(c *Ipv4AddressContext) - // ExitSingleIPv4Address is called when exiting the singleIPv4Address production. - ExitSingleIPv4Address(c *SingleIPv4AddressContext) - // ExitIpv6Address is called when exiting the ipv6Address production. ExitIpv6Address(c *Ipv6AddressContext) - // ExitSingleIPv6Address is called when exiting the singleIPv6Address production. - ExitSingleIPv6Address(c *SingleIPv6AddressContext) - - // ExitIpv4Digit is called when exiting the ipv4Digit production. - ExitIpv4Digit(c *Ipv4DigitContext) - - // ExitIpv6Octet is called when exiting the ipv6Octet production. - ExitIpv6Octet(c *Ipv6OctetContext) - // ExitIpRange is called when exiting the ipRange production. ExitIpRange(c *IpRangeContext) // ExitIpRangeBits is called when exiting the ipRangeBits production. ExitIpRangeBits(c *IpRangeBitsContext) + // ExitIpPort is called when exiting the ipPort production. + ExitIpPort(c *IpPortContext) + // ExitComment is called when exiting the comment production. ExitComment(c *CommentContext) diff --git a/handlers/hosts/ast/parser/hosts_parser.go b/server/handlers/hosts/ast/parser/hosts_parser.go similarity index 71% rename from handlers/hosts/ast/parser/hosts_parser.go rename to server/handlers/hosts/ast/parser/hosts_parser.go index 81dca33..5f6503e 100644 --- a/handlers/hosts/ast/parser/hosts_parser.go +++ b/server/handlers/hosts/ast/parser/hosts_parser.go @@ -37,57 +37,70 @@ func hostsParserInit() { } staticData.SymbolicNames = []string{ "", "COMMENTLINE", "SLASH", "DOT", "COLON", "HASHTAG", "SEPARATOR", - "NEWLINE", "DIGITS", "OCTETS", "DOMAIN", + "NEWLINE", "STRING", } staticData.RuleNames = []string{ "lineStatement", "entry", "aliases", "alias", "hostname", "domain", - "ipAddress", "ipv4Address", "singleIPv4Address", "ipv6Address", "singleIPv6Address", - "ipv4Digit", "ipv6Octet", "ipRange", "ipRangeBits", "comment", "leadingComment", + "ipAddress", "ipv4Address", "ipv6Address", "ipRange", "ipRangeBits", + "ipPort", "comment", "leadingComment", } staticData.PredictionContextCache = antlr.NewPredictionContextCache() staticData.serializedATN = []int32{ - 4, 1, 10, 110, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, + 4, 1, 8, 131, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2, 10, 7, - 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15, 7, 15, - 2, 16, 7, 16, 1, 0, 3, 0, 36, 8, 0, 1, 0, 1, 0, 3, 0, 40, 8, 0, 1, 0, 3, - 0, 43, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 52, 8, 1, - 1, 2, 1, 2, 3, 2, 56, 8, 2, 4, 2, 58, 8, 2, 11, 2, 12, 2, 59, 1, 3, 1, - 3, 1, 4, 1, 4, 1, 5, 1, 5, 1, 6, 1, 6, 3, 6, 70, 8, 6, 1, 7, 1, 7, 3, 7, - 74, 8, 7, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 8, 1, 9, 1, 9, 3, - 9, 86, 8, 9, 1, 10, 1, 10, 1, 10, 4, 10, 91, 8, 10, 11, 10, 12, 10, 92, - 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, 1, 13, 1, 14, 1, - 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 16, 0, 0, 17, 0, 2, 4, 6, 8, 10, 12, - 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 0, 0, 102, 0, 35, 1, 0, 0, 0, 2, - 46, 1, 0, 0, 0, 4, 57, 1, 0, 0, 0, 6, 61, 1, 0, 0, 0, 8, 63, 1, 0, 0, 0, - 10, 65, 1, 0, 0, 0, 12, 69, 1, 0, 0, 0, 14, 71, 1, 0, 0, 0, 16, 75, 1, - 0, 0, 0, 18, 83, 1, 0, 0, 0, 20, 90, 1, 0, 0, 0, 22, 96, 1, 0, 0, 0, 24, - 98, 1, 0, 0, 0, 26, 100, 1, 0, 0, 0, 28, 103, 1, 0, 0, 0, 30, 105, 1, 0, - 0, 0, 32, 107, 1, 0, 0, 0, 34, 36, 5, 6, 0, 0, 35, 34, 1, 0, 0, 0, 35, - 36, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 39, 3, 2, 1, 0, 38, 40, 5, 6, 0, - 0, 39, 38, 1, 0, 0, 0, 39, 40, 1, 0, 0, 0, 40, 42, 1, 0, 0, 0, 41, 43, - 3, 32, 16, 0, 42, 41, 1, 0, 0, 0, 42, 43, 1, 0, 0, 0, 43, 44, 1, 0, 0, - 0, 44, 45, 5, 0, 0, 1, 45, 1, 1, 0, 0, 0, 46, 47, 3, 12, 6, 0, 47, 48, - 5, 6, 0, 0, 48, 51, 3, 8, 4, 0, 49, 50, 5, 6, 0, 0, 50, 52, 3, 4, 2, 0, - 51, 49, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 3, 1, 0, 0, 0, 53, 55, 3, 6, - 3, 0, 54, 56, 5, 6, 0, 0, 55, 54, 1, 0, 0, 0, 55, 56, 1, 0, 0, 0, 56, 58, - 1, 0, 0, 0, 57, 53, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 57, 1, 0, 0, 0, - 59, 60, 1, 0, 0, 0, 60, 5, 1, 0, 0, 0, 61, 62, 5, 10, 0, 0, 62, 7, 1, 0, - 0, 0, 63, 64, 3, 10, 5, 0, 64, 9, 1, 0, 0, 0, 65, 66, 5, 10, 0, 0, 66, - 11, 1, 0, 0, 0, 67, 70, 3, 14, 7, 0, 68, 70, 3, 18, 9, 0, 69, 67, 1, 0, - 0, 0, 69, 68, 1, 0, 0, 0, 70, 13, 1, 0, 0, 0, 71, 73, 3, 16, 8, 0, 72, - 74, 3, 26, 13, 0, 73, 72, 1, 0, 0, 0, 73, 74, 1, 0, 0, 0, 74, 15, 1, 0, - 0, 0, 75, 76, 3, 22, 11, 0, 76, 77, 5, 3, 0, 0, 77, 78, 3, 22, 11, 0, 78, - 79, 5, 3, 0, 0, 79, 80, 3, 22, 11, 0, 80, 81, 5, 3, 0, 0, 81, 82, 3, 22, - 11, 0, 82, 17, 1, 0, 0, 0, 83, 85, 3, 20, 10, 0, 84, 86, 3, 26, 13, 0, - 85, 84, 1, 0, 0, 0, 85, 86, 1, 0, 0, 0, 86, 19, 1, 0, 0, 0, 87, 88, 3, - 24, 12, 0, 88, 89, 5, 4, 0, 0, 89, 91, 1, 0, 0, 0, 90, 87, 1, 0, 0, 0, - 91, 92, 1, 0, 0, 0, 92, 90, 1, 0, 0, 0, 92, 93, 1, 0, 0, 0, 93, 94, 1, - 0, 0, 0, 94, 95, 3, 24, 12, 0, 95, 21, 1, 0, 0, 0, 96, 97, 5, 8, 0, 0, - 97, 23, 1, 0, 0, 0, 98, 99, 5, 9, 0, 0, 99, 25, 1, 0, 0, 0, 100, 101, 5, - 2, 0, 0, 101, 102, 3, 28, 14, 0, 102, 27, 1, 0, 0, 0, 103, 104, 5, 8, 0, - 0, 104, 29, 1, 0, 0, 0, 105, 106, 5, 1, 0, 0, 106, 31, 1, 0, 0, 0, 107, - 108, 5, 1, 0, 0, 108, 33, 1, 0, 0, 0, 10, 35, 39, 42, 51, 55, 59, 69, 73, - 85, 92, + 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 1, 0, 3, 0, 30, 8, 0, 1, + 0, 1, 0, 3, 0, 34, 8, 0, 1, 0, 3, 0, 37, 8, 0, 1, 0, 1, 0, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 3, 1, 46, 8, 1, 1, 2, 1, 2, 3, 2, 50, 8, 2, 4, 2, 52, + 8, 2, 11, 2, 12, 2, 53, 1, 3, 1, 3, 1, 4, 1, 4, 1, 5, 4, 5, 61, 8, 5, 11, + 5, 12, 5, 62, 1, 5, 1, 5, 5, 5, 67, 8, 5, 10, 5, 12, 5, 70, 9, 5, 5, 5, + 72, 8, 5, 10, 5, 12, 5, 75, 9, 5, 1, 6, 1, 6, 3, 6, 79, 8, 6, 1, 7, 1, + 7, 4, 7, 83, 8, 7, 11, 7, 12, 7, 84, 1, 7, 1, 7, 3, 7, 89, 8, 7, 1, 7, + 3, 7, 92, 8, 7, 3, 7, 94, 8, 7, 1, 8, 1, 8, 4, 8, 98, 8, 8, 11, 8, 12, + 8, 99, 1, 8, 1, 8, 3, 8, 104, 8, 8, 1, 8, 1, 8, 1, 8, 3, 8, 109, 8, 8, + 1, 8, 3, 8, 112, 8, 8, 1, 8, 3, 8, 115, 8, 8, 3, 8, 117, 8, 8, 1, 9, 1, + 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13, + 1, 13, 0, 0, 14, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 0, + 0, 136, 0, 29, 1, 0, 0, 0, 2, 40, 1, 0, 0, 0, 4, 51, 1, 0, 0, 0, 6, 55, + 1, 0, 0, 0, 8, 57, 1, 0, 0, 0, 10, 60, 1, 0, 0, 0, 12, 78, 1, 0, 0, 0, + 14, 82, 1, 0, 0, 0, 16, 108, 1, 0, 0, 0, 18, 118, 1, 0, 0, 0, 20, 121, + 1, 0, 0, 0, 22, 123, 1, 0, 0, 0, 24, 126, 1, 0, 0, 0, 26, 128, 1, 0, 0, + 0, 28, 30, 5, 6, 0, 0, 29, 28, 1, 0, 0, 0, 29, 30, 1, 0, 0, 0, 30, 31, + 1, 0, 0, 0, 31, 33, 3, 2, 1, 0, 32, 34, 5, 6, 0, 0, 33, 32, 1, 0, 0, 0, + 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 26, 13, 0, 36, 35, 1, + 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 39, 5, 0, 0, 1, 39, + 1, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 42, 5, 6, 0, 0, 42, 45, 3, 8, 4, + 0, 43, 44, 5, 6, 0, 0, 44, 46, 3, 4, 2, 0, 45, 43, 1, 0, 0, 0, 45, 46, + 1, 0, 0, 0, 46, 3, 1, 0, 0, 0, 47, 49, 3, 6, 3, 0, 48, 50, 5, 6, 0, 0, + 49, 48, 1, 0, 0, 0, 49, 50, 1, 0, 0, 0, 50, 52, 1, 0, 0, 0, 51, 47, 1, + 0, 0, 0, 52, 53, 1, 0, 0, 0, 53, 51, 1, 0, 0, 0, 53, 54, 1, 0, 0, 0, 54, + 5, 1, 0, 0, 0, 55, 56, 3, 10, 5, 0, 56, 7, 1, 0, 0, 0, 57, 58, 3, 10, 5, + 0, 58, 9, 1, 0, 0, 0, 59, 61, 5, 8, 0, 0, 60, 59, 1, 0, 0, 0, 61, 62, 1, + 0, 0, 0, 62, 60, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 73, 1, 0, 0, 0, 64, + 68, 5, 3, 0, 0, 65, 67, 5, 8, 0, 0, 66, 65, 1, 0, 0, 0, 67, 70, 1, 0, 0, + 0, 68, 66, 1, 0, 0, 0, 68, 69, 1, 0, 0, 0, 69, 72, 1, 0, 0, 0, 70, 68, + 1, 0, 0, 0, 71, 64, 1, 0, 0, 0, 72, 75, 1, 0, 0, 0, 73, 71, 1, 0, 0, 0, + 73, 74, 1, 0, 0, 0, 74, 11, 1, 0, 0, 0, 75, 73, 1, 0, 0, 0, 76, 79, 3, + 14, 7, 0, 77, 79, 3, 16, 8, 0, 78, 76, 1, 0, 0, 0, 78, 77, 1, 0, 0, 0, + 79, 13, 1, 0, 0, 0, 80, 81, 5, 8, 0, 0, 81, 83, 5, 3, 0, 0, 82, 80, 1, + 0, 0, 0, 83, 84, 1, 0, 0, 0, 84, 82, 1, 0, 0, 0, 84, 85, 1, 0, 0, 0, 85, + 86, 1, 0, 0, 0, 86, 93, 5, 8, 0, 0, 87, 89, 3, 18, 9, 0, 88, 87, 1, 0, + 0, 0, 88, 89, 1, 0, 0, 0, 89, 94, 1, 0, 0, 0, 90, 92, 3, 22, 11, 0, 91, + 90, 1, 0, 0, 0, 91, 92, 1, 0, 0, 0, 92, 94, 1, 0, 0, 0, 93, 88, 1, 0, 0, + 0, 93, 91, 1, 0, 0, 0, 94, 15, 1, 0, 0, 0, 95, 96, 5, 8, 0, 0, 96, 98, + 5, 4, 0, 0, 97, 95, 1, 0, 0, 0, 98, 99, 1, 0, 0, 0, 99, 97, 1, 0, 0, 0, + 99, 100, 1, 0, 0, 0, 100, 101, 1, 0, 0, 0, 101, 109, 5, 8, 0, 0, 102, 104, + 5, 8, 0, 0, 103, 102, 1, 0, 0, 0, 103, 104, 1, 0, 0, 0, 104, 105, 1, 0, + 0, 0, 105, 106, 5, 4, 0, 0, 106, 107, 5, 4, 0, 0, 107, 109, 5, 8, 0, 0, + 108, 97, 1, 0, 0, 0, 108, 103, 1, 0, 0, 0, 109, 116, 1, 0, 0, 0, 110, 112, + 3, 18, 9, 0, 111, 110, 1, 0, 0, 0, 111, 112, 1, 0, 0, 0, 112, 117, 1, 0, + 0, 0, 113, 115, 3, 22, 11, 0, 114, 113, 1, 0, 0, 0, 114, 115, 1, 0, 0, + 0, 115, 117, 1, 0, 0, 0, 116, 111, 1, 0, 0, 0, 116, 114, 1, 0, 0, 0, 117, + 17, 1, 0, 0, 0, 118, 119, 5, 2, 0, 0, 119, 120, 3, 20, 10, 0, 120, 19, + 1, 0, 0, 0, 121, 122, 5, 8, 0, 0, 122, 21, 1, 0, 0, 0, 123, 124, 5, 4, + 0, 0, 124, 125, 5, 8, 0, 0, 125, 23, 1, 0, 0, 0, 126, 127, 5, 1, 0, 0, + 127, 25, 1, 0, 0, 0, 128, 129, 5, 1, 0, 0, 129, 27, 1, 0, 0, 0, 20, 29, + 33, 36, 45, 49, 53, 62, 68, 73, 78, 84, 88, 91, 93, 99, 103, 108, 111, + 114, 116, } deserializer := antlr.NewATNDeserializer(nil) staticData.atn = deserializer.Deserialize(staticData.serializedATN) @@ -133,30 +146,25 @@ const ( HostsParserHASHTAG = 5 HostsParserSEPARATOR = 6 HostsParserNEWLINE = 7 - HostsParserDIGITS = 8 - HostsParserOCTETS = 9 - HostsParserDOMAIN = 10 + HostsParserSTRING = 8 ) // HostsParser rules. const ( - HostsParserRULE_lineStatement = 0 - HostsParserRULE_entry = 1 - HostsParserRULE_aliases = 2 - HostsParserRULE_alias = 3 - HostsParserRULE_hostname = 4 - HostsParserRULE_domain = 5 - HostsParserRULE_ipAddress = 6 - HostsParserRULE_ipv4Address = 7 - HostsParserRULE_singleIPv4Address = 8 - HostsParserRULE_ipv6Address = 9 - HostsParserRULE_singleIPv6Address = 10 - HostsParserRULE_ipv4Digit = 11 - HostsParserRULE_ipv6Octet = 12 - HostsParserRULE_ipRange = 13 - HostsParserRULE_ipRangeBits = 14 - HostsParserRULE_comment = 15 - HostsParserRULE_leadingComment = 16 + HostsParserRULE_lineStatement = 0 + HostsParserRULE_entry = 1 + HostsParserRULE_aliases = 2 + HostsParserRULE_alias = 3 + HostsParserRULE_hostname = 4 + HostsParserRULE_domain = 5 + HostsParserRULE_ipAddress = 6 + HostsParserRULE_ipv4Address = 7 + HostsParserRULE_ipv6Address = 8 + HostsParserRULE_ipRange = 9 + HostsParserRULE_ipRangeBits = 10 + HostsParserRULE_ipPort = 11 + HostsParserRULE_comment = 12 + HostsParserRULE_leadingComment = 13 ) // ILineStatementContext is an interface to support dynamic dispatch. @@ -279,7 +287,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(35) + p.SetState(29) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -288,7 +296,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserSEPARATOR { { - p.SetState(34) + p.SetState(28) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -298,10 +306,10 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { } { - p.SetState(37) + p.SetState(31) p.Entry() } - p.SetState(39) + p.SetState(33) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -310,7 +318,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserSEPARATOR { { - p.SetState(38) + p.SetState(32) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -319,7 +327,7 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { } } - p.SetState(42) + p.SetState(36) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -328,13 +336,13 @@ func (p *HostsParser) LineStatement() (localctx ILineStatementContext) { if _la == HostsParserCOMMENTLINE { { - p.SetState(41) + p.SetState(35) p.LeadingComment() } } { - p.SetState(44) + p.SetState(38) p.Match(HostsParserEOF) if p.HasError() { // Recognition error - abort rule @@ -486,11 +494,11 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { p.EnterRule(localctx, 2, HostsParserRULE_entry) p.EnterOuterAlt(localctx, 1) { - p.SetState(46) + p.SetState(40) p.IpAddress() } { - p.SetState(47) + p.SetState(41) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -498,15 +506,15 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { } } { - p.SetState(48) + p.SetState(42) p.Hostname() } - p.SetState(51) + p.SetState(45) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { { - p.SetState(49) + p.SetState(43) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -514,7 +522,7 @@ func (p *HostsParser) Entry() (localctx IEntryContext) { } } { - p.SetState(50) + p.SetState(44) p.Aliases() } @@ -659,24 +667,24 @@ func (p *HostsParser) Aliases() (localctx IAliasesContext) { var _la int p.EnterOuterAlt(localctx, 1) - p.SetState(57) + p.SetState(51) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } _la = p.GetTokenStream().LA(1) - for ok := true; ok; ok = _la == HostsParserDOMAIN { + for ok := true; ok; ok = _la == HostsParserSTRING { { - p.SetState(53) + p.SetState(47) p.Alias() } - p.SetState(55) + p.SetState(49) p.GetErrorHandler().Sync(p) if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { { - p.SetState(54) + p.SetState(48) p.Match(HostsParserSEPARATOR) if p.HasError() { // Recognition error - abort rule @@ -688,7 +696,7 @@ func (p *HostsParser) Aliases() (localctx IAliasesContext) { goto errorExit } - p.SetState(59) + p.SetState(53) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit @@ -717,7 +725,7 @@ type IAliasContext interface { GetParser() antlr.Parser // Getter signatures - DOMAIN() antlr.TerminalNode + Domain() IDomainContext // IsAliasContext differentiates from other interfaces. IsAliasContext() @@ -755,8 +763,20 @@ func NewAliasContext(parser antlr.Parser, parent antlr.ParserRuleContext, invoki func (s *AliasContext) GetParser() antlr.Parser { return s.parser } -func (s *AliasContext) DOMAIN() antlr.TerminalNode { - return s.GetToken(HostsParserDOMAIN, 0) +func (s *AliasContext) Domain() IDomainContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IDomainContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IDomainContext) } func (s *AliasContext) GetRuleContext() antlr.RuleContext { @@ -784,12 +804,8 @@ func (p *HostsParser) Alias() (localctx IAliasContext) { p.EnterRule(localctx, 6, HostsParserRULE_alias) p.EnterOuterAlt(localctx, 1) { - p.SetState(61) - p.Match(HostsParserDOMAIN) - if p.HasError() { - // Recognition error - abort rule - goto errorExit - } + p.SetState(55) + p.Domain() } errorExit: @@ -892,7 +908,7 @@ func (p *HostsParser) Hostname() (localctx IHostnameContext) { p.EnterRule(localctx, 8, HostsParserRULE_hostname) p.EnterOuterAlt(localctx, 1) { - p.SetState(63) + p.SetState(57) p.Domain() } @@ -917,7 +933,10 @@ type IDomainContext interface { GetParser() antlr.Parser // Getter signatures - DOMAIN() antlr.TerminalNode + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllDOT() []antlr.TerminalNode + DOT(i int) antlr.TerminalNode // IsDomainContext differentiates from other interfaces. IsDomainContext() @@ -955,8 +974,20 @@ func NewDomainContext(parser antlr.Parser, parent antlr.ParserRuleContext, invok func (s *DomainContext) GetParser() antlr.Parser { return s.parser } -func (s *DomainContext) DOMAIN() antlr.TerminalNode { - return s.GetToken(HostsParserDOMAIN, 0) +func (s *DomainContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} + +func (s *DomainContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} + +func (s *DomainContext) AllDOT() []antlr.TerminalNode { + return s.GetTokens(HostsParserDOT) +} + +func (s *DomainContext) DOT(i int) antlr.TerminalNode { + return s.GetToken(HostsParserDOT, i) } func (s *DomainContext) GetRuleContext() antlr.RuleContext { @@ -982,14 +1013,95 @@ func (s *DomainContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Domain() (localctx IDomainContext) { localctx = NewDomainContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 10, HostsParserRULE_domain) + var _la int + + var _alt int + p.EnterOuterAlt(localctx, 1) - { - p.SetState(65) - p.Match(HostsParserDOMAIN) - if p.HasError() { - // Recognition error - abort rule + p.SetState(60) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(59) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) goto errorExit } + + p.SetState(62) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 6, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(73) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for _la == HostsParserDOT { + { + p.SetState(64) + p.Match(HostsParserDOT) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(68) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(65) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(70) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + + p.SetState(75) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) } errorExit: @@ -1108,27 +1220,26 @@ func (p *HostsParser) IpAddress() (localctx IIpAddressContext) { localctx = NewIpAddressContext(p, p.GetParserRuleContext(), p.GetState()) p.EnterRule(localctx, 12, HostsParserRULE_ipAddress) p.EnterOuterAlt(localctx, 1) - p.SetState(69) + p.SetState(78) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - switch p.GetTokenStream().LA(1) { - case HostsParserDIGITS: + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) { + case 1: { - p.SetState(67) + p.SetState(76) p.Ipv4Address() } - case HostsParserOCTETS: + case 2: { - p.SetState(68) + p.SetState(77) p.Ipv6Address() } - default: - p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + case antlr.ATNInvalidAltNumber: goto errorExit } @@ -1153,8 +1264,12 @@ type IIpv4AddressContext interface { GetParser() antlr.Parser // Getter signatures - SingleIPv4Address() ISingleIPv4AddressContext + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllDOT() []antlr.TerminalNode + DOT(i int) antlr.TerminalNode IpRange() IIpRangeContext + IpPort() IIpPortContext // IsIpv4AddressContext differentiates from other interfaces. IsIpv4AddressContext() @@ -1192,20 +1307,20 @@ func NewIpv4AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *Ipv4AddressContext) GetParser() antlr.Parser { return s.parser } -func (s *Ipv4AddressContext) SingleIPv4Address() ISingleIPv4AddressContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISingleIPv4AddressContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } +func (s *Ipv4AddressContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} - if t == nil { - return nil - } +func (s *Ipv4AddressContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} - return t.(ISingleIPv4AddressContext) +func (s *Ipv4AddressContext) AllDOT() []antlr.TerminalNode { + return s.GetTokens(HostsParserDOT) +} + +func (s *Ipv4AddressContext) DOT(i int) antlr.TerminalNode { + return s.GetToken(HostsParserDOT, i) } func (s *Ipv4AddressContext) IpRange() IIpRangeContext { @@ -1224,6 +1339,22 @@ func (s *Ipv4AddressContext) IpRange() IIpRangeContext { return t.(IIpRangeContext) } +func (s *Ipv4AddressContext) IpPort() IIpPortContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IIpPortContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IIpPortContext) +} + func (s *Ipv4AddressContext) GetRuleContext() antlr.RuleContext { return s } @@ -1249,200 +1380,96 @@ func (p *HostsParser) Ipv4Address() (localctx IIpv4AddressContext) { p.EnterRule(localctx, 14, HostsParserRULE_ipv4Address) var _la int + var _alt int + p.EnterOuterAlt(localctx, 1) - { - p.SetState(71) - p.SingleIPv4Address() - } - p.SetState(73) + p.SetState(82) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _la = p.GetTokenStream().LA(1) - - if _la == HostsParserSLASH { - { - p.SetState(72) - p.IpRange() - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISingleIPv4AddressContext is an interface to support dynamic dispatch. -type ISingleIPv4AddressContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllIpv4Digit() []IIpv4DigitContext - Ipv4Digit(i int) IIpv4DigitContext - AllDOT() []antlr.TerminalNode - DOT(i int) antlr.TerminalNode - - // IsSingleIPv4AddressContext differentiates from other interfaces. - IsSingleIPv4AddressContext() -} - -type SingleIPv4AddressContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySingleIPv4AddressContext() *SingleIPv4AddressContext { - var p = new(SingleIPv4AddressContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv4Address - return p -} - -func InitEmptySingleIPv4AddressContext(p *SingleIPv4AddressContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv4Address -} - -func (*SingleIPv4AddressContext) IsSingleIPv4AddressContext() {} - -func NewSingleIPv4AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SingleIPv4AddressContext { - var p = new(SingleIPv4AddressContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_singleIPv4Address - - return p -} - -func (s *SingleIPv4AddressContext) GetParser() antlr.Parser { return s.parser } - -func (s *SingleIPv4AddressContext) AllIpv4Digit() []IIpv4DigitContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IIpv4DigitContext); ok { - len++ - } - } - - tst := make([]IIpv4DigitContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IIpv4DigitContext); ok { - tst[i] = t.(IIpv4DigitContext) - i++ - } - } - - return tst -} - -func (s *SingleIPv4AddressContext) Ipv4Digit(i int) IIpv4DigitContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IIpv4DigitContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(80) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } } - j++ + { + p.SetState(81) + p.Match(HostsParserDOT) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit + } + + p.SetState(84) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 10, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit } } - - if t == nil { - return nil - } - - return t.(IIpv4DigitContext) -} - -func (s *SingleIPv4AddressContext) AllDOT() []antlr.TerminalNode { - return s.GetTokens(HostsParserDOT) -} - -func (s *SingleIPv4AddressContext) DOT(i int) antlr.TerminalNode { - return s.GetToken(HostsParserDOT, i) -} - -func (s *SingleIPv4AddressContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SingleIPv4AddressContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SingleIPv4AddressContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterSingleIPv4Address(s) - } -} - -func (s *SingleIPv4AddressContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitSingleIPv4Address(s) - } -} - -func (p *HostsParser) SingleIPv4Address() (localctx ISingleIPv4AddressContext) { - localctx = NewSingleIPv4AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 16, HostsParserRULE_singleIPv4Address) - p.EnterOuterAlt(localctx, 1) { - p.SetState(75) - p.Ipv4Digit() - } - { - p.SetState(76) - p.Match(HostsParserDOT) + p.SetState(86) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - { - p.SetState(77) - p.Ipv4Digit() + p.SetState(93) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit } - { - p.SetState(78) - p.Match(HostsParserDOT) + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 13, p.GetParserRuleContext()) { + case 1: + p.SetState(88) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } - { - p.SetState(79) - p.Ipv4Digit() - } - { - p.SetState(80) - p.Match(HostsParserDOT) + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserSLASH { + { + p.SetState(87) + p.IpRange() + } + + } + + case 2: + p.SetState(91) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } - { - p.SetState(81) - p.Ipv4Digit() + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserCOLON { + { + p.SetState(90) + p.IpPort() + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit } errorExit: @@ -1466,8 +1493,12 @@ type IIpv6AddressContext interface { GetParser() antlr.Parser // Getter signatures - SingleIPv6Address() ISingleIPv6AddressContext + AllSTRING() []antlr.TerminalNode + STRING(i int) antlr.TerminalNode + AllCOLON() []antlr.TerminalNode + COLON(i int) antlr.TerminalNode IpRange() IIpRangeContext + IpPort() IIpPortContext // IsIpv6AddressContext differentiates from other interfaces. IsIpv6AddressContext() @@ -1505,20 +1536,20 @@ func NewIpv6AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *Ipv6AddressContext) GetParser() antlr.Parser { return s.parser } -func (s *Ipv6AddressContext) SingleIPv6Address() ISingleIPv6AddressContext { - var t antlr.RuleContext - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(ISingleIPv6AddressContext); ok { - t = ctx.(antlr.RuleContext) - break - } - } +func (s *Ipv6AddressContext) AllSTRING() []antlr.TerminalNode { + return s.GetTokens(HostsParserSTRING) +} - if t == nil { - return nil - } +func (s *Ipv6AddressContext) STRING(i int) antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, i) +} - return t.(ISingleIPv6AddressContext) +func (s *Ipv6AddressContext) AllCOLON() []antlr.TerminalNode { + return s.GetTokens(HostsParserCOLON) +} + +func (s *Ipv6AddressContext) COLON(i int) antlr.TerminalNode { + return s.GetToken(HostsParserCOLON, i) } func (s *Ipv6AddressContext) IpRange() IIpRangeContext { @@ -1537,6 +1568,22 @@ func (s *Ipv6AddressContext) IpRange() IIpRangeContext { return t.(IIpRangeContext) } +func (s *Ipv6AddressContext) IpPort() IIpPortContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IIpPortContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IIpPortContext) +} + func (s *Ipv6AddressContext) GetRuleContext() antlr.RuleContext { return s } @@ -1559,395 +1606,155 @@ func (s *Ipv6AddressContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Ipv6Address() (localctx IIpv6AddressContext) { localctx = NewIpv6AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 18, HostsParserRULE_ipv6Address) + p.EnterRule(localctx, 16, HostsParserRULE_ipv6Address) var _la int - p.EnterOuterAlt(localctx, 1) - { - p.SetState(83) - p.SingleIPv6Address() - } - p.SetState(85) - p.GetErrorHandler().Sync(p) - if p.HasError() { - goto errorExit - } - _la = p.GetTokenStream().LA(1) - - if _la == HostsParserSLASH { - { - p.SetState(84) - p.IpRange() - } - - } - -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} - -// ISingleIPv6AddressContext is an interface to support dynamic dispatch. -type ISingleIPv6AddressContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - AllIpv6Octet() []IIpv6OctetContext - Ipv6Octet(i int) IIpv6OctetContext - AllCOLON() []antlr.TerminalNode - COLON(i int) antlr.TerminalNode - - // IsSingleIPv6AddressContext differentiates from other interfaces. - IsSingleIPv6AddressContext() -} - -type SingleIPv6AddressContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptySingleIPv6AddressContext() *SingleIPv6AddressContext { - var p = new(SingleIPv6AddressContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv6Address - return p -} - -func InitEmptySingleIPv6AddressContext(p *SingleIPv6AddressContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_singleIPv6Address -} - -func (*SingleIPv6AddressContext) IsSingleIPv6AddressContext() {} - -func NewSingleIPv6AddressContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SingleIPv6AddressContext { - var p = new(SingleIPv6AddressContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_singleIPv6Address - - return p -} - -func (s *SingleIPv6AddressContext) GetParser() antlr.Parser { return s.parser } - -func (s *SingleIPv6AddressContext) AllIpv6Octet() []IIpv6OctetContext { - children := s.GetChildren() - len := 0 - for _, ctx := range children { - if _, ok := ctx.(IIpv6OctetContext); ok { - len++ - } - } - - tst := make([]IIpv6OctetContext, len) - i := 0 - for _, ctx := range children { - if t, ok := ctx.(IIpv6OctetContext); ok { - tst[i] = t.(IIpv6OctetContext) - i++ - } - } - - return tst -} - -func (s *SingleIPv6AddressContext) Ipv6Octet(i int) IIpv6OctetContext { - var t antlr.RuleContext - j := 0 - for _, ctx := range s.GetChildren() { - if _, ok := ctx.(IIpv6OctetContext); ok { - if j == i { - t = ctx.(antlr.RuleContext) - break - } - j++ - } - } - - if t == nil { - return nil - } - - return t.(IIpv6OctetContext) -} - -func (s *SingleIPv6AddressContext) AllCOLON() []antlr.TerminalNode { - return s.GetTokens(HostsParserCOLON) -} - -func (s *SingleIPv6AddressContext) COLON(i int) antlr.TerminalNode { - return s.GetToken(HostsParserCOLON, i) -} - -func (s *SingleIPv6AddressContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *SingleIPv6AddressContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *SingleIPv6AddressContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterSingleIPv6Address(s) - } -} - -func (s *SingleIPv6AddressContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitSingleIPv6Address(s) - } -} - -func (p *HostsParser) SingleIPv6Address() (localctx ISingleIPv6AddressContext) { - localctx = NewSingleIPv6AddressContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 20, HostsParserRULE_singleIPv6Address) var _alt int p.EnterOuterAlt(localctx, 1) - p.SetState(90) + p.SetState(108) p.GetErrorHandler().Sync(p) if p.HasError() { goto errorExit } - _alt = 1 - for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { - switch _alt { - case 1: - { - p.SetState(87) - p.Ipv6Octet() + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 16, p.GetParserRuleContext()) { + case 1: + p.SetState(97) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = 1 + for ok := true; ok; ok = _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + switch _alt { + case 1: + { + p.SetState(95) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(96) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + default: + p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) + goto errorExit } + + p.SetState(99) + p.GetErrorHandler().Sync(p) + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 14, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + { + p.SetState(101) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + case 2: + p.SetState(103) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == HostsParserSTRING { { - p.SetState(88) - p.Match(HostsParserCOLON) + p.SetState(102) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit } } - default: - p.SetError(antlr.NewNoViableAltException(p, nil, nil, nil, nil, nil)) - goto errorExit + } + { + p.SetState(105) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(106) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(107) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } } - p.SetState(92) + case antlr.ATNInvalidAltNumber: + goto errorExit + } + p.SetState(116) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 19, p.GetParserRuleContext()) { + case 1: + p.SetState(111) p.GetErrorHandler().Sync(p) - _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 9, p.GetParserRuleContext()) if p.HasError() { goto errorExit } - } - { - p.SetState(94) - p.Ipv6Octet() - } + _la = p.GetTokenStream().LA(1) -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} + if _la == HostsParserSLASH { + { + p.SetState(110) + p.IpRange() + } -// IIpv4DigitContext is an interface to support dynamic dispatch. -type IIpv4DigitContext interface { - antlr.ParserRuleContext + } - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - DIGITS() antlr.TerminalNode - - // IsIpv4DigitContext differentiates from other interfaces. - IsIpv4DigitContext() -} - -type Ipv4DigitContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyIpv4DigitContext() *Ipv4DigitContext { - var p = new(Ipv4DigitContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv4Digit - return p -} - -func InitEmptyIpv4DigitContext(p *Ipv4DigitContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv4Digit -} - -func (*Ipv4DigitContext) IsIpv4DigitContext() {} - -func NewIpv4DigitContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *Ipv4DigitContext { - var p = new(Ipv4DigitContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_ipv4Digit - - return p -} - -func (s *Ipv4DigitContext) GetParser() antlr.Parser { return s.parser } - -func (s *Ipv4DigitContext) DIGITS() antlr.TerminalNode { - return s.GetToken(HostsParserDIGITS, 0) -} - -func (s *Ipv4DigitContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *Ipv4DigitContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *Ipv4DigitContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterIpv4Digit(s) - } -} - -func (s *Ipv4DigitContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitIpv4Digit(s) - } -} - -func (p *HostsParser) Ipv4Digit() (localctx IIpv4DigitContext) { - localctx = NewIpv4DigitContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 22, HostsParserRULE_ipv4Digit) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(96) - p.Match(HostsParserDIGITS) + case 2: + p.SetState(114) + p.GetErrorHandler().Sync(p) if p.HasError() { - // Recognition error - abort rule goto errorExit } - } + _la = p.GetTokenStream().LA(1) -errorExit: - if p.HasError() { - v := p.GetError() - localctx.SetException(v) - p.GetErrorHandler().ReportError(p, v) - p.GetErrorHandler().Recover(p, v) - p.SetError(nil) - } - p.ExitRule() - return localctx - goto errorExit // Trick to prevent compiler error if the label is not used -} + if _la == HostsParserCOLON { + { + p.SetState(113) + p.IpPort() + } -// IIpv6OctetContext is an interface to support dynamic dispatch. -type IIpv6OctetContext interface { - antlr.ParserRuleContext - - // GetParser returns the parser. - GetParser() antlr.Parser - - // Getter signatures - OCTETS() antlr.TerminalNode - - // IsIpv6OctetContext differentiates from other interfaces. - IsIpv6OctetContext() -} - -type Ipv6OctetContext struct { - antlr.BaseParserRuleContext - parser antlr.Parser -} - -func NewEmptyIpv6OctetContext() *Ipv6OctetContext { - var p = new(Ipv6OctetContext) - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv6Octet - return p -} - -func InitEmptyIpv6OctetContext(p *Ipv6OctetContext) { - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) - p.RuleIndex = HostsParserRULE_ipv6Octet -} - -func (*Ipv6OctetContext) IsIpv6OctetContext() {} - -func NewIpv6OctetContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *Ipv6OctetContext { - var p = new(Ipv6OctetContext) - - antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) - - p.parser = parser - p.RuleIndex = HostsParserRULE_ipv6Octet - - return p -} - -func (s *Ipv6OctetContext) GetParser() antlr.Parser { return s.parser } - -func (s *Ipv6OctetContext) OCTETS() antlr.TerminalNode { - return s.GetToken(HostsParserOCTETS, 0) -} - -func (s *Ipv6OctetContext) GetRuleContext() antlr.RuleContext { - return s -} - -func (s *Ipv6OctetContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { - return antlr.TreesStringTree(s, ruleNames, recog) -} - -func (s *Ipv6OctetContext) EnterRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.EnterIpv6Octet(s) - } -} - -func (s *Ipv6OctetContext) ExitRule(listener antlr.ParseTreeListener) { - if listenerT, ok := listener.(HostsListener); ok { - listenerT.ExitIpv6Octet(s) - } -} - -func (p *HostsParser) Ipv6Octet() (localctx IIpv6OctetContext) { - localctx = NewIpv6OctetContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 24, HostsParserRULE_ipv6Octet) - p.EnterOuterAlt(localctx, 1) - { - p.SetState(98) - p.Match(HostsParserOCTETS) - if p.HasError() { - // Recognition error - abort rule - goto errorExit } + + case antlr.ATNInvalidAltNumber: + goto errorExit } errorExit: @@ -2052,10 +1859,10 @@ func (s *IpRangeContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) IpRange() (localctx IIpRangeContext) { localctx = NewIpRangeContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 26, HostsParserRULE_ipRange) + p.EnterRule(localctx, 18, HostsParserRULE_ipRange) p.EnterOuterAlt(localctx, 1) { - p.SetState(100) + p.SetState(118) p.Match(HostsParserSLASH) if p.HasError() { // Recognition error - abort rule @@ -2063,7 +1870,7 @@ func (p *HostsParser) IpRange() (localctx IIpRangeContext) { } } { - p.SetState(101) + p.SetState(119) p.IpRangeBits() } @@ -2088,7 +1895,7 @@ type IIpRangeBitsContext interface { GetParser() antlr.Parser // Getter signatures - DIGITS() antlr.TerminalNode + STRING() antlr.TerminalNode // IsIpRangeBitsContext differentiates from other interfaces. IsIpRangeBitsContext() @@ -2126,8 +1933,8 @@ func NewIpRangeBitsContext(parser antlr.Parser, parent antlr.ParserRuleContext, func (s *IpRangeBitsContext) GetParser() antlr.Parser { return s.parser } -func (s *IpRangeBitsContext) DIGITS() antlr.TerminalNode { - return s.GetToken(HostsParserDIGITS, 0) +func (s *IpRangeBitsContext) STRING() antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, 0) } func (s *IpRangeBitsContext) GetRuleContext() antlr.RuleContext { @@ -2152,11 +1959,120 @@ func (s *IpRangeBitsContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) IpRangeBits() (localctx IIpRangeBitsContext) { localctx = NewIpRangeBitsContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 28, HostsParserRULE_ipRangeBits) + p.EnterRule(localctx, 20, HostsParserRULE_ipRangeBits) p.EnterOuterAlt(localctx, 1) { - p.SetState(103) - p.Match(HostsParserDIGITS) + p.SetState(121) + p.Match(HostsParserSTRING) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IIpPortContext is an interface to support dynamic dispatch. +type IIpPortContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + COLON() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsIpPortContext differentiates from other interfaces. + IsIpPortContext() +} + +type IpPortContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyIpPortContext() *IpPortContext { + var p = new(IpPortContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = HostsParserRULE_ipPort + return p +} + +func InitEmptyIpPortContext(p *IpPortContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = HostsParserRULE_ipPort +} + +func (*IpPortContext) IsIpPortContext() {} + +func NewIpPortContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *IpPortContext { + var p = new(IpPortContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = HostsParserRULE_ipPort + + return p +} + +func (s *IpPortContext) GetParser() antlr.Parser { return s.parser } + +func (s *IpPortContext) COLON() antlr.TerminalNode { + return s.GetToken(HostsParserCOLON, 0) +} + +func (s *IpPortContext) STRING() antlr.TerminalNode { + return s.GetToken(HostsParserSTRING, 0) +} + +func (s *IpPortContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *IpPortContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *IpPortContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(HostsListener); ok { + listenerT.EnterIpPort(s) + } +} + +func (s *IpPortContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(HostsListener); ok { + listenerT.ExitIpPort(s) + } +} + +func (p *HostsParser) IpPort() (localctx IIpPortContext) { + localctx = NewIpPortContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 22, HostsParserRULE_ipPort) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(123) + p.Match(HostsParserCOLON) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + { + p.SetState(124) + p.Match(HostsParserSTRING) if p.HasError() { // Recognition error - abort rule goto errorExit @@ -2248,10 +2164,10 @@ func (s *CommentContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) Comment() (localctx ICommentContext) { localctx = NewCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 30, HostsParserRULE_comment) + p.EnterRule(localctx, 24, HostsParserRULE_comment) p.EnterOuterAlt(localctx, 1) { - p.SetState(105) + p.SetState(126) p.Match(HostsParserCOMMENTLINE) if p.HasError() { // Recognition error - abort rule @@ -2344,10 +2260,10 @@ func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { func (p *HostsParser) LeadingComment() (localctx ILeadingCommentContext) { localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) - p.EnterRule(localctx, 32, HostsParserRULE_leadingComment) + p.EnterRule(localctx, 26, HostsParserRULE_leadingComment) p.EnterOuterAlt(localctx, 1) { - p.SetState(107) + p.SetState(128) p.Match(HostsParserCOMMENTLINE) if p.HasError() { // Recognition error - abort rule diff --git a/server/handlers/hosts/ast/parser_test.go b/server/handlers/hosts/ast/parser_test.go new file mode 100644 index 0000000..c62b075 --- /dev/null +++ b/server/handlers/hosts/ast/parser_test.go @@ -0,0 +1,51 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestParserInvalidWithPort( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4:80 hello.com +`) + parser := NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 1 { + t.Fatalf("Expected 1 error, but got %v", errors) + } +} + +func TestParserValidComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +1.2.3.4 hello.com alias.com example.com +1.2.3.5 hello1.com alias1.com example1.com +192.168.1.1 goodbye.com +`) + parser := NewHostsParser() + errors := parser.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, but got %v", errors) + } + + if !(parser.Tree.Entries.Size() == 3) { + t.Fatalf("Expected 3 entries, but got %v", parser.Tree.Entries.Size()) + } + + rawEntry, _ := parser.Tree.Entries.Get(uint32(0)) + entry := rawEntry.(*HostsEntry) + + if !(entry.IPAddress.Value.String() == "1.2.3.4") { + t.Errorf("Expected IP address to be 1.2.3.4, but got %v", entry.IPAddress.Value) + } + + if !(entry.Hostname.Value == "hello.com") { + t.Errorf("Expected hostname to be hello.com, but got %v", entry.Hostname.Value) + } +} diff --git a/handlers/hosts/fields/documentation-fields.go b/server/handlers/hosts/fields/documentation-fields.go similarity index 92% rename from handlers/hosts/fields/documentation-fields.go rename to server/handlers/hosts/fields/documentation-fields.go index 83837a8..9d15411 100644 --- a/handlers/hosts/fields/documentation-fields.go +++ b/server/handlers/hosts/fields/documentation-fields.go @@ -9,5 +9,5 @@ var IPAddressField = docvalues.IPAddressValue{ var HostnameField = docvalues.DocumentationValue{ Documentation: `Host names may contain only alphanumeric characters, minus signs ("-"), and periods ("."). They must begin with an alphabetic character and end with an alphanumeric character. Optional aliases provide for name changes, alternate spellings, shorter hostnames, or generic hostnames (for example, localhost).`, - Value: docvalues.DomainValue(), + Value: docvalues.StringValue{}, } diff --git a/handlers/hosts/handlers/code-actions.go b/server/handlers/hosts/handlers/code-actions.go similarity index 89% rename from handlers/hosts/handlers/code-actions.go rename to server/handlers/hosts/handlers/code-actions.go index 7618226..4d91dcf 100644 --- a/handlers/hosts/handlers/code-actions.go +++ b/server/handlers/hosts/handlers/code-actions.go @@ -36,14 +36,17 @@ func CodeActionInlineAliasesArgsFromArguments(arguments map[string]any) CodeActi } func (args CodeActionInlineAliasesArgs) RunCommand(hostsParser ast.HostsParser) (*protocol.ApplyWorkspaceEditParams, error) { - fromEntry := hostsParser.Tree.Entries[args.FromLine] - toEntry := hostsParser.Tree.Entries[args.ToLine] + rawFromEntry, foundFromEntry := hostsParser.Tree.Entries.Get(args.FromLine) + rawToEntry, foundToEntry := hostsParser.Tree.Entries.Get(args.ToLine) - if fromEntry == nil || toEntry == nil { + if !foundFromEntry || !foundToEntry { // Weird return nil, nil } + fromEntry := rawFromEntry.(*ast.HostsEntry) + toEntry := rawToEntry.(*ast.HostsEntry) + var insertCharacter uint32 if toEntry.Aliases != nil { diff --git a/handlers/hosts/handlers/fetch-code-actions.go b/server/handlers/hosts/handlers/fetch-code-actions.go similarity index 100% rename from handlers/hosts/handlers/fetch-code-actions.go rename to server/handlers/hosts/handlers/fetch-code-actions.go diff --git a/handlers/hosts/handlers/hover.go b/server/handlers/hosts/handlers/hover.go similarity index 74% rename from handlers/hosts/handlers/hover.go rename to server/handlers/hosts/handlers/hover.go index 50cc9cd..52b330b 100644 --- a/handlers/hosts/handlers/hover.go +++ b/server/handlers/hosts/handlers/hover.go @@ -1,6 +1,7 @@ package handlers import ( + "config-lsp/common" "config-lsp/handlers/hosts" "config-lsp/handlers/hosts/ast" "fmt" @@ -15,21 +16,21 @@ const ( ) func GetHoverTargetInEntry( + index common.IndexPosition, e ast.HostsEntry, - cursor uint32, ) *HoverTarget { - if e.IPAddress != nil && e.IPAddress.Location.ContainsCursorByCharacter(cursor) { + if e.IPAddress != nil && e.IPAddress.Location.ContainsPosition(index) { target := HoverTargetIPAddress return &target } - if e.Hostname != nil && e.Hostname.Location.ContainsCursorByCharacter(cursor) { + if e.Hostname != nil && e.Hostname.Location.ContainsPosition(index) { target := HoverTargetHostname return &target } for _, alias := range e.Aliases { - if alias.Location.ContainsCursorByCharacter(cursor) { + if alias.Location.ContainsPosition(index) { target := HoverTargetAlias return &target } @@ -39,9 +40,9 @@ func GetHoverTargetInEntry( } func GetHoverInfoForHostname( + index common.IndexPosition, d hosts.HostsDocument, hostname ast.HostsHostname, - cursor uint32, ) []string { ipAddress := d.Indexes.Resolver.Entries[hostname.Value] diff --git a/handlers/hosts/indexes/indexes.go b/server/handlers/hosts/indexes/indexes.go similarity index 100% rename from handlers/hosts/indexes/indexes.go rename to server/handlers/hosts/indexes/indexes.go diff --git a/handlers/hosts/indexes/resolver.go b/server/handlers/hosts/indexes/resolver.go similarity index 76% rename from handlers/hosts/indexes/resolver.go rename to server/handlers/hosts/indexes/resolver.go index aabb6f4..dc3655c 100644 --- a/handlers/hosts/indexes/resolver.go +++ b/server/handlers/hosts/indexes/resolver.go @@ -5,8 +5,8 @@ import ( ) type ResolverEntry struct { - IPv4Address net.IP - IPv6Address net.IP + IPv4Address *net.IP + IPv6Address *net.IP Line uint32 } @@ -19,5 +19,5 @@ func (e ResolverEntry) GetInfo() string { } type Resolver struct { - Entries map[string]ResolverEntry + Entries map[string]*ResolverEntry } diff --git a/handlers/hosts/lsp/text-document-code-action.go b/server/handlers/hosts/lsp/text-document-code-action.go similarity index 100% rename from handlers/hosts/lsp/text-document-code-action.go rename to server/handlers/hosts/lsp/text-document-code-action.go diff --git a/handlers/hosts/lsp/text-document-completion.go b/server/handlers/hosts/lsp/text-document-completion.go similarity index 100% rename from handlers/hosts/lsp/text-document-completion.go rename to server/handlers/hosts/lsp/text-document-completion.go diff --git a/handlers/hosts/lsp/text-document-did-change.go b/server/handlers/hosts/lsp/text-document-did-change.go similarity index 92% rename from handlers/hosts/lsp/text-document-did-change.go rename to server/handlers/hosts/lsp/text-document-did-change.go index af39187..e0504e1 100644 --- a/handlers/hosts/lsp/text-document-did-change.go +++ b/server/handlers/hosts/lsp/text-document-did-change.go @@ -29,10 +29,10 @@ func TextDocumentDidChange( return err.ToDiagnostic() }, )...) + } else { + diagnostics = append(diagnostics, analyzer.Analyze(document)...) } - diagnostics = append(diagnostics, analyzer.Analyze(document)...) - if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) } diff --git a/handlers/aliases/lsp/text-document-did-close.go b/server/handlers/hosts/lsp/text-document-did-close.go similarity index 100% rename from handlers/aliases/lsp/text-document-did-close.go rename to server/handlers/hosts/lsp/text-document-did-close.go diff --git a/handlers/hosts/lsp/text-document-did-open.go b/server/handlers/hosts/lsp/text-document-did-open.go similarity index 73% rename from handlers/hosts/lsp/text-document-did-open.go rename to server/handlers/hosts/lsp/text-document-did-open.go index 2e07550..6022344 100644 --- a/handlers/hosts/lsp/text-document-did-open.go +++ b/server/handlers/hosts/lsp/text-document-did-open.go @@ -7,6 +7,7 @@ import ( "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/indexes" "config-lsp/utils" + "github.com/tliron/glsp" protocol "github.com/tliron/glsp/protocol_3_16" ) @@ -26,18 +27,21 @@ func TextDocumentDidOpen( hosts.DocumentParserMap[params.TextDocument.URI] = &document errors := parser.Parse(params.TextDocument.Text) + diagnostics := make([]protocol.Diagnostic, 0) - diagnostics := utils.Map( - errors, - func(err common.LSPError) protocol.Diagnostic { - return err.ToDiagnostic() - }, - ) - - diagnostics = append( - diagnostics, - analyzer.Analyze(&document)..., - ) + if len(errors) > 0 { + diagnostics = utils.Map( + errors, + func(err common.LSPError) protocol.Diagnostic { + return err.ToDiagnostic() + }, + ) + } else { + diagnostics = append( + diagnostics, + analyzer.Analyze(&document)..., + ) + } if len(diagnostics) > 0 { common.SendDiagnostics(context, params.TextDocument.URI, diagnostics) diff --git a/handlers/hosts/lsp/text-document-hover.go b/server/handlers/hosts/lsp/text-document-hover.go similarity index 69% rename from handlers/hosts/lsp/text-document-hover.go rename to server/handlers/hosts/lsp/text-document-hover.go index 1c6484e..7fcbe53 100644 --- a/handlers/hosts/lsp/text-document-hover.go +++ b/server/handlers/hosts/lsp/text-document-hover.go @@ -1,6 +1,7 @@ package lsp import ( + "config-lsp/common" "config-lsp/handlers/hosts" "config-lsp/handlers/hosts/ast" "config-lsp/handlers/hosts/fields" @@ -18,28 +19,30 @@ func TextDocumentHover( document := hosts.DocumentParserMap[params.TextDocument.URI] line := params.Position.Line - character := params.Position.Character + index := common.LSPCharacterAsIndexPosition(params.Position.Character) if _, found := document.Parser.CommentLines[line]; found { // Comment return nil, nil } - entry, found := document.Parser.Tree.Entries[line] + rawEntry, found := document.Parser.Tree.Entries.Get(line) if !found { // Empty line return nil, nil } - target := handlers.GetHoverTargetInEntry(*entry, character) + entry := rawEntry.(*ast.HostsEntry) + target := handlers.GetHoverTargetInEntry(index, *entry) var hostname *ast.HostsHostname switch *target { case handlers.HoverTargetIPAddress: - relativeCursor := character - entry.IPAddress.Location.Start.Character - hover := fields.IPAddressField.FetchHoverInfo(entry.IPAddress.Value.String(), relativeCursor) + line := entry.IPAddress.Value.String() + relativeCursor := uint32(entry.IPAddress.Location.Start.GetRelativeIndexPosition(index)) + hover := fields.IPAddressField.DeprecatedFetchHoverInfo(line, relativeCursor) return &protocol.Hover{ Contents: hover, @@ -48,7 +51,7 @@ func TextDocumentHover( hostname = entry.Hostname case handlers.HoverTargetAlias: for _, alias := range entry.Aliases { - if alias.Location.Start.Character <= character && character <= alias.Location.End.Character { + if alias.Location.ContainsPosition(index) { hostname = alias break } @@ -75,7 +78,13 @@ func TextDocumentHover( ) contents = append( contents, - handlers.GetHoverInfoForHostname(*document, *hostname, character)..., + []string{ + "", + }..., + ) + contents = append( + contents, + handlers.GetHoverInfoForHostname(index, *document, *hostname)..., ) return &protocol.Hover{ diff --git a/handlers/hosts/lsp/workspace-execute-command.go b/server/handlers/hosts/lsp/workspace-execute-command.go similarity index 100% rename from handlers/hosts/lsp/workspace-execute-command.go rename to server/handlers/hosts/lsp/workspace-execute-command.go diff --git a/handlers/hosts/shared.go b/server/handlers/hosts/shared.go similarity index 100% rename from handlers/hosts/shared.go rename to server/handlers/hosts/shared.go diff --git a/handlers/hosts/shared/errors.go b/server/handlers/hosts/shared/errors.go similarity index 100% rename from handlers/hosts/shared/errors.go rename to server/handlers/hosts/shared/errors.go diff --git a/handlers/index.go b/server/handlers/index.go similarity index 100% rename from handlers/index.go rename to server/handlers/index.go diff --git a/server/handlers/ssh_config/Config.g4 b/server/handlers/ssh_config/Config.g4 new file mode 100644 index 0000000..3033862 --- /dev/null +++ b/server/handlers/ssh_config/Config.g4 @@ -0,0 +1,51 @@ +grammar Config; + +lineStatement + : (entry | leadingComment | WHITESPACE?) EOF + ; + +entry + : WHITESPACE? key? separator? value? leadingComment? + ; + +separator + : WHITESPACE + ; + +key + : string + ; + +value + : (string WHITESPACE)* string? WHITESPACE? + ; + +leadingComment + : HASH WHITESPACE? (string WHITESPACE?)+ + ; + +string + : (QUOTED_STRING | STRING) + ; + +/////////////////////////////////////////////// + +HASH + : '#' + ; + +WHITESPACE + : [ \t]+ + ; + +STRING + : ~('#' | '\r' | '\n' | '"' | ' ' | '\t')+ + ; + +NEWLINE + : '\r'? '\n' + ; + +QUOTED_STRING + : '"' WHITESPACE? (STRING WHITESPACE)* STRING? ('"')? + ; diff --git a/server/handlers/ssh_config/analyzer/analyzer.go b/server/handlers/ssh_config/analyzer/analyzer.go new file mode 100644 index 0000000..48adb23 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/analyzer.go @@ -0,0 +1,49 @@ +package analyzer + +import ( + "config-lsp/common" + sshconfig "config-lsp/handlers/ssh_config" + "config-lsp/handlers/ssh_config/indexes" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +type analyzerContext struct { + document *sshconfig.SSHDocument + diagnostics []protocol.Diagnostic +} + +func Analyze( + d *sshconfig.SSHDocument, +) []protocol.Diagnostic { + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) > 0 { + return ctx.diagnostics + } + + i, indexErrors := indexes.CreateIndexes(*d.Config) + + if len(indexErrors) > 0 { + return common.ErrsToDiagnostics(indexErrors) + } + + d.Indexes = i + + analyzeValuesAreValid(ctx) + analyzeIgnoreUnknownHasNoUnnecessary(ctx) + analyzeDependents(ctx) + analyzeBlocks(ctx) + analyzeMatchBlocks(ctx) + analyzeHostBlock(ctx) + analyzeBlocks(ctx) + analyzeTagOptions(ctx) + analyzeTagImports(ctx) + + return ctx.diagnostics +} diff --git a/server/handlers/ssh_config/analyzer/block.go b/server/handlers/ssh_config/analyzer/block.go new file mode 100644 index 0000000..02c9acc --- /dev/null +++ b/server/handlers/ssh_config/analyzer/block.go @@ -0,0 +1,29 @@ +package analyzer + +import ( + "config-lsp/common" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeBlocks( + ctx *analyzerContext, +) { + for _, block := range ctx.document.GetAllBlocks() { + if block == nil { + continue + } + + // Check if block is empty + if block.GetOptions().Size() == 0 { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: block.GetEntryOption().LocationRange.ToLSPRange(), + Message: "This block is empty", + Severity: &common.SeverityHint, + Tags: []protocol.DiagnosticTag{ + protocol.DiagnosticTagUnnecessary, + }, + }) + } + } +} diff --git a/server/handlers/ssh_config/analyzer/block_test.go b/server/handlers/ssh_config/analyzer/block_test.go new file mode 100644 index 0000000..4d09361 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/block_test.go @@ -0,0 +1,26 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestBlockEmptyBlock( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host * +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeBlocks(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected an error, but got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/dependents.go b/server/handlers/ssh_config/analyzer/dependents.go new file mode 100644 index 0000000..ad838da --- /dev/null +++ b/server/handlers/ssh_config/analyzer/dependents.go @@ -0,0 +1,47 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeDependents( + ctx *analyzerContext, +) { + for _, option := range ctx.document.Config.GetAllOptions() { + checkIsDependent(ctx, option.Option.Key, option.Block) + } +} + +func checkIsDependent( + ctx *analyzerContext, + key *ast.SSHKey, + block ast.SSHBlock, +) { + dependentOptions, found := fields.DependentFields[key.Key] + + if !found { + return + } + + for _, dependentOption := range dependentOptions { + if opts, found := ctx.document.Indexes.AllOptionsPerName[dependentOption]; found { + _, existsInBlock := opts[block] + _, existsInGlobal := opts[nil] + + if existsInBlock || existsInGlobal { + continue + } + } + + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: key.LocationRange.ToLSPRange(), + Message: fmt.Sprintf("Option '%s' requires option '%s' to be present", key.Key, dependentOption), + Severity: &common.SeverityError, + }) + } +} diff --git a/server/handlers/ssh_config/analyzer/dependents_test.go b/server/handlers/ssh_config/analyzer/dependents_test.go new file mode 100644 index 0000000..d573d4f --- /dev/null +++ b/server/handlers/ssh_config/analyzer/dependents_test.go @@ -0,0 +1,45 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleDependentExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +CanonicalDomains test.com +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeDependents(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestSimpleDependentExistsExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +CanonicalizeHostname yes +CanonicalDomains test.com +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeDependents(ctx) + + if len(ctx.diagnostics) > 0 { + t.Errorf("Expected no errors, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/host.go b/server/handlers/ssh_config/analyzer/host.go new file mode 100644 index 0000000..0fcc94c --- /dev/null +++ b/server/handlers/ssh_config/analyzer/host.go @@ -0,0 +1,44 @@ +package analyzer + +import ( + "cmp" + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast" + hostparser "config-lsp/handlers/ssh_config/host-parser" + "fmt" + "slices" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeHostBlock( + ctx *analyzerContext, +) { + hosts := make(map[string]*hostparser.HostValue, 0) + + blocks := ctx.document.GetAllHostBlocks() + slices.SortFunc( + blocks, + func(a, b *ast.SSHHostBlock) int { + return cmp.Compare(a.Start.Line, b.Start.Line) + }, + ) + + for _, block := range blocks { + if block == nil || block.HostValue == nil { + continue + } + + for _, host := range block.HostValue.Hosts { + if _, found := hosts[host.Value.Value]; found { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: host.ToLSPRange(), + Message: fmt.Sprintf("Host %s has already been defined on line %d", host.Value.Value, hosts[host.Value.Value].Start.Line+1), + Severity: &common.SeverityError, + }) + } else { + hosts[host.Value.Value] = host + } + } + } +} diff --git a/server/handlers/ssh_config/analyzer/host_test.go b/server/handlers/ssh_config/analyzer/host_test.go new file mode 100644 index 0000000..3ffe56c --- /dev/null +++ b/server/handlers/ssh_config/analyzer/host_test.go @@ -0,0 +1,74 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestDuplicateHostExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host example.com + User root + +Host example.com + User test +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeHostBlock(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestDuplicateMultipleHostExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host example.com google.com + User root + +Host test.com example.com + User test +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeHostBlock(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestNonDuplicateHostExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host example.com + User root + +Host example2.com + User test +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeHostBlock(ctx) + + if !(len(ctx.diagnostics) == 0) { + t.Errorf("Expected 0 error, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/ignore_unknown.go b/server/handlers/ssh_config/analyzer/ignore_unknown.go new file mode 100644 index 0000000..3e78749 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/ignore_unknown.go @@ -0,0 +1,39 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/fields" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var ignoreUnknownOption = fields.CreateNormalizedName("IgnoreUnknown") + +func analyzeIgnoreUnknownHasNoUnnecessary( + ctx *analyzerContext, +) { + for _, block := range ctx.document.GetAllBlocks() { + ignoreUnknown, found := ctx.document.Indexes.IgnoredOptions[block] + + if !found { + // No `IgnoreUnknown` option specified + continue + } + + for optionName, ignoreInfo := range ignoreUnknown.IgnoredOptions { + info := ctx.document.FindOptionByNameAndBlock(optionName, block) + + if info == nil { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: ignoreInfo.ToLSPRange(), + Message: fmt.Sprintf("Option %s is not present", optionName), + Tags: []protocol.DiagnosticTag{ + protocol.DiagnosticTagUnnecessary, + }, + Severity: &common.SeverityHint, + }) + } + } + } +} diff --git a/server/handlers/ssh_config/analyzer/ignore_unknown_test.go b/server/handlers/ssh_config/analyzer/ignore_unknown_test.go new file mode 100644 index 0000000..e2b079f --- /dev/null +++ b/server/handlers/ssh_config/analyzer/ignore_unknown_test.go @@ -0,0 +1,26 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestIgnoreUnknownUnnecessary( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +IgnoreUnknown helloWorld +PermitRootLogin 'yes' +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + analyzeIgnoreUnknownHasNoUnnecessary(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/match.go b/server/handlers/ssh_config/analyzer/match.go new file mode 100644 index 0000000..9865201 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/match.go @@ -0,0 +1,93 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/fields" + matchparser "config-lsp/handlers/ssh_config/match-parser" + "config-lsp/utils" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeMatchBlocks( + ctx *analyzerContext, +) { + for _, matchBlock := range ctx.document.GetAllMatchBlocks() { + isValid := isMatchStructureValid(ctx, matchBlock.MatchValue) + + if !isValid { + continue + } + + checkMatch(ctx, matchBlock.MatchValue) + } +} + +func isMatchStructureValid( + ctx *analyzerContext, + m *matchparser.Match, +) bool { + isValid := true + + for _, entry := range m.Entries { + if !utils.KeyExists(fields.MatchSingleOptionCriterias, entry.Criteria.Type) && entry.Value.Value == "" { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: entry.LocationRange.ToLSPRange(), + Message: fmt.Sprintf("Argument '%s' requires a value", entry.Criteria.Type), + Severity: &common.SeverityError, + }) + + isValid = false + } + } + + return isValid +} + +func checkMatch( + ctx *analyzerContext, + m *matchparser.Match, +) { + // Check single options + allEntries := m.FindEntries("all") + if len(allEntries) > 1 { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: allEntries[1].LocationRange.ToLSPRange(), + Message: "'all' may only be used once", + Severity: &common.SeverityError, + }) + } + + canonicalEntries := m.FindEntries("canonical") + if len(canonicalEntries) > 1 { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: canonicalEntries[1].LocationRange.ToLSPRange(), + Message: "'canonical' may only be used once", + Severity: &common.SeverityError, + }) + } + + finalEntries := m.FindEntries("final") + if len(finalEntries) > 1 { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: finalEntries[1].LocationRange.ToLSPRange(), + Message: "'final' may only be used once", + Severity: &common.SeverityError, + }) + } + + // Check the `all` argument + if len(allEntries) == 1 { + allEntry := allEntries[0] + previousEntry := m.GetPreviousEntry(allEntry) + + if previousEntry != nil && !utils.KeyExists(fields.MatchAllArgumentAllowedPreviousOptions, previousEntry.Criteria.Type) { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: allEntry.LocationRange.ToLSPRange(), + Message: "'all' should either be the first entry or immediately follow 'final' or 'canonical'", + Severity: &common.SeverityError, + }) + } + } +} diff --git a/server/handlers/ssh_config/analyzer/match_test.go b/server/handlers/ssh_config/analyzer/match_test.go new file mode 100644 index 0000000..a1278a7 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/match_test.go @@ -0,0 +1,26 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestMatchInvalidAllArgument( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Match user lena all +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeMatchBlocks(ctx) + + if !(len(ctx.diagnostics) == 1 && ctx.diagnostics[0].Range.Start.Line == 0) { + t.Fatalf("Expected one error, got %v", ctx.diagnostics) + } +} diff --git a/server/handlers/ssh_config/analyzer/options.go b/server/handlers/ssh_config/analyzer/options.go new file mode 100644 index 0000000..34dc670 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/options.go @@ -0,0 +1,90 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "config-lsp/utils" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeStructureIsValid( + ctx *analyzerContext, +) { + it := ctx.document.Config.Options.Iterator() + + for it.Next() { + entry := it.Value().(ast.SSHEntry) + + switch entry.(type) { + case *ast.SSHOption: + checkOption(ctx, entry.(*ast.SSHOption), nil) + case *ast.SSHMatchBlock: + matchBlock := entry.(*ast.SSHMatchBlock) + checkBlock(ctx, matchBlock) + case *ast.SSHHostBlock: + hostBlock := entry.(*ast.SSHHostBlock) + checkBlock(ctx, hostBlock) + } + + } +} + +func checkOption( + ctx *analyzerContext, + option *ast.SSHOption, + block ast.SSHBlock, +) { + checkIsUsingDoubleQuotes(ctx, option.Key.Value, option.Key.LocationRange) + checkQuotesAreClosed(ctx, option.Key.Value, option.Key.LocationRange) + + _, found := fields.Options[option.Key.Key] + + if !found { + // Diagnostics will be handled by `values.go` + return + } + + // Check for values that are not allowed in Host blocks + if block != nil && block.GetBlockType() == ast.SSHBlockTypeHost { + if utils.KeyExists(fields.HostDisallowedOptions, option.Key.Key) { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: option.Key.LocationRange.ToLSPRange(), + Message: fmt.Sprintf("Option '%s' is not allowed in Host blocks", option.Key.Key), + Severity: &common.SeverityError, + }) + } + } + + if option.OptionValue != nil { + checkIsUsingDoubleQuotes(ctx, option.OptionValue.Value, option.OptionValue.LocationRange) + checkQuotesAreClosed(ctx, option.OptionValue.Value, option.OptionValue.LocationRange) + } + + if option.Separator == nil || option.Separator.Value.Value == "" { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: option.Key.LocationRange.ToLSPRange(), + Message: fmt.Sprintf("There should be a separator between an option and its value"), + Severity: &common.SeverityError, + }) + } else { + checkIsUsingDoubleQuotes(ctx, option.Separator.Value, option.Separator.LocationRange) + checkQuotesAreClosed(ctx, option.Separator.Value, option.Separator.LocationRange) + } +} + +func checkBlock( + ctx *analyzerContext, + block ast.SSHBlock, +) { + checkOption(ctx, block.GetEntryOption(), block) + + it := block.GetOptions().Iterator() + for it.Next() { + option := it.Value().(*ast.SSHOption) + + checkOption(ctx, option, block) + } +} diff --git a/server/handlers/ssh_config/analyzer/options_test.go b/server/handlers/ssh_config/analyzer/options_test.go new file mode 100644 index 0000000..e7a1301 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/options_test.go @@ -0,0 +1,114 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ProxyCommand hello + +User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) != 0 { + t.Fatalf("Expected no errors, got %v", ctx.diagnostics) + } +} + +func TestOptionEmpty( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ProxyCommand + +User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) != 0 { + t.Fatalf("Expected no errors, got %v", ctx.diagnostics) + } +} + +func TestNoSeparator( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +"ProxyCommand""hello" + +User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) != 1 { + t.Fatalf("Expected 1 error, got %v", ctx.diagnostics) + } +} + +func TestEmptyMatch( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +User root + +Host example.com + User test + +Match +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) != 1 { + t.Fatalf("Expected 1 error, got %v", ctx.diagnostics) + } +} + +func TestEmptyWithSeparatorMatch( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +User root + +Host example.com + User test + +Match +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeStructureIsValid(ctx) + + if len(ctx.diagnostics) != 0 { + t.Fatalf("Expected no errors, got %v", ctx.diagnostics) + } +} diff --git a/server/handlers/ssh_config/analyzer/quotes.go b/server/handlers/ssh_config/analyzer/quotes.go new file mode 100644 index 0000000..945bd1a --- /dev/null +++ b/server/handlers/ssh_config/analyzer/quotes.go @@ -0,0 +1,54 @@ +package analyzer + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + "config-lsp/utils" + "strings" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeQuotesAreValid( + ctx *analyzerContext, +) { + for _, info := range ctx.document.Config.GetAllOptions() { + checkIsUsingDoubleQuotes(ctx, info.Option.Key.Value, info.Option.Key.LocationRange) + checkIsUsingDoubleQuotes(ctx, info.Option.OptionValue.Value, info.Option.OptionValue.LocationRange) + + checkQuotesAreClosed(ctx, info.Option.Key.Value, info.Option.Key.LocationRange) + checkQuotesAreClosed(ctx, info.Option.OptionValue.Value, info.Option.OptionValue.LocationRange) + } +} + +func checkIsUsingDoubleQuotes( + ctx *analyzerContext, + value commonparser.ParsedString, + valueRange common.LocationRange, +) { + quoteRanges := utils.GetQuoteRanges(value.Raw) + singleQuotePosition := strings.Index(value.Raw, "'") + + // Single quote + if singleQuotePosition != -1 && !quoteRanges.IsCharInside(singleQuotePosition) { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: valueRange.ToLSPRange(), + Message: "ssh_config does not support single quotes. Use double quotes (\") instead.", + Severity: &common.SeverityError, + }) + } +} + +func checkQuotesAreClosed( + ctx *analyzerContext, + value commonparser.ParsedString, + valueRange common.LocationRange, +) { + if strings.Count(value.Raw, "\"")%2 != 0 { + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: valueRange.ToLSPRange(), + Message: "There are unclosed quotes here. Make sure all quotes are closed.", + Severity: &common.SeverityError, + }) + } +} diff --git a/server/handlers/ssh_config/analyzer/quotes_test.go b/server/handlers/ssh_config/analyzer/quotes_test.go new file mode 100644 index 0000000..accb08a --- /dev/null +++ b/server/handlers/ssh_config/analyzer/quotes_test.go @@ -0,0 +1,117 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestSimpleInvalidQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin 'yes' +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + analyzeQuotesAreValid(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestSingleQuotesKeyAndOptionExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +'Port' '22' +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + analyzeQuotesAreValid(ctx) + + if !(len(ctx.diagnostics) == 2) { + t.Errorf("Expected 2 ctx.diagnostics, got %v", len(ctx.diagnostics)) + } +} + +func TestSimpleUnclosedQuoteExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +PermitRootLogin "yes +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + analyzeQuotesAreValid(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestIncompleteQuotesExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +"Port +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + analyzeQuotesAreValid(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestDependentOptionsExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Port 1234 +CanonicalDomains example.com +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + option := d.FindOptionsByName("canonicaldomains")[0] + checkIsDependent(ctx, option.Option.Key, option.Block) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} + +func TestValidDependentOptionsExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Port 1234 +CanonicalizeHostname yes +CanonicalDomains example.com +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + option := d.FindOptionsByName("canonicaldomains")[0] + checkIsDependent(ctx, option.Option.Key, option.Block) + + if len(ctx.diagnostics) > 0 { + t.Errorf("Expected no errors, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/tag_imports.go b/server/handlers/ssh_config/analyzer/tag_imports.go new file mode 100644 index 0000000..ce0713b --- /dev/null +++ b/server/handlers/ssh_config/analyzer/tag_imports.go @@ -0,0 +1,33 @@ +package analyzer + +import ( + "config-lsp/common" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeTagImports( + ctx *analyzerContext, +) { + for name, info := range ctx.document.Indexes.Tags { + if _, found := ctx.document.Indexes.TagImports[name]; !found { + var diagnosticRange protocol.Range + + if len(info.Block.MatchValue.Entries) == 1 { + diagnosticRange = info.Block.MatchOption.ToLSPRange() + } else { + diagnosticRange = info.EntryValue.ToLSPRange() + } + + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: diagnosticRange, + Message: fmt.Sprintf("Tag %s is not used", name), + Severity: &common.SeverityWarning, + Tags: []protocol.DiagnosticTag{ + protocol.DiagnosticTagUnnecessary, + }, + }) + } + } +} diff --git a/server/handlers/ssh_config/analyzer/tag_imports_test.go b/server/handlers/ssh_config/analyzer/tag_imports_test.go new file mode 100644 index 0000000..d3783b7 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/tag_imports_test.go @@ -0,0 +1,49 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestUsedTagImportsExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host test.com + Tag auth + +Match tagged auth + User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeTagImports(ctx) + + if len(ctx.diagnostics) > 0 { + t.Errorf("Expected no errors, got %v", len(ctx.diagnostics)) + } +} + +func TestUnusedTagImportsExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Match tagged auth + User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeTagImports(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/tag_options.go b/server/handlers/ssh_config/analyzer/tag_options.go new file mode 100644 index 0000000..e94356c --- /dev/null +++ b/server/handlers/ssh_config/analyzer/tag_options.go @@ -0,0 +1,32 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/fields" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +var tagOption = fields.CreateNormalizedName("Tag") + +func analyzeTagOptions( + ctx *analyzerContext, +) { + // Check if the specified tags actually exist + for _, options := range ctx.document.Indexes.AllOptionsPerName[tagOption] { + for _, option := range options { + tag, found := ctx.document.Indexes.Tags[option.OptionValue.Value.Value] + + if found && tag.Block.Start.Line > option.Start.Line { + continue + } + + ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{ + Range: option.OptionValue.ToLSPRange(), + Message: fmt.Sprintf("Unknown tag: %s", option.OptionValue.Value.Value), + Severity: &common.SeverityError, + }) + } + } +} diff --git a/server/handlers/ssh_config/analyzer/tag_options_test.go b/server/handlers/ssh_config/analyzer/tag_options_test.go new file mode 100644 index 0000000..e7ef97c --- /dev/null +++ b/server/handlers/ssh_config/analyzer/tag_options_test.go @@ -0,0 +1,52 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestValidTagExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Host test.com + Tag auth + +Match tagged auth + User root +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeTagOptions(ctx) + + if len(ctx.diagnostics) > 0 { + t.Errorf("Expected no errors, got %v", len(ctx.diagnostics)) + } +} + +func TestTagBlockBeforeExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +Match tagged auth + User root + +Host test.com + Tag auth +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeTagOptions(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } +} diff --git a/server/handlers/ssh_config/analyzer/values.go b/server/handlers/ssh_config/analyzer/values.go new file mode 100644 index 0000000..4752220 --- /dev/null +++ b/server/handlers/ssh_config/analyzer/values.go @@ -0,0 +1,38 @@ +package analyzer + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/fields" + "fmt" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func analyzeValuesAreValid( + ctx *analyzerContext, +) { + for _, info := range ctx.document.Config.GetAllOptions() { + option := info.Option + block := info.Block + + _, found := fields.Options[option.Key.Key] + + if !found { + if ctx.document.Indexes.CanOptionBeIgnored(option, block) { + // Skip + continue + } + + ctx.diagnostics = append(ctx.diagnostics, + protocol.Diagnostic{ + Range: option.Key.ToLSPRange(), + Message: fmt.Sprintf("Unknown option: %s", option.Key.Value.Value), + Severity: &common.SeverityError, + }, + ) + ctx.document.Indexes.UnknownOptions[info.Option.Start.Line] = info + + continue + } + } +} diff --git a/server/handlers/ssh_config/analyzer/values_test.go b/server/handlers/ssh_config/analyzer/values_test.go new file mode 100644 index 0000000..88bffcc --- /dev/null +++ b/server/handlers/ssh_config/analyzer/values_test.go @@ -0,0 +1,84 @@ +package analyzer + +import ( + testutils_test "config-lsp/handlers/ssh_config/test_utils" + "testing" + + protocol "github.com/tliron/glsp/protocol_3_16" +) + +func TestUnknownOptionExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ThisOptionDoesNotExist okay +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeValuesAreValid(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } + + if !(len(ctx.document.Indexes.UnknownOptions) == 1) { + t.Errorf("Expected 1 unknown option, got %v", len(ctx.document.Indexes.UnknownOptions)) + } + + if !(ctx.document.Indexes.UnknownOptions[0].Option.Key.Value.Value == "ThisOptionDoesNotExist") { + t.Errorf("Expected 'ThisOptionDoesNotExist', got %v", ctx.document.Indexes.UnknownOptions[0].Option.Key.Value.Value) + } +} + +func TestUnknownOptionButIgnoredExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +IgnoreUnknown ThisOptionDoesNotExist +ThisOptionDoesNotExist okay +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeValuesAreValid(ctx) + + if len(ctx.diagnostics) > 0 { + t.Fatalf("Expected no errors, but got %v", len(ctx.diagnostics)) + } + + if !(len(ctx.document.Indexes.UnknownOptions) == 0) { + t.Errorf("Expected 0 unknown options, got %v", len(ctx.document.Indexes.UnknownOptions)) + } +} + +func TestUnknownOptionIgnoredIsAfterDefinitionExample( + t *testing.T, +) { + d := testutils_test.DocumentFromInput(t, ` +ThisOptionDoesNotExist okay +IgnoreUnknown ThisOptionDoesNotExist +`) + ctx := &analyzerContext{ + document: d, + diagnostics: make([]protocol.Diagnostic, 0), + } + + analyzeValuesAreValid(ctx) + + if !(len(ctx.diagnostics) == 1) { + t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics)) + } + + if !(len(ctx.document.Indexes.UnknownOptions) == 1) { + t.Errorf("Expected 1 unknown option, got %v", len(ctx.document.Indexes.UnknownOptions)) + } + + if !(ctx.document.Indexes.UnknownOptions[0].Option.Key.Value.Value == "ThisOptionDoesNotExist") { + t.Errorf("Expected 'ThisOptionDoesNotExist', got %v", ctx.document.Indexes.UnknownOptions[0].Option.Key.Value.Value) + } +} diff --git a/server/handlers/ssh_config/ast/error-listener.go b/server/handlers/ssh_config/ast/error-listener.go new file mode 100644 index 0000000..74d4387 --- /dev/null +++ b/server/handlers/ssh_config/ast/error-listener.go @@ -0,0 +1,45 @@ +package ast + +import ( + "config-lsp/common" + + "github.com/antlr4-go/antlr/v4" +) + +type errorListenerContext struct { + line uint32 +} + +type errorListener struct { + *antlr.DefaultErrorListener + Errors []common.LSPError + context errorListenerContext +} + +func (d *errorListener) SyntaxError( + recognizer antlr.Recognizer, + offendingSymbol interface{}, + _ int, + character int, + message string, + error antlr.RecognitionException, +) { + line := d.context.line + d.Errors = append(d.Errors, common.LSPError{ + Range: common.CreateSingleCharRange(uint32(line), uint32(character)), + Err: common.SyntaxError{ + Message: message, + }, + }) +} + +func createErrorListener( + line uint32, +) errorListener { + return errorListener{ + Errors: make([]common.LSPError, 0), + context: errorListenerContext{ + line: line, + }, + } +} diff --git a/server/handlers/ssh_config/ast/listener.go b/server/handlers/ssh_config/ast/listener.go new file mode 100644 index 0000000..ae56143 --- /dev/null +++ b/server/handlers/ssh_config/ast/listener.go @@ -0,0 +1,207 @@ +package ast + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + "config-lsp/handlers/ssh_config/ast/parser" + "config-lsp/handlers/ssh_config/fields" + hostparser "config-lsp/handlers/ssh_config/host-parser" + "config-lsp/handlers/ssh_config/match-parser" + "strings" + + "github.com/emirpasic/gods/maps/treemap" + gods "github.com/emirpasic/gods/utils" +) + +type sshListenerContext struct { + line uint32 + currentOption *SSHOption + currentBlock SSHBlock + currentKeyIsBlockOf *SSHBlockType +} + +func createListenerContext() *sshListenerContext { + context := new(sshListenerContext) + + return context +} + +func createListener( + config *SSHConfig, + context *sshListenerContext, +) sshParserListener { + return sshParserListener{ + Config: config, + Errors: make([]common.LSPError, 0), + sshContext: context, + } +} + +type sshParserListener struct { + *parser.BaseConfigListener + Config *SSHConfig + Errors []common.LSPError + sshContext *sshListenerContext +} + +func (s *sshParserListener) EnterEntry(ctx *parser.EntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + option := &SSHOption{ + LocationRange: location, + Value: value, + } + + s.sshContext.currentOption = option +} + +func (s *sshParserListener) EnterKey(ctx *parser.KeyContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + key := fields.CreateNormalizedName(strings.Trim( + value.Value, + " ", + )) + + switch strings.ToLower(text) { + case "match": + value := SSHBlockTypeMatch + s.sshContext.currentKeyIsBlockOf = &value + case "host": + value := SSHBlockTypeHost + s.sshContext.currentKeyIsBlockOf = &value + } + + s.sshContext.currentOption.Key = &SSHKey{ + LocationRange: location, + Value: value, + Key: key, + } +} + +func (s *sshParserListener) EnterSeparator(ctx *parser.SeparatorContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + text := ctx.GetText() + value := commonparser.ParseRawString(text, commonparser.FullFeatures) + + s.sshContext.currentOption.Separator = &SSHSeparator{ + LocationRange: location, + Value: value, + } +} + +func (s *sshParserListener) EnterValue(ctx *parser.ValueContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + value := commonparser.ParseRawString(ctx.GetText(), commonparser.FullFeatures) + s.sshContext.currentOption.OptionValue = &SSHValue{ + LocationRange: location, + Value: value, + } +} + +func (s *sshParserListener) ExitEntry(ctx *parser.EntryContext) { + location := common.CharacterRangeFromCtx(ctx.BaseParserRuleContext) + location.ChangeBothLines(s.sshContext.line) + + defer (func() { + s.sshContext.currentOption = nil + })() + + if s.sshContext.currentKeyIsBlockOf != nil { + switch *s.sshContext.currentKeyIsBlockOf { + case SSHBlockTypeMatch: + var match *matchparser.Match + + matchParser := matchparser.NewMatch() + errors := matchParser.Parse( + s.sshContext.currentOption.OptionValue.Value.Raw, + location.Start.Line, + s.sshContext.currentOption.OptionValue.Start.Character, + ) + + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range, + Err: err.Err, + }) + } + } else { + match = matchParser + } + + matchBlock := &SSHMatchBlock{ + LocationRange: location, + MatchOption: s.sshContext.currentOption, + MatchValue: match, + Options: treemap.NewWith(gods.UInt32Comparator), + } + + s.Config.Options.Put( + location.Start.Line, + matchBlock, + ) + + s.sshContext.currentKeyIsBlockOf = nil + s.sshContext.currentBlock = matchBlock + + case SSHBlockTypeHost: + var host *hostparser.Host + + hostParser := hostparser.NewHost() + errors := hostParser.Parse( + s.sshContext.currentOption.OptionValue.Value.Raw, + location.Start.Line, + s.sshContext.currentOption.OptionValue.Start.Character, + ) + + if len(errors) > 0 { + for _, err := range errors { + s.Errors = append(s.Errors, common.LSPError{ + Range: err.Range, + Err: err.Err, + }) + } + } else { + host = hostParser + } + + hostBlock := &SSHHostBlock{ + LocationRange: location, + HostOption: s.sshContext.currentOption, + HostValue: host, + Options: treemap.NewWith(gods.UInt32Comparator), + } + + s.Config.Options.Put( + location.Start.Line, + hostBlock, + ) + + s.sshContext.currentKeyIsBlockOf = nil + s.sshContext.currentBlock = hostBlock + } + + return + } + + if s.sshContext.currentBlock == nil { + s.Config.Options.Put( + location.Start.Line, + s.sshContext.currentOption, + ) + } else { + block := s.sshContext.currentBlock + block.AddOption(s.sshContext.currentOption) + block.SetEnd(location.End) + } +} diff --git a/server/handlers/ssh_config/ast/parser.go b/server/handlers/ssh_config/ast/parser.go new file mode 100644 index 0000000..c6298d7 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser.go @@ -0,0 +1,85 @@ +package ast + +import ( + "config-lsp/common" + "config-lsp/handlers/ssh_config/ast/parser" + "config-lsp/utils" + "regexp" + + "github.com/antlr4-go/antlr/v4" + "github.com/emirpasic/gods/maps/treemap" + + gods "github.com/emirpasic/gods/utils" +) + +func NewSSHConfig() *SSHConfig { + config := &SSHConfig{} + config.Clear() + + return config +} + +func (c *SSHConfig) Clear() { + c.Options = treemap.NewWith(gods.UInt32Comparator) + c.CommentLines = map[uint32]struct{}{} +} + +var commentPattern = regexp.MustCompile(`^\s*#.*$`) +var emptyPattern = regexp.MustCompile(`^\s*$`) + +func (c *SSHConfig) Parse(input string) []common.LSPError { + errors := make([]common.LSPError, 0) + lines := utils.SplitIntoLines(input) + context := createListenerContext() + + for rawLineNumber, line := range lines { + context.line = uint32(rawLineNumber) + + if emptyPattern.MatchString(line) { + continue + } + + if commentPattern.MatchString(line) { + c.CommentLines[context.line] = struct{}{} + continue + } + + errors = append( + errors, + c.parseStatement(context, line)..., + ) + } + + return errors +} + +func (c *SSHConfig) parseStatement( + context *sshListenerContext, + input string, +) []common.LSPError { + stream := antlr.NewInputStream(input) + + lexerErrorListener := createErrorListener(context.line) + lexer := parser.NewConfigLexer(stream) + lexer.RemoveErrorListeners() + lexer.AddErrorListener(&lexerErrorListener) + + tokenStream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) + + parserErrorListener := createErrorListener(context.line) + antlrParser := parser.NewConfigParser(tokenStream) + antlrParser.RemoveErrorListeners() + antlrParser.AddErrorListener(&parserErrorListener) + + listener := createListener(c, context) + antlr.ParseTreeWalkerDefault.Walk( + &listener, + antlrParser.LineStatement(), + ) + + errors := lexerErrorListener.Errors + errors = append(errors, parserErrorListener.Errors...) + errors = append(errors, listener.Errors...) + + return errors +} diff --git a/server/handlers/ssh_config/ast/parser/Config.interp b/server/handlers/ssh_config/ast/parser/Config.interp new file mode 100644 index 0000000..e02ab96 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/Config.interp @@ -0,0 +1,28 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +rule names: +lineStatement +entry +separator +key +value +leadingComment +string + + +atn: +[4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66] \ No newline at end of file diff --git a/server/handlers/ssh_config/ast/parser/Config.tokens b/server/handlers/ssh_config/ast/parser/Config.tokens new file mode 100644 index 0000000..fa8c415 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/Config.tokens @@ -0,0 +1,6 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +QUOTED_STRING=5 +'#'=1 diff --git a/server/handlers/ssh_config/ast/parser/ConfigLexer.interp b/server/handlers/ssh_config/ast/parser/ConfigLexer.interp new file mode 100644 index 0000000..c093cfb --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/ConfigLexer.interp @@ -0,0 +1,32 @@ +token literal names: +null +'#' +null +null +null +null + +token symbolic names: +null +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +rule names: +HASH +WHITESPACE +STRING +NEWLINE +QUOTED_STRING + +channel names: +DEFAULT_TOKEN_CHANNEL +HIDDEN + +mode names: +DEFAULT_MODE + +atn: +[4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0] \ No newline at end of file diff --git a/server/handlers/ssh_config/ast/parser/ConfigLexer.tokens b/server/handlers/ssh_config/ast/parser/ConfigLexer.tokens new file mode 100644 index 0000000..fa8c415 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/ConfigLexer.tokens @@ -0,0 +1,6 @@ +HASH=1 +WHITESPACE=2 +STRING=3 +NEWLINE=4 +QUOTED_STRING=5 +'#'=1 diff --git a/server/handlers/ssh_config/ast/parser/config_base_listener.go b/server/handlers/ssh_config/ast/parser/config_base_listener.go new file mode 100644 index 0000000..00e7840 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/config_base_listener.go @@ -0,0 +1,64 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// BaseConfigListener is a complete listener for a parse tree produced by ConfigParser. +type BaseConfigListener struct{} + +var _ ConfigListener = &BaseConfigListener{} + +// VisitTerminal is called when a terminal node is visited. +func (s *BaseConfigListener) VisitTerminal(node antlr.TerminalNode) {} + +// VisitErrorNode is called when an error node is visited. +func (s *BaseConfigListener) VisitErrorNode(node antlr.ErrorNode) {} + +// EnterEveryRule is called when any rule is entered. +func (s *BaseConfigListener) EnterEveryRule(ctx antlr.ParserRuleContext) {} + +// ExitEveryRule is called when any rule is exited. +func (s *BaseConfigListener) ExitEveryRule(ctx antlr.ParserRuleContext) {} + +// EnterLineStatement is called when production lineStatement is entered. +func (s *BaseConfigListener) EnterLineStatement(ctx *LineStatementContext) {} + +// ExitLineStatement is called when production lineStatement is exited. +func (s *BaseConfigListener) ExitLineStatement(ctx *LineStatementContext) {} + +// EnterEntry is called when production entry is entered. +func (s *BaseConfigListener) EnterEntry(ctx *EntryContext) {} + +// ExitEntry is called when production entry is exited. +func (s *BaseConfigListener) ExitEntry(ctx *EntryContext) {} + +// EnterSeparator is called when production separator is entered. +func (s *BaseConfigListener) EnterSeparator(ctx *SeparatorContext) {} + +// ExitSeparator is called when production separator is exited. +func (s *BaseConfigListener) ExitSeparator(ctx *SeparatorContext) {} + +// EnterKey is called when production key is entered. +func (s *BaseConfigListener) EnterKey(ctx *KeyContext) {} + +// ExitKey is called when production key is exited. +func (s *BaseConfigListener) ExitKey(ctx *KeyContext) {} + +// EnterValue is called when production value is entered. +func (s *BaseConfigListener) EnterValue(ctx *ValueContext) {} + +// ExitValue is called when production value is exited. +func (s *BaseConfigListener) ExitValue(ctx *ValueContext) {} + +// EnterLeadingComment is called when production leadingComment is entered. +func (s *BaseConfigListener) EnterLeadingComment(ctx *LeadingCommentContext) {} + +// ExitLeadingComment is called when production leadingComment is exited. +func (s *BaseConfigListener) ExitLeadingComment(ctx *LeadingCommentContext) {} + +// EnterString is called when production string is entered. +func (s *BaseConfigListener) EnterString(ctx *StringContext) {} + +// ExitString is called when production string is exited. +func (s *BaseConfigListener) ExitString(ctx *StringContext) {} diff --git a/server/handlers/ssh_config/ast/parser/config_lexer.go b/server/handlers/ssh_config/ast/parser/config_lexer.go new file mode 100644 index 0000000..021f1fc --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/config_lexer.go @@ -0,0 +1,122 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser + +import ( + "fmt" + "github.com/antlr4-go/antlr/v4" + "sync" + "unicode" +) + +// Suppress unused import error +var _ = fmt.Printf +var _ = sync.Once{} +var _ = unicode.IsLetter + +type ConfigLexer struct { + *antlr.BaseLexer + channelNames []string + modeNames []string + // TODO: EOF string +} + +var ConfigLexerLexerStaticData struct { + once sync.Once + serializedATN []int32 + ChannelNames []string + ModeNames []string + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configlexerLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.ChannelNames = []string{ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + } + staticData.ModeNames = []string{ + "DEFAULT_MODE", + } + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 0, 5, 46, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, + 4, 7, 4, 1, 0, 1, 0, 1, 1, 4, 1, 15, 8, 1, 11, 1, 12, 1, 16, 1, 2, 4, 2, + 20, 8, 2, 11, 2, 12, 2, 21, 1, 3, 3, 3, 25, 8, 3, 1, 3, 1, 3, 1, 4, 1, + 4, 3, 4, 31, 8, 4, 1, 4, 1, 4, 1, 4, 5, 4, 36, 8, 4, 10, 4, 12, 4, 39, + 9, 4, 1, 4, 3, 4, 42, 8, 4, 1, 4, 3, 4, 45, 8, 4, 0, 0, 5, 1, 1, 3, 2, + 5, 3, 7, 4, 9, 5, 1, 0, 2, 2, 0, 9, 9, 32, 32, 4, 0, 9, 10, 13, 13, 32, + 32, 34, 35, 52, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5, 1, 0, 0, 0, 0, + 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 11, 1, 0, 0, 0, 3, 14, 1, 0, 0, 0, + 5, 19, 1, 0, 0, 0, 7, 24, 1, 0, 0, 0, 9, 28, 1, 0, 0, 0, 11, 12, 5, 35, + 0, 0, 12, 2, 1, 0, 0, 0, 13, 15, 7, 0, 0, 0, 14, 13, 1, 0, 0, 0, 15, 16, + 1, 0, 0, 0, 16, 14, 1, 0, 0, 0, 16, 17, 1, 0, 0, 0, 17, 4, 1, 0, 0, 0, + 18, 20, 8, 1, 0, 0, 19, 18, 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 19, 1, + 0, 0, 0, 21, 22, 1, 0, 0, 0, 22, 6, 1, 0, 0, 0, 23, 25, 5, 13, 0, 0, 24, + 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 26, 1, 0, 0, 0, 26, 27, 5, 10, + 0, 0, 27, 8, 1, 0, 0, 0, 28, 30, 5, 34, 0, 0, 29, 31, 3, 3, 1, 0, 30, 29, + 1, 0, 0, 0, 30, 31, 1, 0, 0, 0, 31, 37, 1, 0, 0, 0, 32, 33, 3, 5, 2, 0, + 33, 34, 3, 3, 1, 0, 34, 36, 1, 0, 0, 0, 35, 32, 1, 0, 0, 0, 36, 39, 1, + 0, 0, 0, 37, 35, 1, 0, 0, 0, 37, 38, 1, 0, 0, 0, 38, 41, 1, 0, 0, 0, 39, + 37, 1, 0, 0, 0, 40, 42, 3, 5, 2, 0, 41, 40, 1, 0, 0, 0, 41, 42, 1, 0, 0, + 0, 42, 44, 1, 0, 0, 0, 43, 45, 5, 34, 0, 0, 44, 43, 1, 0, 0, 0, 44, 45, + 1, 0, 0, 0, 45, 10, 1, 0, 0, 0, 8, 0, 16, 21, 24, 30, 37, 41, 44, 0, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigLexerInit initializes any static state used to implement ConfigLexer. By default the +// static state used to implement the lexer is lazily initialized during the first call to +// NewConfigLexer(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigLexerInit() { + staticData := &ConfigLexerLexerStaticData + staticData.once.Do(configlexerLexerInit) +} + +// NewConfigLexer produces a new lexer instance for the optional input antlr.CharStream. +func NewConfigLexer(input antlr.CharStream) *ConfigLexer { + ConfigLexerInit() + l := new(ConfigLexer) + l.BaseLexer = antlr.NewBaseLexer(input) + staticData := &ConfigLexerLexerStaticData + l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + l.channelNames = staticData.ChannelNames + l.modeNames = staticData.ModeNames + l.RuleNames = staticData.RuleNames + l.LiteralNames = staticData.LiteralNames + l.SymbolicNames = staticData.SymbolicNames + l.GrammarFileName = "Config.g4" + // TODO: l.EOF = antlr.TokenEOF + + return l +} + +// ConfigLexer tokens. +const ( + ConfigLexerHASH = 1 + ConfigLexerWHITESPACE = 2 + ConfigLexerSTRING = 3 + ConfigLexerNEWLINE = 4 + ConfigLexerQUOTED_STRING = 5 +) diff --git a/server/handlers/ssh_config/ast/parser/config_listener.go b/server/handlers/ssh_config/ast/parser/config_listener.go new file mode 100644 index 0000000..1acf598 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/config_listener.go @@ -0,0 +1,52 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import "github.com/antlr4-go/antlr/v4" + +// ConfigListener is a complete listener for a parse tree produced by ConfigParser. +type ConfigListener interface { + antlr.ParseTreeListener + + // EnterLineStatement is called when entering the lineStatement production. + EnterLineStatement(c *LineStatementContext) + + // EnterEntry is called when entering the entry production. + EnterEntry(c *EntryContext) + + // EnterSeparator is called when entering the separator production. + EnterSeparator(c *SeparatorContext) + + // EnterKey is called when entering the key production. + EnterKey(c *KeyContext) + + // EnterValue is called when entering the value production. + EnterValue(c *ValueContext) + + // EnterLeadingComment is called when entering the leadingComment production. + EnterLeadingComment(c *LeadingCommentContext) + + // EnterString is called when entering the string production. + EnterString(c *StringContext) + + // ExitLineStatement is called when exiting the lineStatement production. + ExitLineStatement(c *LineStatementContext) + + // ExitEntry is called when exiting the entry production. + ExitEntry(c *EntryContext) + + // ExitSeparator is called when exiting the separator production. + ExitSeparator(c *SeparatorContext) + + // ExitKey is called when exiting the key production. + ExitKey(c *KeyContext) + + // ExitValue is called when exiting the value production. + ExitValue(c *ValueContext) + + // ExitLeadingComment is called when exiting the leadingComment production. + ExitLeadingComment(c *LeadingCommentContext) + + // ExitString is called when exiting the string production. + ExitString(c *StringContext) +} diff --git a/server/handlers/ssh_config/ast/parser/config_parser.go b/server/handlers/ssh_config/ast/parser/config_parser.go new file mode 100644 index 0000000..aefb1e3 --- /dev/null +++ b/server/handlers/ssh_config/ast/parser/config_parser.go @@ -0,0 +1,1254 @@ +// Code generated from Config.g4 by ANTLR 4.13.0. DO NOT EDIT. + +package parser // Config + +import ( + "fmt" + "strconv" + "sync" + + "github.com/antlr4-go/antlr/v4" +) + +// Suppress unused import errors +var _ = fmt.Printf +var _ = strconv.Itoa +var _ = sync.Once{} + +type ConfigParser struct { + *antlr.BaseParser +} + +var ConfigParserStaticData struct { + once sync.Once + serializedATN []int32 + LiteralNames []string + SymbolicNames []string + RuleNames []string + PredictionContextCache *antlr.PredictionContextCache + atn *antlr.ATN + decisionToDFA []*antlr.DFA +} + +func configParserInit() { + staticData := &ConfigParserStaticData + staticData.LiteralNames = []string{ + "", "'#'", + } + staticData.SymbolicNames = []string{ + "", "HASH", "WHITESPACE", "STRING", "NEWLINE", "QUOTED_STRING", + } + staticData.RuleNames = []string{ + "lineStatement", "entry", "separator", "key", "value", "leadingComment", + "string", + } + staticData.PredictionContextCache = antlr.NewPredictionContextCache() + staticData.serializedATN = []int32{ + 4, 1, 5, 71, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2, 4, 7, 4, + 2, 5, 7, 5, 2, 6, 7, 6, 1, 0, 1, 0, 1, 0, 3, 0, 18, 8, 0, 3, 0, 20, 8, + 0, 1, 0, 1, 0, 1, 1, 3, 1, 25, 8, 1, 1, 1, 3, 1, 28, 8, 1, 1, 1, 3, 1, + 31, 8, 1, 1, 1, 3, 1, 34, 8, 1, 1, 1, 3, 1, 37, 8, 1, 1, 2, 1, 2, 1, 3, + 1, 3, 1, 4, 1, 4, 1, 4, 5, 4, 46, 8, 4, 10, 4, 12, 4, 49, 9, 4, 1, 4, 3, + 4, 52, 8, 4, 1, 4, 3, 4, 55, 8, 4, 1, 5, 1, 5, 3, 5, 59, 8, 5, 1, 5, 1, + 5, 3, 5, 63, 8, 5, 4, 5, 65, 8, 5, 11, 5, 12, 5, 66, 1, 6, 1, 6, 1, 6, + 0, 0, 7, 0, 2, 4, 6, 8, 10, 12, 0, 1, 2, 0, 3, 3, 5, 5, 77, 0, 19, 1, 0, + 0, 0, 2, 24, 1, 0, 0, 0, 4, 38, 1, 0, 0, 0, 6, 40, 1, 0, 0, 0, 8, 47, 1, + 0, 0, 0, 10, 56, 1, 0, 0, 0, 12, 68, 1, 0, 0, 0, 14, 20, 3, 2, 1, 0, 15, + 20, 3, 10, 5, 0, 16, 18, 5, 2, 0, 0, 17, 16, 1, 0, 0, 0, 17, 18, 1, 0, + 0, 0, 18, 20, 1, 0, 0, 0, 19, 14, 1, 0, 0, 0, 19, 15, 1, 0, 0, 0, 19, 17, + 1, 0, 0, 0, 20, 21, 1, 0, 0, 0, 21, 22, 5, 0, 0, 1, 22, 1, 1, 0, 0, 0, + 23, 25, 5, 2, 0, 0, 24, 23, 1, 0, 0, 0, 24, 25, 1, 0, 0, 0, 25, 27, 1, + 0, 0, 0, 26, 28, 3, 6, 3, 0, 27, 26, 1, 0, 0, 0, 27, 28, 1, 0, 0, 0, 28, + 30, 1, 0, 0, 0, 29, 31, 3, 4, 2, 0, 30, 29, 1, 0, 0, 0, 30, 31, 1, 0, 0, + 0, 31, 33, 1, 0, 0, 0, 32, 34, 3, 8, 4, 0, 33, 32, 1, 0, 0, 0, 33, 34, + 1, 0, 0, 0, 34, 36, 1, 0, 0, 0, 35, 37, 3, 10, 5, 0, 36, 35, 1, 0, 0, 0, + 36, 37, 1, 0, 0, 0, 37, 3, 1, 0, 0, 0, 38, 39, 5, 2, 0, 0, 39, 5, 1, 0, + 0, 0, 40, 41, 3, 12, 6, 0, 41, 7, 1, 0, 0, 0, 42, 43, 3, 12, 6, 0, 43, + 44, 5, 2, 0, 0, 44, 46, 1, 0, 0, 0, 45, 42, 1, 0, 0, 0, 46, 49, 1, 0, 0, + 0, 47, 45, 1, 0, 0, 0, 47, 48, 1, 0, 0, 0, 48, 51, 1, 0, 0, 0, 49, 47, + 1, 0, 0, 0, 50, 52, 3, 12, 6, 0, 51, 50, 1, 0, 0, 0, 51, 52, 1, 0, 0, 0, + 52, 54, 1, 0, 0, 0, 53, 55, 5, 2, 0, 0, 54, 53, 1, 0, 0, 0, 54, 55, 1, + 0, 0, 0, 55, 9, 1, 0, 0, 0, 56, 58, 5, 1, 0, 0, 57, 59, 5, 2, 0, 0, 58, + 57, 1, 0, 0, 0, 58, 59, 1, 0, 0, 0, 59, 64, 1, 0, 0, 0, 60, 62, 3, 12, + 6, 0, 61, 63, 5, 2, 0, 0, 62, 61, 1, 0, 0, 0, 62, 63, 1, 0, 0, 0, 63, 65, + 1, 0, 0, 0, 64, 60, 1, 0, 0, 0, 65, 66, 1, 0, 0, 0, 66, 64, 1, 0, 0, 0, + 66, 67, 1, 0, 0, 0, 67, 11, 1, 0, 0, 0, 68, 69, 7, 0, 0, 0, 69, 13, 1, + 0, 0, 0, 13, 17, 19, 24, 27, 30, 33, 36, 47, 51, 54, 58, 62, 66, + } + deserializer := antlr.NewATNDeserializer(nil) + staticData.atn = deserializer.Deserialize(staticData.serializedATN) + atn := staticData.atn + staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState)) + decisionToDFA := staticData.decisionToDFA + for index, state := range atn.DecisionToState { + decisionToDFA[index] = antlr.NewDFA(state, index) + } +} + +// ConfigParserInit initializes any static state used to implement ConfigParser. By default the +// static state used to implement the parser is lazily initialized during the first call to +// NewConfigParser(). You can call this function if you wish to initialize the static state ahead +// of time. +func ConfigParserInit() { + staticData := &ConfigParserStaticData + staticData.once.Do(configParserInit) +} + +// NewConfigParser produces a new parser instance for the optional input antlr.TokenStream. +func NewConfigParser(input antlr.TokenStream) *ConfigParser { + ConfigParserInit() + this := new(ConfigParser) + this.BaseParser = antlr.NewBaseParser(input) + staticData := &ConfigParserStaticData + this.Interpreter = antlr.NewParserATNSimulator(this, staticData.atn, staticData.decisionToDFA, staticData.PredictionContextCache) + this.RuleNames = staticData.RuleNames + this.LiteralNames = staticData.LiteralNames + this.SymbolicNames = staticData.SymbolicNames + this.GrammarFileName = "Config.g4" + + return this +} + +// ConfigParser tokens. +const ( + ConfigParserEOF = antlr.TokenEOF + ConfigParserHASH = 1 + ConfigParserWHITESPACE = 2 + ConfigParserSTRING = 3 + ConfigParserNEWLINE = 4 + ConfigParserQUOTED_STRING = 5 +) + +// ConfigParser rules. +const ( + ConfigParserRULE_lineStatement = 0 + ConfigParserRULE_entry = 1 + ConfigParserRULE_separator = 2 + ConfigParserRULE_key = 3 + ConfigParserRULE_value = 4 + ConfigParserRULE_leadingComment = 5 + ConfigParserRULE_string = 6 +) + +// ILineStatementContext is an interface to support dynamic dispatch. +type ILineStatementContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + EOF() antlr.TerminalNode + Entry() IEntryContext + LeadingComment() ILeadingCommentContext + WHITESPACE() antlr.TerminalNode + + // IsLineStatementContext differentiates from other interfaces. + IsLineStatementContext() +} + +type LineStatementContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLineStatementContext() *LineStatementContext { + var p = new(LineStatementContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement + return p +} + +func InitEmptyLineStatementContext(p *LineStatementContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_lineStatement +} + +func (*LineStatementContext) IsLineStatementContext() {} + +func NewLineStatementContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LineStatementContext { + var p = new(LineStatementContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_lineStatement + + return p +} + +func (s *LineStatementContext) GetParser() antlr.Parser { return s.parser } + +func (s *LineStatementContext) EOF() antlr.TerminalNode { + return s.GetToken(ConfigParserEOF, 0) +} + +func (s *LineStatementContext) Entry() IEntryContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IEntryContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IEntryContext) +} + +func (s *LineStatementContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *LineStatementContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *LineStatementContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LineStatementContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LineStatementContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLineStatement(s) + } +} + +func (s *LineStatementContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLineStatement(s) + } +} + +func (p *ConfigParser) LineStatement() (localctx ILineStatementContext) { + localctx = NewLineStatementContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 0, ConfigParserRULE_lineStatement) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(19) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + + switch p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 1, p.GetParserRuleContext()) { + case 1: + { + p.SetState(14) + p.Entry() + } + + case 2: + { + p.SetState(15) + p.LeadingComment() + } + + case 3: + p.SetState(17) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(16) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + case antlr.ATNInvalidAltNumber: + goto errorExit + } + { + p.SetState(21) + p.Match(ConfigParserEOF) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IEntryContext is an interface to support dynamic dispatch. +type IEntryContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + Key() IKeyContext + Separator() ISeparatorContext + Value() IValueContext + LeadingComment() ILeadingCommentContext + + // IsEntryContext differentiates from other interfaces. + IsEntryContext() +} + +type EntryContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyEntryContext() *EntryContext { + var p = new(EntryContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry + return p +} + +func InitEmptyEntryContext(p *EntryContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_entry +} + +func (*EntryContext) IsEntryContext() {} + +func NewEntryContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *EntryContext { + var p = new(EntryContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_entry + + return p +} + +func (s *EntryContext) GetParser() antlr.Parser { return s.parser } + +func (s *EntryContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *EntryContext) Key() IKeyContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IKeyContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IKeyContext) +} + +func (s *EntryContext) Separator() ISeparatorContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ISeparatorContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ISeparatorContext) +} + +func (s *EntryContext) Value() IValueContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IValueContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IValueContext) +} + +func (s *EntryContext) LeadingComment() ILeadingCommentContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(ILeadingCommentContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(ILeadingCommentContext) +} + +func (s *EntryContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *EntryContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *EntryContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterEntry(s) + } +} + +func (s *EntryContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitEntry(s) + } +} + +func (p *ConfigParser) Entry() (localctx IEntryContext) { + localctx = NewEntryContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 2, ConfigParserRULE_entry) + var _la int + + p.EnterOuterAlt(localctx, 1) + p.SetState(24) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 2, p.GetParserRuleContext()) == 1 { + { + p.SetState(23) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(27) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 3, p.GetParserRuleContext()) == 1 { + { + p.SetState(26) + p.Key() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(30) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 4, p.GetParserRuleContext()) == 1 { + { + p.SetState(29) + p.Separator() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(33) + p.GetErrorHandler().Sync(p) + + if p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 5, p.GetParserRuleContext()) == 1 { + { + p.SetState(32) + p.Value() + } + + } else if p.HasError() { // JIM + goto errorExit + } + p.SetState(36) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserHASH { + { + p.SetState(35) + p.LeadingComment() + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ISeparatorContext is an interface to support dynamic dispatch. +type ISeparatorContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + WHITESPACE() antlr.TerminalNode + + // IsSeparatorContext differentiates from other interfaces. + IsSeparatorContext() +} + +type SeparatorContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptySeparatorContext() *SeparatorContext { + var p = new(SeparatorContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator + return p +} + +func InitEmptySeparatorContext(p *SeparatorContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_separator +} + +func (*SeparatorContext) IsSeparatorContext() {} + +func NewSeparatorContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *SeparatorContext { + var p = new(SeparatorContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_separator + + return p +} + +func (s *SeparatorContext) GetParser() antlr.Parser { return s.parser } + +func (s *SeparatorContext) WHITESPACE() antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, 0) +} + +func (s *SeparatorContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *SeparatorContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *SeparatorContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterSeparator(s) + } +} + +func (s *SeparatorContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitSeparator(s) + } +} + +func (p *ConfigParser) Separator() (localctx ISeparatorContext) { + localctx = NewSeparatorContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 4, ConfigParserRULE_separator) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(38) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IKeyContext is an interface to support dynamic dispatch. +type IKeyContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + String_() IStringContext + + // IsKeyContext differentiates from other interfaces. + IsKeyContext() +} + +type KeyContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyKeyContext() *KeyContext { + var p = new(KeyContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key + return p +} + +func InitEmptyKeyContext(p *KeyContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_key +} + +func (*KeyContext) IsKeyContext() {} + +func NewKeyContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *KeyContext { + var p = new(KeyContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_key + + return p +} + +func (s *KeyContext) GetParser() antlr.Parser { return s.parser } + +func (s *KeyContext) String_() IStringContext { + var t antlr.RuleContext + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + t = ctx.(antlr.RuleContext) + break + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *KeyContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *KeyContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *KeyContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterKey(s) + } +} + +func (s *KeyContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitKey(s) + } +} + +func (p *ConfigParser) Key() (localctx IKeyContext) { + localctx = NewKeyContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 6, ConfigParserRULE_key) + p.EnterOuterAlt(localctx, 1) + { + p.SetState(40) + p.String_() + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IValueContext is an interface to support dynamic dispatch. +type IValueContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + AllString_() []IStringContext + String_(i int) IStringContext + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + + // IsValueContext differentiates from other interfaces. + IsValueContext() +} + +type ValueContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyValueContext() *ValueContext { + var p = new(ValueContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value + return p +} + +func InitEmptyValueContext(p *ValueContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_value +} + +func (*ValueContext) IsValueContext() {} + +func NewValueContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *ValueContext { + var p = new(ValueContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_value + + return p +} + +func (s *ValueContext) GetParser() antlr.Parser { return s.parser } + +func (s *ValueContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst +} + +func (s *ValueContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *ValueContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *ValueContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *ValueContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *ValueContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *ValueContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterValue(s) + } +} + +func (s *ValueContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitValue(s) + } +} + +func (p *ConfigParser) Value() (localctx IValueContext) { + localctx = NewValueContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 8, ConfigParserRULE_value) + var _la int + + var _alt int + + p.EnterOuterAlt(localctx, 1) + p.SetState(47) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + for _alt != 2 && _alt != antlr.ATNInvalidAltNumber { + if _alt == 1 { + { + p.SetState(42) + p.String_() + } + { + p.SetState(43) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(49) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _alt = p.GetInterpreter().AdaptivePredict(p.BaseParser, p.GetTokenStream(), 7, p.GetParserRuleContext()) + if p.HasError() { + goto errorExit + } + } + p.SetState(51) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { + { + p.SetState(50) + p.String_() + } + + } + p.SetState(54) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(53) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// ILeadingCommentContext is an interface to support dynamic dispatch. +type ILeadingCommentContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + HASH() antlr.TerminalNode + AllWHITESPACE() []antlr.TerminalNode + WHITESPACE(i int) antlr.TerminalNode + AllString_() []IStringContext + String_(i int) IStringContext + + // IsLeadingCommentContext differentiates from other interfaces. + IsLeadingCommentContext() +} + +type LeadingCommentContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyLeadingCommentContext() *LeadingCommentContext { + var p = new(LeadingCommentContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment + return p +} + +func InitEmptyLeadingCommentContext(p *LeadingCommentContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_leadingComment +} + +func (*LeadingCommentContext) IsLeadingCommentContext() {} + +func NewLeadingCommentContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *LeadingCommentContext { + var p = new(LeadingCommentContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_leadingComment + + return p +} + +func (s *LeadingCommentContext) GetParser() antlr.Parser { return s.parser } + +func (s *LeadingCommentContext) HASH() antlr.TerminalNode { + return s.GetToken(ConfigParserHASH, 0) +} + +func (s *LeadingCommentContext) AllWHITESPACE() []antlr.TerminalNode { + return s.GetTokens(ConfigParserWHITESPACE) +} + +func (s *LeadingCommentContext) WHITESPACE(i int) antlr.TerminalNode { + return s.GetToken(ConfigParserWHITESPACE, i) +} + +func (s *LeadingCommentContext) AllString_() []IStringContext { + children := s.GetChildren() + len := 0 + for _, ctx := range children { + if _, ok := ctx.(IStringContext); ok { + len++ + } + } + + tst := make([]IStringContext, len) + i := 0 + for _, ctx := range children { + if t, ok := ctx.(IStringContext); ok { + tst[i] = t.(IStringContext) + i++ + } + } + + return tst +} + +func (s *LeadingCommentContext) String_(i int) IStringContext { + var t antlr.RuleContext + j := 0 + for _, ctx := range s.GetChildren() { + if _, ok := ctx.(IStringContext); ok { + if j == i { + t = ctx.(antlr.RuleContext) + break + } + j++ + } + } + + if t == nil { + return nil + } + + return t.(IStringContext) +} + +func (s *LeadingCommentContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *LeadingCommentContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *LeadingCommentContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterLeadingComment(s) + } +} + +func (s *LeadingCommentContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitLeadingComment(s) + } +} + +func (p *ConfigParser) LeadingComment() (localctx ILeadingCommentContext) { + localctx = NewLeadingCommentContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 10, ConfigParserRULE_leadingComment) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(56) + p.Match(ConfigParserHASH) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + p.SetState(58) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(57) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + p.SetState(64) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + for ok := true; ok; ok = _la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING { + { + p.SetState(60) + p.String_() + } + p.SetState(62) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + + if _la == ConfigParserWHITESPACE { + { + p.SetState(61) + p.Match(ConfigParserWHITESPACE) + if p.HasError() { + // Recognition error - abort rule + goto errorExit + } + } + + } + + p.SetState(66) + p.GetErrorHandler().Sync(p) + if p.HasError() { + goto errorExit + } + _la = p.GetTokenStream().LA(1) + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} + +// IStringContext is an interface to support dynamic dispatch. +type IStringContext interface { + antlr.ParserRuleContext + + // GetParser returns the parser. + GetParser() antlr.Parser + + // Getter signatures + QUOTED_STRING() antlr.TerminalNode + STRING() antlr.TerminalNode + + // IsStringContext differentiates from other interfaces. + IsStringContext() +} + +type StringContext struct { + antlr.BaseParserRuleContext + parser antlr.Parser +} + +func NewEmptyStringContext() *StringContext { + var p = new(StringContext) + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string + return p +} + +func InitEmptyStringContext(p *StringContext) { + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, nil, -1) + p.RuleIndex = ConfigParserRULE_string +} + +func (*StringContext) IsStringContext() {} + +func NewStringContext(parser antlr.Parser, parent antlr.ParserRuleContext, invokingState int) *StringContext { + var p = new(StringContext) + + antlr.InitBaseParserRuleContext(&p.BaseParserRuleContext, parent, invokingState) + + p.parser = parser + p.RuleIndex = ConfigParserRULE_string + + return p +} + +func (s *StringContext) GetParser() antlr.Parser { return s.parser } + +func (s *StringContext) QUOTED_STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserQUOTED_STRING, 0) +} + +func (s *StringContext) STRING() antlr.TerminalNode { + return s.GetToken(ConfigParserSTRING, 0) +} + +func (s *StringContext) GetRuleContext() antlr.RuleContext { + return s +} + +func (s *StringContext) ToStringTree(ruleNames []string, recog antlr.Recognizer) string { + return antlr.TreesStringTree(s, ruleNames, recog) +} + +func (s *StringContext) EnterRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.EnterString(s) + } +} + +func (s *StringContext) ExitRule(listener antlr.ParseTreeListener) { + if listenerT, ok := listener.(ConfigListener); ok { + listenerT.ExitString(s) + } +} + +func (p *ConfigParser) String_() (localctx IStringContext) { + localctx = NewStringContext(p, p.GetParserRuleContext(), p.GetState()) + p.EnterRule(localctx, 12, ConfigParserRULE_string) + var _la int + + p.EnterOuterAlt(localctx, 1) + { + p.SetState(68) + _la = p.GetTokenStream().LA(1) + + if !(_la == ConfigParserSTRING || _la == ConfigParserQUOTED_STRING) { + p.GetErrorHandler().RecoverInline(p) + } else { + p.GetErrorHandler().ReportMatch(p) + p.Consume() + } + } + +errorExit: + if p.HasError() { + v := p.GetError() + localctx.SetException(v) + p.GetErrorHandler().ReportError(p, v) + p.GetErrorHandler().Recover(p, v) + p.SetError(nil) + } + p.ExitRule() + return localctx + goto errorExit // Trick to prevent compiler error if the label is not used +} diff --git a/server/handlers/ssh_config/ast/parser_test.go b/server/handlers/ssh_config/ast/parser_test.go new file mode 100644 index 0000000..054e01d --- /dev/null +++ b/server/handlers/ssh_config/ast/parser_test.go @@ -0,0 +1,477 @@ +package ast + +import ( + matchparser "config-lsp/handlers/ssh_config/match-parser" + "config-lsp/utils" + "testing" +) + +func TestSSHConfigParserExample( + t *testing.T, +) { + input := utils.Dedent(` +HostName 1.2.3.4 +User root +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 options and no comment lines, but got: %v, %v", p.Options, p.CommentLines) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + + if !(firstEntry.Value.Value == "HostName 1.2.3.4" && + firstEntry.LocationRange.Start.Line == 0 && + firstEntry.LocationRange.End.Line == 0 && + firstEntry.LocationRange.Start.Character == 0 && + firstEntry.LocationRange.End.Character == 16 && + firstEntry.Key.Value.Value == "HostName" && + firstEntry.Key.LocationRange.Start.Character == 0 && + firstEntry.Key.LocationRange.End.Character == 8 && + firstEntry.OptionValue.Value.Value == "1.2.3.4" && + firstEntry.OptionValue.LocationRange.Start.Character == 9 && + firstEntry.OptionValue.LocationRange.End.Character == 16) { + t.Errorf("Expected first entry to be HostName 1.2.3.4, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(1)) + secondEntry := rawSecondEntry.(*SSHOption) + + if !(secondEntry.Value.Value == "User root" && + secondEntry.LocationRange.Start.Line == 1 && + secondEntry.LocationRange.End.Line == 1 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Character == 9 && + secondEntry.Key.Value.Value == "User" && + secondEntry.Key.LocationRange.Start.Character == 0 && + secondEntry.Key.LocationRange.End.Character == 4 && + secondEntry.OptionValue.Value.Value == "root" && + secondEntry.OptionValue.LocationRange.Start.Character == 5 && + secondEntry.OptionValue.LocationRange.End.Character == 9) { + t.Errorf("Expected second entry to be User root, but got: %v", secondEntry) + } +} + +func TestMatchSimpleBlock( + t *testing.T, +) { + input := utils.Dedent(` +Hostname 1.2.3.4 + +Match originalhost "192.168.0.1" + User root +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + + if !(firstEntry.Value.Value == "Hostname 1.2.3.4" && + firstEntry.LocationRange.Start.Line == 0 && + firstEntry.LocationRange.End.Line == 0 && + firstEntry.LocationRange.Start.Character == 0 && + firstEntry.LocationRange.End.Character == 16 && + firstEntry.Key.Value.Value == "Hostname" && + firstEntry.Key.LocationRange.Start.Character == 0 && + firstEntry.Key.LocationRange.End.Character == 8 && + firstEntry.OptionValue.Value.Value == "1.2.3.4" && + firstEntry.OptionValue.LocationRange.Start.Character == 9 && + firstEntry.OptionValue.LocationRange.End.Character == 16) { + t.Errorf("Expected first entry to be Hostname 1.2.3.4, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHMatchBlock) + + if !(secondEntry.Options.Size() == 1 && + secondEntry.LocationRange.Start.Line == 2 && + secondEntry.LocationRange.End.Line == 3 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Character == 10 && + secondEntry.MatchOption.OptionValue.Value.Raw == "originalhost \"192.168.0.1\"" && + secondEntry.MatchOption.OptionValue.LocationRange.Start.Character == 6 && + secondEntry.MatchOption.OptionValue.LocationRange.End.Character == 32) { + t.Errorf("Expected second entry to be Match originalhost \"192.168.0.1\", but got: %v; options amount: %d", secondEntry, secondEntry.Options.Size()) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Value.Raw == "\tUser root" && + thirdEntry.LocationRange.Start.Line == 3 && + thirdEntry.LocationRange.End.Line == 3 && + thirdEntry.LocationRange.Start.Character == 0 && + thirdEntry.LocationRange.End.Character == 10 && + thirdEntry.Key.Value.Value == "User" && + thirdEntry.Key.LocationRange.Start.Character == 1 && + thirdEntry.Key.LocationRange.End.Character == 5 && + thirdEntry.OptionValue.Value.Value == "root" && + thirdEntry.OptionValue.LocationRange.Start.Character == 6 && + thirdEntry.OptionValue.LocationRange.End.Character == 10) { + t.Errorf("Expected third entry to be User root, but got: %v", thirdEntry) + } +} + +func TestSimpleHostBlock( + t *testing.T, +) { + input := utils.Dedent(` +Ciphers 3des-cbc + +Host example.com + Port 22 +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Value.Value == "Ciphers 3des-cbc") { + t.Errorf("Expected first entry to be Ciphers 3des-cbc, but got: %v", firstEntry) + } + + rawSecondEntry, _ := p.Options.Get(uint32(2)) + secondEntry := rawSecondEntry.(*SSHHostBlock) + if !(secondEntry.Options.Size() == 1 && + secondEntry.LocationRange.Start.Line == 2 && + secondEntry.LocationRange.Start.Character == 0 && + secondEntry.LocationRange.End.Line == 3 && + secondEntry.LocationRange.End.Character == 8) { + t.Errorf("Expected second entry to be Host example.com, but got: %v", secondEntry) + } + + rawThirdEntry, _ := secondEntry.Options.Get(uint32(3)) + thirdEntry := rawThirdEntry.(*SSHOption) + if !(thirdEntry.Value.Raw == "\tPort 22" && + thirdEntry.Key.Value.Raw == "Port" && + thirdEntry.OptionValue.Value.Raw == "22" && + thirdEntry.LocationRange.Start.Line == 3 && + thirdEntry.LocationRange.Start.Character == 0 && + thirdEntry.LocationRange.End.Line == 3 && + thirdEntry.LocationRange.End.Character == 8) { + t.Errorf("Expected third entry to be Port 22, but got: %v", thirdEntry) + } + + rawFourthEntry, _ := p.Options.Get(uint32(3)) + + if !(rawFourthEntry == nil) { + t.Errorf("Expected fourth entry to be nil, but got: %v", rawFourthEntry) + } +} + +func TestComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +Host laptop + HostName laptop.lan + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 2 && + len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected 2 option and no comment lines, but got: %v entries, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstBlock := rawFirstEntry.(*SSHHostBlock) + if !(firstBlock.Options.Size() == 1 && + firstBlock.LocationRange.Start.Line == 0 && + firstBlock.LocationRange.Start.Character == 0 && + firstBlock.LocationRange.End.Line == 1 && + firstBlock.LocationRange.End.Character == 23) { + t.Errorf("Expected first entry to be Host laptop, but got: %v", firstBlock) + } + + rawSecondEntry, _ := firstBlock.Options.Get(uint32(1)) + secondOption := rawSecondEntry.(*SSHOption) + if !(secondOption.Value.Raw == " HostName laptop.lan" && + secondOption.Key.Value.Raw == "HostName" && + secondOption.OptionValue.Value.Raw == "laptop.lan" && + secondOption.LocationRange.Start.Line == 1 && + secondOption.LocationRange.Start.Character == 0 && + secondOption.Key.LocationRange.Start.Character == 4 && + secondOption.LocationRange.End.Line == 1 && + secondOption.LocationRange.End.Character == 23) { + t.Errorf("Expected second entry to be HostName laptop.lan, but got: %v", secondOption) + } + + rawThirdEntry, _ := p.Options.Get(uint32(3)) + secondBlock := rawThirdEntry.(*SSHMatchBlock) + if !(secondBlock.Options.Size() == 1 && + secondBlock.LocationRange.Start.Line == 3 && + secondBlock.LocationRange.Start.Character == 0 && + secondBlock.LocationRange.End.Line == 4 && + secondBlock.LocationRange.End.Character == 23) { + t.Errorf("Expected second entry to be Match originalhost laptop exec \"[[ $(/usr/bin/dig +short laptop.lan) == '' ]]\", but got: %v", secondBlock) + } + + if !(secondBlock.MatchOption.LocationRange.End.Character == 78) { + t.Errorf("Expected second entry to be Match originalhost laptop exec \"[[ $(/usr/bin/dig +short laptop.lan) == '' ]]\", but got: %v", secondBlock) + } + + rawFourthEntry, _ := secondBlock.Options.Get(uint32(4)) + thirdOption := rawFourthEntry.(*SSHOption) + if !(thirdOption.Value.Raw == " HostName laptop.sdn" && + thirdOption.Key.Value.Raw == "HostName" && + thirdOption.OptionValue.Value.Raw == "laptop.sdn" && + thirdOption.LocationRange.Start.Line == 4 && + thirdOption.LocationRange.Start.Character == 0 && + thirdOption.Key.LocationRange.Start.Character == 4 && + thirdOption.LocationRange.End.Line == 4 && + thirdOption.LocationRange.End.Character == 23) { + t.Errorf("Expected third entry to be HostName laptop.sdn, but got: %v", thirdOption) + } +} + +func TestIncompleteExample( + t *testing.T, +) { + input := utils.Dedent(` +User +`) + p := NewSSHConfig() + + errors := p.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1) { + t.Errorf("Expected 1 option, but got: %v", p.Options.Size()) + } + + if !(len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected no comment lines, but got: %v", len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHOption) + if !(firstEntry.Value.Raw == "User " && firstEntry.Key.Value.Raw == "User") { + t.Errorf("Expected first entry to be User, but got: %v", firstEntry) + } + + if !(firstEntry.OptionValue != nil && firstEntry.OptionValue.Value.Raw == "") { + t.Errorf("Expected first entry to have an empty value, but got: %v", firstEntry) + } +} + +func TestIncompleteMatch( + t *testing.T, +) { + input := utils.Dedent(` +Match +`) + p := NewSSHConfig() + + errors := p.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1) { + t.Errorf("Expected 1 option, but got: %v", p.Options.Size()) + } + + if !(len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected no comment lines, but got: %v", len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHMatchBlock) + if !(firstEntry.MatchOption.Key.Value.Raw == "Match") { + t.Errorf("Expected first entry to be User, but got: %v", firstEntry) + } + + if !(firstEntry.MatchOption.OptionValue != nil && firstEntry.MatchOption.OptionValue.Value.Raw == "") { + t.Errorf("Expected first entry to have an empty value, but got: %v", firstEntry) + } +} + +func TestMatchWithIncompleteEntry( + t *testing.T, +) { + input := utils.Dedent(` +Match user +`) + p := NewSSHConfig() + + errors := p.Parse(input) + + if len(errors) > 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 1) { + t.Errorf("Expected 1 option, but got: %v", p.Options.Size()) + } + + if !(len(utils.KeysOfMap(p.CommentLines)) == 0) { + t.Errorf("Expected no comment lines, but got: %v", len(p.CommentLines)) + } + + rawFirstEntry, _ := p.Options.Get(uint32(0)) + firstEntry := rawFirstEntry.(*SSHMatchBlock) + if !(firstEntry.MatchOption.Key.Value.Raw == "Match") { + t.Errorf("Expected first entry to be User, but got: %v", firstEntry) + } + + if !(firstEntry.MatchOption.OptionValue != nil && firstEntry.MatchOption.OptionValue.Value.Raw == "user ") { + t.Errorf("Expected first entry to have an empty value, but got: %v", firstEntry) + } + + if !(firstEntry.MatchValue.Entries[0].Criteria.Type == matchparser.MatchCriteriaTypeUser) { + t.Errorf("Expected first entry to have a user criteria, but got: %v", firstEntry) + } +} + +func TestInvalidMatchExample( + t *testing.T, +) { + input := utils.Dedent(` +Match us +`) + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) == 0 { + t.Fatalf("Expected errors, got none") + } +} + +func TestComplexBigExample( + t *testing.T, +) { + // From https://gist.github.com/zeloc/b9455b793b07898025db + input := utils.Dedent(` +### default for all ## +Host * + ForwardAgent no + ForwardX11 no + ForwardX11Trusted yes + User nixcraft + Port 22 + Protocol 2 + ServerAliveInterval 60 + ServerAliveCountMax 30 + +## override as per host ## +Host server1 + HostName server1.cyberciti.biz + User nixcraft + Port 4242 + IdentityFile /nfs/shared/users/nixcraft/keys/server1/id_rsa + +## Home nas server ## +Host nas01 + HostName 192.168.1.100 + User root + IdentityFile ~/.ssh/nas01.key + +## Login AWS Cloud ## +Host aws.apache + HostName 1.2.3.4 + User wwwdata + IdentityFile ~/.ssh/aws.apache.key + +## Login to internal lan server at 192.168.0.251 via our public uk office ssh based gateway using ## +## $ ssh uk.gw.lan ## +Host uk.gw.lan uk.lan + HostName 192.168.0.251 + User nixcraft + ProxyCommand ssh nixcraft@gateway.uk.cyberciti.biz nc %h %p 2> /dev/null + +## Our Us Proxy Server ## +## Forward all local port 3128 traffic to port 3128 on the remote vps1.cyberciti.biz server ## +## $ ssh -f -N proxyus ## +Host proxyus + HostName vps1.cyberciti.biz + User breakfree + IdentityFile ~/.ssh/vps1.cyberciti.biz.key + LocalForward 3128 127.0.0.1:3128 +`) + p := NewSSHConfig() + + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + if !(p.Options.Size() == 6 && len(utils.KeysOfMap(p.CommentLines)) == 9) { + t.Errorf("Expected 6 options and no comment lines, but got: %v options, %v comment lines", p.Options.Size(), len(p.CommentLines)) + } + + // Validate each Host block and its options + rawFirstEntry, _ := p.Options.Get(uint32(1)) + firstBlock := rawFirstEntry.(*SSHHostBlock) + if !(firstBlock.Options.Size() == 8) { + t.Errorf("Expected 8 options for Host *, but got: %v", firstBlock.Options.Size()) + } + + rawSecondEntry, _ := p.Options.Get(uint32(12)) + secondBlock := rawSecondEntry.(*SSHHostBlock) + if !(secondBlock.Options.Size() == 4) { + t.Errorf("Expected 4 options for Host server1, but got: %v", secondBlock.Options.Size()) + } + + rawThirdEntry, _ := p.Options.Get(uint32(19)) + thirdBlock := rawThirdEntry.(*SSHHostBlock) + if !(thirdBlock.Options.Size() == 3) { + t.Errorf("Expected 2 options for Host nas01, but got: %v", thirdBlock.Options.Size()) + } + + rawFourthEntry, _ := p.Options.Get(uint32(25)) + fourthBlock := rawFourthEntry.(*SSHHostBlock) + if !(fourthBlock.Options.Size() == 3) { + t.Errorf("Expected 2 options for Host aws.apache, but got: %v", fourthBlock.Options.Size()) + } + + rawFifthEntry, _ := p.Options.Get(uint32(32)) + fifthBlock := rawFifthEntry.(*SSHHostBlock) + if !(fifthBlock.Options.Size() == 3) { + t.Errorf("Expected 3 options for Host uk.gw.lan uk.lan, but got: %v", fifthBlock.Options.Size()) + } + + rawSixthEntry, _ := p.Options.Get(uint32(40)) + sixthBlock := rawSixthEntry.(*SSHHostBlock) + if !(sixthBlock.Options.Size() == 4) { + t.Errorf("Expected 4 options for Host proxyus, but got: %v", sixthBlock.Options.Size()) + } +} diff --git a/server/handlers/ssh_config/ast/ssh_cofig_fields_test.go b/server/handlers/ssh_config/ast/ssh_cofig_fields_test.go new file mode 100644 index 0000000..9946529 --- /dev/null +++ b/server/handlers/ssh_config/ast/ssh_cofig_fields_test.go @@ -0,0 +1,61 @@ +package ast + +import ( + "config-lsp/utils" + "testing" +) + +func TestComplexExampleRetrievesCorrectly( + t *testing.T, +) { + input := utils.Dedent(` +Port 22 + +Host laptop + HostName laptop.lan + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn + + + `) + + p := NewSSHConfig() + errors := p.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + firstOption, firstBlock := p.FindOption(0) + if !(firstOption.Value.Raw == "Port 22") { + t.Errorf("Expected Port 22, got %v", firstOption.Value.Raw) + } + + if !(firstBlock == nil) { + t.Errorf("Expected no block, got %v", firstBlock) + } + + secondOption, secondBlock := p.FindOption(3) + if !(secondOption.Value.Raw == " HostName laptop.lan") { + t.Errorf("Expected HostName laptop.lan, got %v", secondOption.Value.Raw) + } + + if !(secondBlock.GetLocation().Start.Line == 2) { + t.Errorf("Expected line 2, got %v", secondBlock.GetLocation().Start.Line) + } + + thirdOption, thirdBlock := p.FindOption(6) + if !(thirdOption.Value.Raw == " HostName laptop.sdn") { + t.Errorf("Expected HostName laptop.sdn, got %v", thirdOption.Value.Raw) + } + + if !(thirdBlock.GetLocation().Start.Line == 5) { + t.Errorf("Expected line 3, got %v", thirdBlock.GetLocation().Start.Line) + } + + fourthOption, fourthBlock := p.FindOption(8) + if !(fourthOption == nil && fourthBlock == thirdBlock) { + t.Errorf("Expected no option and same block, got %v and %v", fourthOption, fourthBlock) + } +} diff --git a/server/handlers/ssh_config/ast/ssh_config.go b/server/handlers/ssh_config/ast/ssh_config.go new file mode 100644 index 0000000..168d949 --- /dev/null +++ b/server/handlers/ssh_config/ast/ssh_config.go @@ -0,0 +1,62 @@ +package ast + +import ( + "config-lsp/common" + commonparser "config-lsp/common/parser" + "config-lsp/handlers/ssh_config/fields" + hostparser "config-lsp/handlers/ssh_config/host-parser" + "config-lsp/handlers/ssh_config/match-parser" + + "github.com/emirpasic/gods/maps/treemap" +) + +type SSHKey struct { + common.LocationRange + Value commonparser.ParsedString + Key fields.NormalizedOptionName +} + +type SSHSeparator struct { + common.LocationRange + Value commonparser.ParsedString +} + +type SSHValue struct { + common.LocationRange + Value commonparser.ParsedString +} + +type SSHOption struct { + common.LocationRange + Value commonparser.ParsedString + + Key *SSHKey + Separator *SSHSeparator + OptionValue *SSHValue +} + +type SSHMatchBlock struct { + common.LocationRange + MatchOption *SSHOption + MatchValue *matchparser.Match + + // [uint32]*SSHOption -> line number -> *SSHOption + Options *treemap.Map +} + +type SSHHostBlock struct { + common.LocationRange + HostOption *SSHOption + HostValue *hostparser.Host + + // [uint32]*SSHOption -> line number -> *SSHOption + Options *treemap.Map +} + +type SSHConfig struct { + // [uint32]SSHOption -> line number -> *SSHEntry + Options *treemap.Map + + // [uint32]{} -> line number -> {} + CommentLines map[uint32]struct{} +} diff --git a/server/handlers/ssh_config/ast/ssh_config_fields.go b/server/handlers/ssh_config/ast/ssh_config_fields.go new file mode 100644 index 0000000..0115ed6 --- /dev/null +++ b/server/handlers/ssh_config/ast/ssh_config_fields.go @@ -0,0 +1,243 @@ +package ast + +import ( + "config-lsp/common" + "config-lsp/utils" + + "github.com/emirpasic/gods/maps/treemap" +) + +type SSHBlockType uint8 + +const ( + SSHBlockTypeMatch SSHBlockType = iota + SSHBlockTypeHost +) + +type SSHBlock interface { + GetBlockType() SSHBlockType + AddOption(option *SSHOption) + SetEnd(common.Location) + GetOptions() *treemap.Map + GetEntryOption() *SSHOption + GetLocation() common.LocationRange +} + +func (b *SSHMatchBlock) GetBlockType() SSHBlockType { + return SSHBlockTypeMatch +} + +func (b *SSHMatchBlock) AddOption(option *SSHOption) { + b.Options.Put(option.LocationRange.Start.Line, option) +} + +func (b *SSHMatchBlock) SetEnd(end common.Location) { + b.LocationRange.End = end +} + +func (b *SSHMatchBlock) GetOptions() *treemap.Map { + return b.Options +} + +func (b *SSHMatchBlock) GetEntryOption() *SSHOption { + return b.MatchOption +} + +func (b *SSHMatchBlock) GetLocation() common.LocationRange { + return b.LocationRange +} + +func (b *SSHHostBlock) GetBlockType() SSHBlockType { + return SSHBlockTypeHost +} + +func (b *SSHHostBlock) AddOption(option *SSHOption) { + b.Options.Put(option.LocationRange.Start.Line, option) +} + +func (b *SSHHostBlock) SetEnd(end common.Location) { + b.LocationRange.End = end +} + +func (b *SSHHostBlock) GetOptions() *treemap.Map { + return b.Options +} + +func (b *SSHHostBlock) GetEntryOption() *SSHOption { + return b.HostOption +} + +func (b *SSHHostBlock) GetLocation() common.LocationRange { + return b.LocationRange +} + +type SSHType uint8 + +const ( + SSHTypeOption SSHType = iota + SSHTypeMatch + SSHTypeHost +) + +type SSHEntry interface { + GetType() SSHType + GetOption() *SSHOption +} + +func (o *SSHOption) GetType() SSHType { + return SSHTypeOption +} + +func (o *SSHOption) GetOption() *SSHOption { + return o +} + +func (b *SSHMatchBlock) GetType() SSHType { + return SSHTypeMatch +} + +func (b *SSHMatchBlock) GetOption() *SSHOption { + return b.MatchOption +} + +func (b *SSHHostBlock) GetType() SSHType { + return SSHTypeHost +} + +func (b *SSHHostBlock) GetOption() *SSHOption { + return b.HostOption +} + +// FindBlock Gets the block based on the line number +// Note: This does not find the block strictly. +// This means an empty line will belong to the previous block +// However, this is required for example for completions, as the +// user is about to type the new option, and we therefore need to know +// which block this new option will belong to. +// +// You will probably need this in most cases +func (c SSHConfig) FindBlock(line uint32) SSHBlock { + it := c.Options.Iterator() + it.End() + + for it.Prev() { + entry := it.Value().(SSHEntry) + + if entry.GetType() == SSHTypeOption { + continue + } + + block := entry.(SSHBlock) + + if line >= block.GetLocation().Start.Line { + return block + } + } + + return nil +} + +func (c SSHConfig) FindOption(line uint32) (*SSHOption, SSHBlock) { + block := c.FindBlock(line) + + var option *SSHOption + + if block == nil { + if rawOption, found := c.Options.Get(line); found { + option = rawOption.(*SSHOption) + } + } else { + if line == block.GetLocation().Start.Line { + return block.GetEntryOption(), block + } + + if rawOption, found := block.GetOptions().Get(line); found { + option = rawOption.(*SSHOption) + } + } + + return option, block +} + +type AllOptionInfo struct { + Block SSHBlock + Option *SSHOption +} + +func (c SSHConfig) GetAllOptionsForBlock(block SSHBlock) []AllOptionInfo { + if block == nil { + return c.GetAllOptions() + } + + return utils.Map( + block.GetOptions().Values(), + func(rawOption interface{}) AllOptionInfo { + option := rawOption.(*SSHOption) + + return AllOptionInfo{ + Block: block, + Option: option, + } + }, + ) +} + +func (c SSHConfig) GetAllOptions() []AllOptionInfo { + options := make([]AllOptionInfo, 0, 50) + + for _, rawEntry := range c.Options.Values() { + switch rawEntry.(type) { + case *SSHOption: + option := rawEntry.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: nil, + Option: option, + }) + case *SSHMatchBlock: + block := rawEntry.(SSHBlock) + + options = append(options, AllOptionInfo{ + Block: block, + Option: block.GetEntryOption(), + }) + + for _, rawOption := range block.GetOptions().Values() { + option := rawOption.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: block, + Option: option, + }) + } + case *SSHHostBlock: + block := rawEntry.(SSHBlock) + + options = append(options, AllOptionInfo{ + Block: block, + Option: block.GetEntryOption(), + }) + + for _, rawOption := range block.GetOptions().Values() { + option := rawOption.(*SSHOption) + options = append(options, AllOptionInfo{ + Block: block, + Option: option, + }) + } + } + + } + + return options +} + +func (c SSHConfig) GetOptionsInRange(startLine uint32, endLine uint32) []AllOptionInfo { + options := make([]AllOptionInfo, 0, 50) + + for _, info := range c.GetAllOptions() { + if info.Option.LocationRange.Start.Line >= startLine && info.Option.LocationRange.End.Line <= endLine { + options = append(options, info) + } + } + + return options +} diff --git a/server/handlers/ssh_config/document_fields.go b/server/handlers/ssh_config/document_fields.go new file mode 100644 index 0000000..7663a21 --- /dev/null +++ b/server/handlers/ssh_config/document_fields.go @@ -0,0 +1,91 @@ +package sshconfig + +import ( + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/fields" + "config-lsp/utils" +) + +func (d SSHDocument) FindOptionByNameAndBlock( + option fields.NormalizedOptionName, + block ast.SSHBlock, +) *ast.AllOptionInfo { + for _, info := range d.FindOptionsByName(option) { + if info.Block == block { + return &info + } + } + + return nil +} + +func (d SSHDocument) FindOptionsByName( + option fields.NormalizedOptionName, +) []ast.AllOptionInfo { + options := make([]ast.AllOptionInfo, 0, 5) + + for _, info := range d.Config.GetAllOptions() { + if info.Option.Key.Key == option { + options = append(options, info) + } + } + + return options +} + +func (d SSHDocument) DoesOptionExist( + option fields.NormalizedOptionName, + block ast.SSHBlock, +) bool { + return d.FindOptionByNameAndBlock(option, block) != nil +} + +var matchOption = fields.CreateNormalizedName("Match") + +func (d SSHDocument) GetAllMatchBlocks() []*ast.SSHMatchBlock { + matchBlocks := make([]*ast.SSHMatchBlock, 0, 5) + + options := d.Indexes.AllOptionsPerName[matchOption] + blocks := utils.KeysOfMap(options) + + for _, block := range blocks { + matchBlocks = append(matchBlocks, block.(*ast.SSHMatchBlock)) + } + + return matchBlocks +} + +var hostOption = fields.CreateNormalizedName("Host") + +// GetAllHostBlocks: Returns all Host blocks. +// Note: This is not sorted +func (d SSHDocument) GetAllHostBlocks() []*ast.SSHHostBlock { + hostBlocks := make([]*ast.SSHHostBlock, 0, 5) + + options := d.Indexes.AllOptionsPerName[hostOption] + blocks := utils.KeysOfMap(options) + + for _, block := range blocks { + hostBlocks = append(hostBlocks, block.(*ast.SSHHostBlock)) + } + + return hostBlocks +} + +// GetAllBlocks returns all blocks in the document +// Note: The blocks are **not** sorted +// Note: This also returns `nil` (as the global block) +func (d SSHDocument) GetAllBlocks() []ast.SSHBlock { + blocks := make([]ast.SSHBlock, 0) + blocks = append(blocks, nil) + + for _, block := range d.GetAllHostBlocks() { + blocks = append(blocks, block) + } + + for _, block := range d.GetAllMatchBlocks() { + blocks = append(blocks, block) + } + + return blocks +} diff --git a/server/handlers/ssh_config/document_fields_test.go b/server/handlers/ssh_config/document_fields_test.go new file mode 100644 index 0000000..653a546 --- /dev/null +++ b/server/handlers/ssh_config/document_fields_test.go @@ -0,0 +1,64 @@ +package sshconfig + +import ( + "config-lsp/handlers/ssh_config/ast" + "config-lsp/handlers/ssh_config/indexes" + "config-lsp/utils" + "testing" +) + +func TestComplexExample( + t *testing.T, +) { + input := utils.Dedent(` +ProxyCommand hello + +Host laptop + HostName laptop.lan + ProxyCommand test + +Match originalhost laptop exec "[[ $(/usr/bin/dig +short laptop.lan) == '' ]]" + HostName laptop.sdn +`) + c := ast.NewSSHConfig() + errors := c.Parse(input) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + i, errors := indexes.CreateIndexes(*c) + + if len(errors) != 0 { + t.Fatalf("Expected no errors, got %v", errors) + } + + d := &SSHDocument{ + Config: c, + Indexes: i, + } + + options := d.FindOptionsByName("proxycommand") + if !(len(options) == 2 && options[0].Option.Start.Line == 0 && options[1].Option.Start.Line == 4) { + t.Errorf("Expected 2 options, got %v", options) + } + + options = d.FindOptionsByName("hostname") + if !(len(options) == 2 && options[0].Option.Start.Line == 3 && options[1].Option.Start.Line == 7) { + t.Errorf("Expected 2 options, got %v", options) + } + + block := d.Config.FindBlock(4) + if !(d.FindOptionByNameAndBlock("proxycommand", block).Option.Start.Line == 4) { + t.Errorf("Expected 4, got %v", d.FindOptionByNameAndBlock("proxycommand", block).Option.Start.Line) + } + + if !(d.FindOptionByNameAndBlock("proxycommand", nil).Option.Start.Line == 0) { + t.Errorf("Expected 0, got %v", d.FindOptionByNameAndBlock("proxycommand", nil).Option.Start.Line) + } + + matchBlocks := d.GetAllMatchBlocks() + if !(len(matchBlocks) == 1 && matchBlocks[0].Start.Line == 6) { + t.Errorf("Expected 1 match block, got %v", matchBlocks) + } +} diff --git a/server/handlers/ssh_config/fields/common.go b/server/handlers/ssh_config/fields/common.go new file mode 100644 index 0000000..35d0123 --- /dev/null +++ b/server/handlers/ssh_config/fields/common.go @@ -0,0 +1,9 @@ +package fields + +import "strings" + +type NormalizedOptionName string + +func CreateNormalizedName(s string) NormalizedOptionName { + return NormalizedOptionName(strings.ToLower(s)) +} diff --git a/server/handlers/ssh_config/fields/fields.go b/server/handlers/ssh_config/fields/fields.go new file mode 100644 index 0000000..59caccf --- /dev/null +++ b/server/handlers/ssh_config/fields/fields.go @@ -0,0 +1,982 @@ +package fields + +import ( + "config-lsp/common/ssh" + docvalues "config-lsp/doc-values" + "regexp" +) + +var ZERO = 0 +var MAX_PORT = 65535 + +var Options = map[NormalizedOptionName]docvalues.DocumentationValue{ + "host": { + Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be only for those hosts that match one of the patterns given after the keyword. If more than one pattern is provided, they should be separated by whitespace. A single ‘*’ as a pattern can be used to provide global defaults for all hosts. The host is usually the hostname argument given on the command line (see the CanonicalizeHostname keyword for exceptions). + A pattern entry may be negated by prefixing it with an exclamation mark (‘!’). If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match. Negated matches are therefore useful to provide exceptions for wildcard matches. + See PATTERNS for more information on patterns.`, + Value: docvalues.StringValue{}, + }, + "match": { + Documentation: `Restricts the following declarations (up to the next Host or Match keyword) to be used only when the conditions following the Match keyword are satisfied. Match conditions are specified using one or more criteria or the single token all which always matches. The available criteria keywords are: canonical, final, exec, localnetwork, host, originalhost, tagged, user, and localuser. The all criteria must appear alone or immediately after canonical or final. Other criteria may be combined arbitrarily. All criteria but all, canonical, and final require an argument. Criteria may be negated by prepending an exclamation mark (‘!’). + The canonical keyword matches only when the configuration file is being re-parsed after hostname canonicalization (see the CanonicalizeHostname option). This may be useful to specify conditions that work with canonical host names only. + The final keyword requests that the configuration be re-parsed (regardless of whether CanonicalizeHostname is enabled), and matches only during this final pass. If CanonicalizeHostname is enabled, then canonical and final match during the same pass. + The exec keyword executes the specified command under the user's shell. If the command returns a zero exit status then the condition is considered true. Commands containing whitespace characters must be quoted. Arguments to exec accept the tokens described in the TOKENS section. + The localnetwork keyword matches the addresses of active local network interfaces against the supplied list of networks in CIDR format. This may be convenient for varying the effective configuration on devices that roam between networks. Note that network address is not a trustworthy criteria in many situations (e.g. when the network is automatically configured using DHCP) and so caution should be applied if using it to control security-sensitive configuration. + The other keywords' criteria must be single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section. The criteria for the host keyword are matched against the target hostname, after any substitution by the Hostname or CanonicalizeHostname options. The originalhost keyword matches against the hostname as it was specified on the command-line. The tagged keyword matches a tag name specified by a prior Tag directive or on the ssh(1) command-line using the -P flag. The user keyword matches against the target username on the remote host. The localuser keyword matches against the name of the local user running ssh(1) (this keyword may be useful in system-wide ssh_config files).`, + Value: docvalues.StringValue{}, + }, + "addkeystoagent": { + Documentation: `Specifies whether keys should be automatically added to a running ssh-agent(1). If this option is set to yes and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if by ssh-add(1). If this option is set to ask, ssh(1) will require confirmation using the SSH_ASKPASS program before adding a key (see ssh-add(1) for details). If this option is set to confirm, each use of the key must be confirmed, as if the -c option was specified to ssh-add(1). If this option is set to no, no keys are added to the agent. Alternately, this option may be specified as a time interval using the format described in the TIME FORMATS section of sshd_config(5) to specify the key's lifetime in ssh-agent(1), after which it will automatically be removed. The argument must be no (the default), yes, confirm (optionally followed by a time interval), ask or a time interval.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("confirm"), + docvalues.CreateEnumString("ask"), + }, + }, + docvalues.TimeFormatValue{}, + }, + }, + }, + "addressfamily": { + Documentation: `Specifies which address family to use when connecting. Valid arguments are any (the default), inet (use IPv4 only), or inet6 (use IPv6 only).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("any"), + docvalues.CreateEnumString("inet"), + docvalues.CreateEnumString("inet6"), + }, + }, + }, + "batchmode": { + Documentation: `If set to yes, user interaction such as password prompts and host key confirmation requests will be disabled. This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1). The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "bindaddress": { + Documentation: `Use the specified address on the local machine as the source address of the connection. Only useful on systems with more than one address.`, + Value: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, + }, + "bindinterface": { + Documentation: `Use the address of the specified interface on the local machine as the source address of the connection.`, + Value: docvalues.IPAddressValue{ + AllowIPv4: false, + AllowIPv6: false, + AllowRange: false, + }, + }, + "canonicaldomains": { + Documentation: `When CanonicalizeHostname is enabled, this option specifies the list of domain suffixes in which to search for the specified destination host.`, + Value: docvalues.StringValue{}, + }, + "canonicalizefallbacklocal": { + Documentation: `Specifies whether to fail with an error when hostname canonicalization fails. The default, yes, will attempt to look up the unqualified hostname using the system resolver's search rules. A value of no will cause ssh(1) to fail instantly if CanonicalizeHostname is enabled and the target hostname cannot be found in any of the domains specified by CanonicalDomains.`, + Value: booleanEnumValue, + }, + "canonicalizehostname": { + Documentation: `Controls whether explicit hostname canonicalization is performed. The default, no, is not to perform any name rewriting and let the system resolver handle all hostname lookups. If set to yes then, for connections that do not use a ProxyCommand or ProxyJump, ssh(1) will attempt to canonicalize the hostname specified on the command line using the CanonicalDomains suffixes and CanonicalizePermittedCNAMEs rules. If CanonicalizeHostname is set to always, then canonicalization is applied to proxied connections too. + If this option is enabled, then the configuration files are processed again using the new target name to pick up any new configuration in matching Host and Match stanzas. A value of none disables the use of a ProxyJump host.`, + Value: booleanEnumValue, + }, + "canonicalizemaxdots": { + Documentation: `Specifies the maximum number of dot characters in a hostname before canonicalization is disabled. The default, 1, allows a single dot (i.e. hostname.subdomain).`, + Value: docvalues.PositiveNumberValue(), + }, + "canonicalizepermittedcnames": { + Documentation: `Specifies rules to determine whether CNAMEs should be followed when canonicalizing hostnames. The rules consist of one or more arguments of source_domain_list:target_domain_list, where source_domain_list is a pattern-list of domains that may follow CNAMEs in canonicalization, and target_domain_list is a pattern-list of domains that they may resolve to. + For example, + '*.a.example.com:*.b.example.com,*.c.example.com' will allow hostnames matching '*.a.example.com' to be canonicalized to names in the '*.b.example.com' or '*.c.example.com' domains. + A single argument of 'none' causes no CNAMEs to be considered for canonicalization. This is the default behaviour.`, + Value: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.StringValue{}, + }, + }, + "casignaturealgorithms": { + Documentation: `Specifies which algorithms are allowed for signing of certificates by certificate authorities (CAs). The default is: + +ssh-ed25519,ecdsa-sha2-nistp256, +ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a + ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. + ssh(1) will not accept host certificates signed using algorithms other than those specified.`, + Value: docvalues.PrefixWithMeaningValue{ + Prefixes: []docvalues.Prefix{ + { + Prefix: "+", + Meaning: "Appende to the default set", + }, + { + Prefix: "-", + Meaning: "Remove from the default set", + }, + }, + SubValue: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.DuplicatesAllowedExtractor, + // TODO: Add + SubValue: docvalues.StringValue{}, + }, + }, + }, + "certificatefile": { + Documentation: `Specifies a file from which the user's certificate is read. A corresponding private key must be provided separately in order to use this certificate either from an IdentityFile directive or -i flag to ssh(1), via ssh-agent(1), or via a PKCS11Provider or SecurityKeyProvider. + Arguments to CertificateFile may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. + It is possible to have multiple certificate files specified in configuration files; these certificates will be tried in sequence. Multiple CertificateFile directives will add to the list of certificates used for authentication.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + "channeltimeout": { + Documentation: `Specifies whether and how quickly ssh(1) should close inactive channels. Timeouts are specified as one or more “type=interval” pairs separated by whitespace, where the “type” must be the special keyword “global” or a channel type name from the list below, optionally containing wildcard characters. + +The timeout value “interval” is specified in seconds or may use any of the units documented in the TIME FORMATS section. For example, “session=5m” would cause interactive sessions to terminate after five minutes of inactivity. Specifying a zero value disables the inactivity timeout. + +The special timeout “global” applies to all active channels, taken together. Traffic on any active channel will reset the timeout, but when the timeout expires then all open channels will be closed. Note that this global timeout is not matched by wildcards and must be specified explicitly. + +The available channel type names include: + +agent-connection + Open connections to ssh-agent(1). +direct-tcpip, direct-streamlocal@openssh.com + Open TCP or Unix socket (respectively) connections that have been established from a ssh(1) local forwarding, i.e. LocalForward or DynamicForward. +forwarded-tcpip, forwarded-streamlocal@openssh.com + Open TCP or Unix socket (respectively) connections that have been established to a sshd(8) listening on behalf of a ssh(1) remote forwarding, i.e. RemoteForward. +session + The interactive main session, including shell session, command execution, scp(1), sftp(1), etc. +tun-connection + Open TunnelForward connections. +x11-connection + Open X11 forwarding sessions. + +Note that in all the above cases, terminating an inactive session does not guarantee to remove all resources associated with the session, e.g. shell processes or X11 clients relating to the session may continue to execute. + +Moreover, terminating an inactive channel or session does not necessarily close the SSH connection, nor does it prevent a client from requesting another channel of the same type. In particular, expiring an inactive forwarding session does not prevent another identical forwarding from being subsequently created. + +The default is not to expire channels of any type for inactivity.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &channelTimeoutExtractor, + SubValue: docvalues.KeyValueAssignmentValue{ + ValueIsOptional: false, + Separator: "=", + Key: docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("global"), + docvalues.CreateEnumString("agent-connection"), + docvalues.CreateEnumString("direct-tcpip"), + docvalues.CreateEnumString("direct-streamlocal@openssh.com"), + docvalues.CreateEnumString("forwarded-tcpip"), + docvalues.CreateEnumString("forwarded-streamlocal@openssh.com"), + docvalues.CreateEnumString("session"), + docvalues.CreateEnumString("tun-connection"), + docvalues.CreateEnumString("x11-connection"), + }, + }, + Value: docvalues.TimeFormatValue{}, + }, + }, + }, + "checkhostip": { + Documentation: `If set to yes, ssh(1) will additionally check the host IP address in the known_hosts file. This allows it to detect if a host key changed due to DNS spoofing and will add addresses of destination hosts to ~/.ssh/known_hosts in the process, regardless of the setting of StrictHostKeyChecking. If the option is set to no (the default), the check will not be executed.`, + Value: booleanEnumValue, + }, + "ciphers": { + Documentation: `Specifies the ciphers allowed and their order of preference. Multiple ciphers must be comma-separated. If the specified list begins with a + ‘+’ character, then the specified ciphers will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified ciphers (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified ciphers will be placed at the head of the default set. + The supported ciphers are: + +3des-cbc +aes128-cbc +aes192-cbc +aes256-cbc +aes128-ctr +aes192-ctr +aes256-ctr +aes128-gcm@openssh.com +aes256-gcm@openssh.com +chacha20-poly1305@openssh.com + + The default is: + +chacha20-poly1305@openssh.com, +aes128-ctr,aes192-ctr,aes256-ctr, +aes128-gcm@openssh.com,aes256-gcm@openssh.com + + The list of available ciphers may also be obtained using 'ssh -Q cipher'.`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("3des-cbc"), + docvalues.CreateEnumString("aes128-cbc"), + docvalues.CreateEnumString("aes192-cbc"), + docvalues.CreateEnumString("aes256-cbc"), + docvalues.CreateEnumString("aes128-ctr"), + docvalues.CreateEnumString("aes192-ctr"), + docvalues.CreateEnumString("aes256-ctr"), + docvalues.CreateEnumString("aes128-gcm@openssh.com"), + docvalues.CreateEnumString("aes256-gcm@openssh.com"), + docvalues.CreateEnumString("chacha20-poly1305@openssh.com"), + }), + }, + "clearallforwardings": { + Documentation: `Specifies that all local, remote, and dynamic port forwardings specified in the configuration files or on the command line be cleared. This option is primarily useful when used from the ssh(1) command line to clear port forwardings set in configuration files, and is automatically set by scp(1) and sftp(1). The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "compression": { + Documentation: `Specifies whether to use compression. The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "connectionattempts": { + Documentation: `Specifies the number of tries (one per second) to make before exiting. The argument must be an integer. This may be useful in scripts if the connection sometimes fails. The default is 1.`, + Value: docvalues.NumberValue{}, + }, + "connecttimeout": { + Documentation: `Specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout. This timeout is applied both to establishing the connection and to performing the initial SSH protocol handshake and key exchange.`, + Value: docvalues.NumberValue{}, + }, + "controlmaster": { + Documentation: `Enables the sharing of multiple sessions over a single network connection. When set to yes, ssh(1) will listen for connections on a control socket specified using the ControlPath argument. Additional sessions can connect to this socket using the same ControlPath with ControlMaster set to no (the default). These sessions will try to reuse the master instance's network connection rather than initiating new ones, but will fall back to connecting normally if the control socket does not exist, or is not listening. + Setting this to ask will cause ssh(1) to listen for control connections, but require confirmation using ssh-askpass(1). If the ControlPath cannot be opened, ssh(1) will continue without connecting to a master instance. + X11 and ssh-agent(1) forwarding is supported over these multiplexed connections, however the display and agent forwarded will be the one belonging to the master connection i.e. it is not possible to forward multiple displays or agents. + Two additional options allow for opportunistic multiplexing: try to use a master connection but fall back to creating a new one if one does not already exist. These options are: auto and autoask. The latter requires confirmation like the ask option.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + docvalues.CreateEnumString("auto"), + docvalues.CreateEnumString("autoask"), + }, + }, + }, + "controlpath": { + Documentation: `Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string none to disable connection sharing. Arguments to ControlPath may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r (or alternatively %C) and be placed in a directory that is not writable by other users. This ensures that shared connections are uniquely identified.`, + Value: docvalues.StringValue{}, + }, + "controlpersist": { + Documentation: `When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for future client connections) after the initial client connection has been closed. If set to no (the default), then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the 'ssh -O exit'). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + booleanEnumValue, + docvalues.TimeFormatValue{}, + docvalues.PositiveNumberValue(), + }, + }, + }, + "dynamicforward": { + Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. The argument must be + [bind_address:]port. IPv6 addresses can be specified by enclosing addresses in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. + Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh(1) will act as a SOCKS server. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + docvalues.KeyValueAssignmentValue{ + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + }, + }, + }, + "enableescapecommandline": { + Documentation: `Enables the command line option in the EscapeChar menu for interactive sessions (default ‘~C’). By default, the command line is disabled.`, + Value: docvalues.StringValue{}, + }, + "enablesshkeysign": { + Documentation: `Setting this option to yes in the global client configuration file /etc/ssh/ssh_config enables the use of the helper program ssh-keysign(8) during HostbasedAuthentication. The argument must be yes or no (the default). This option should be placed in the non-hostspecific section. See ssh-keysign(8) for more information.`, + Value: booleanEnumValue, + }, + "escapechar": { + Documentation: `Sets the escape character (default: ‘~’). The escape character can also be set on the command line. The argument should be a single character, ‘^’ followed by a letter, or none to disable the escape character entirely (making the connection transparent for binary data).`, + Value: docvalues.StringValue{}, + }, + "exitonforwardfailure": { + Documentation: `Specifies whether ssh(1) should terminate the connection if it cannot set up all requested dynamic, tunnel, local, and remote port forwardings, (e.g. if either end is unable to bind and listen on a specified port). Note that ExitOnForwardFailure does not apply to connections made over port forwardings and will not, for example, cause ssh(1) to exit if TCP connections to the ultimate forwarding destination fail. The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "fingerprinthash": { + Documentation: `Specifies the hash algorithm used when displaying key fingerprints. Valid options are: md5 and sha256 (the default).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("md5"), + docvalues.CreateEnumString("sha256"), + }, + }, + }, + "forkafterauthentication": { + Documentation: `Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies the StdinNull configuration option being set to “yes”. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm, which is the same as ssh host xterm if the ForkAfterAuthentication configuration option is set to “yes”. + If the ExitOnForwardFailure configuration option is set to “yes”, then a client started with the ForkAfterAuthentication configuration option being set to “yes” will wait for all remote port forwards to be successfully established before placing itself in the background. The argument to this keyword must be yes (same as the -f option) or no (the default).`, + Value: booleanEnumValue, + }, + "forwardagent": { + Documentation: `Specifies whether the connection to the authentication agent (if any) will be forwarded to the remote machine. The argument may be yes, no (the default), an explicit path to an agent socket or the name of an environment variable (beginning with ‘$’) in which to find the path. + Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + booleanEnumValue, + docvalues.StringValue{}, + }, + }, + }, + "forwardx11": { + Documentation: `Specifies whether X11 connections will be automatically redirected over the secure channel and DISPLAY set. The argument must be yes or no (the default). + X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X11 authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring if the ForwardX11Trusted option is also enabled.`, + Value: booleanEnumValue, + }, + "forwardx11timeout": { + Documentation: `Specify a timeout for untrusted X11 forwarding using the format described in the TIME FORMATS section of sshd_config(5). X11 connections received by ssh(1) after this time will be refused. Setting ForwardX11Timeout to zero will disable the timeout and permit X11 forwarding for the life of the connection. The default is to disable untrusted X11 forwarding after twenty minutes has elapsed.`, + Value: docvalues.TimeFormatValue{}, + }, + "forwardx11trusted": { + Documentation: `If this option is set to yes, remote X11 clients will have full access to the original X11 display. + If this option is set to no (the default), remote X11 clients will be considered untrusted and prevented from stealing or tampering with data belonging to trusted X11 clients. Furthermore, the xauth(1) token used for the session will be set to expire after 20 minutes. Remote clients will be refused access after this time. + See the X11 SECURITY extension specification for full details on the restrictions imposed on untrusted clients.`, + Value: booleanEnumValue, + }, + "gatewayports": { + Documentation: `Specifies whether remote hosts are allowed to connect to local forwarded ports. By default, ssh(1) binds local port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that ssh should bind local port forwardings to the wildcard address, thus allowing remote hosts to connect to forwarded ports. The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "globalknownhostsfile": { + Documentation: `Specifies one or more files to use for the global host key database, separated by whitespace. The default is + /etc/ssh/ssh_known_hosts, + /etc/ssh/ssh_known_hosts2.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + }, + "gssapiauthentication": { + Documentation: `Specifies whether user authentication based on GSSAPI is allowed. The default is no.`, + Value: booleanEnumValue, + }, + "gssapidelegatecredentials": { + Documentation: `Forward (delegate) credentials to the server. The default is no.`, + Value: booleanEnumValue, + }, + "hashknownhosts": { + Documentation: `Indicates that ssh(1) should hash host names and addresses when they are added to ~/.ssh/known_hosts. These hashed names may be used normally by ssh(1) and sshd(8), but they do not visually reveal identifying information if the file's contents are disclosed. The default is no. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using ssh-keygen(1).`, + Value: booleanEnumValue, + }, + "hostbasedacceptedalgorithms": { + Documentation: `Specifies the signature algorithms that will be used for hostbased authentication as a comma-separated list of patterns. Alternately if the specified list begins with a ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: + +ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + The -Q option of ssh(1) may be used to list supported signature algorithms. This was formerly named HostbasedKeyTypes.`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.DeprecatedValue { + options, err := ssh.QueryOpenSSHOptions("HostbasedAcceptedAlgorithms") + + if err != nil { + // Fallback + options, _ = ssh.QueryOpenSSHOptions("HostbasedAcceptedKeyTypes") + } + + return prefixPlusMinusCaret(options) + }, + }, + }, + "hostbasedauthentication": { + Documentation: `Specifies whether to try rhosts based authentication with public key authentication. The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "hostkeyalgorithms": { + Documentation: `Specifies the host key signature algorithms that the client wants to use in order of preference. Alternately if the specified list begins with a + ‘+’ character, then the specified signature algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified signature algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified signature algorithms will be placed at the head of the default set. The default for this option is: + +ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ecdsa-sha2-nistp256@openssh.com, +sk-ssh-ed25519@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + If hostkeys are known for the destination host then this default is modified to prefer their algorithms. + The list of available signature algorithms may also be obtained using 'ssh -Q HostKeyAlgorithms'.`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.DeprecatedValue { + options, _ := ssh.QueryOpenSSHOptions("HostKeyAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, + }, + "hostkeyalias": { + Documentation: `Specifies an alias that should be used instead of the real host name when looking up or saving the host key in the host key database files and when validating host certificates. This option is useful for tunneling SSH connections or for multiple servers running on a single host.`, + Value: docvalues.StringValue{}, + }, + "hostname": { + Documentation: `Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts. Arguments to Hostname accept the tokens described in the TOKENS section. Numeric IP addresses are also permitted (both on the command line and in Hostname specifications). The default is the name given on the command line.`, + Value: docvalues.StringValue{}, + }, + "identitiesonly": { + Documentation: `Specifies that ssh(1) should only use the configured authentication identity and certificate files (either the default files, or those explicitly configured in the ssh_config files or passed on the ssh(1) command-line), even if ssh-agent(1) or a PKCS11Provider or SecurityKeyProvider offers more identities. The argument to this keyword must be yes or no (the default). This option is intended for situations where ssh-agent offers many different identities.`, + Value: booleanEnumValue, + }, + "identityagent": { + Documentation: `Specifies the UNIX-domain socket used to communicate with the authentication agent. This option overrides the SSH_AUTH_SOCK environment variable and can be used to select a specific agent. Setting the socket name to none disables the use of an authentication agent. If the string 'SSH_AUTH_SOCK' is specified, the location of the socket will be read from the SSH_AUTH_SOCK environment variable. Otherwise if the specified value begins with a '$' character, then it will be treated as an environment variable containing the location of the socket. + Arguments to IdentityAgent may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.StringValue{}, + }, + "identityfile": { + Documentation: `Specifies a file from which the user's ECDSA, authenticator-hosted ECDSA, Ed25519, authenticator-hosted Ed25519 or RSA authentication identity is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, + ~/.ssh/id_ecdsa, + ~/.ssh/id_ecdsa_sk, + ~/.ssh/id_ed25519 and + ~/.ssh/id_ed25519_sk. Additionally, any identities represented by the authentication agent will be used for authentication unless IdentitiesOnly is set. If no certificates have been explicitly specified by CertificateFile, ssh(1) will try to load certificate information from the filename obtained by appending -cert.pub to the path of a specified IdentityFile. + Arguments to IdentityFile may use the tilde syntax to refer to a user's home directory or the tokens described in the TOKENS section. Alternately an argument of none may be used to indicate no identity files should be loaded. + It is possible to have multiple identity files specified in configuration files; all these identities will be tried in sequence. Multiple IdentityFile directives will add to the list of identities tried (this behaviour differs from that of other configuration directives). + IdentityFile may be used in conjunction with IdentitiesOnly to select which identities in an agent are offered during authentication. IdentityFile may also be used in conjunction with CertificateFile in order to provide any certificate also needed for authentication with the identity.`, + Value: docvalues.StringValue{}, + }, + "ignoreunknown": { + Documentation: `Specifies a pattern-list of unknown options to be ignored if they are encountered in configuration parsing. This may be used to suppress errors if ssh_config contains options that are unrecognised by ssh(1). It is recommended that IgnoreUnknown be listed early in the configuration file as it will not be applied to unknown options that appear before it.`, + Value: docvalues.StringValue{}, + }, + "include": { + Documentation: `Include the specified configuration file(s). Multiple pathnames may be specified and each pathname may contain glob(7) wildcards, tokens as described in the TOKENS section, environment variables as described in the ENVIRONMENT VARIABLES section and, for user configurations, shell-like ‘~’ references to user home directories. Wildcards will be expanded and processed in lexical order. Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the system configuration file. Include directive may appear inside a Match or Host block to perform conditional inclusion.`, + Value: docvalues.ArrayValue{ + Separator: " ", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.StringValue{}, + }, + }, + "ipqos": { + Documentation: `Specifies the IPv4 type-of-service or DSCP class for connections. Accepted values are af11, af12, af13, af21, af22, af23, af31, af32, af33, af41, af42, af43, cs0, cs1, cs2, cs3, cs4, cs5, cs6, cs7, ef, le, lowdelay, throughput, reliability, a numeric value, or none to use the operating system default. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is af21 (Low-Latency Data) for interactive sessions and cs1 (Lower Effort) for non-interactive sessions.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + docvalues.NumberValue{}, + docvalues.EnumValue{ + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("none"), + }, + }, + docvalues.ArrayValue{ + Separator: " ", + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("af11"), + docvalues.CreateEnumString("af12"), + docvalues.CreateEnumString("af13"), + docvalues.CreateEnumString("af21"), + docvalues.CreateEnumString("af22"), + docvalues.CreateEnumString("af23"), + docvalues.CreateEnumString("af31"), + docvalues.CreateEnumString("af32"), + docvalues.CreateEnumString("af33"), + docvalues.CreateEnumString("af41"), + docvalues.CreateEnumString("af42"), + docvalues.CreateEnumString("af43"), + docvalues.CreateEnumString("cs0"), + docvalues.CreateEnumString("cs1"), + docvalues.CreateEnumString("cs2"), + docvalues.CreateEnumString("cs3"), + docvalues.CreateEnumString("cs4"), + docvalues.CreateEnumString("cs5"), + docvalues.CreateEnumString("cs6"), + docvalues.CreateEnumString("cs7"), + docvalues.CreateEnumString("ef"), + docvalues.CreateEnumString("le"), + docvalues.CreateEnumString("lowdelay"), + docvalues.CreateEnumString("throughput"), + docvalues.CreateEnumString("reliability"), + docvalues.CreateEnumString("none"), + }, + }, + }, + }, + }, + }, + "kbdinteractiveauthentication": { + // TODO: Show deprecation + Documentation: `Specifies whether to use keyboard-interactive authentication. The argument to this keyword must be yes (the default) or no. ChallengeResponseAuthentication is a deprecated alias for this.`, + Value: booleanEnumValue, + }, + "kbdinteractivedevices": { + Documentation: `Specifies the list of methods to use in keyboard-interactive authentication. Multiple method names must be comma-separated. The default is to use the server specified list. The methods available vary depending on what the server supports. For an OpenSSH server, it may be zero or more of: bsdauth, pam, and skey.`, + Value: docvalues.ArrayValue{ + Separator: ",", + DuplicatesExtractor: &docvalues.SimpleDuplicatesExtractor, + SubValue: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("bsdauth"), + docvalues.CreateEnumString("pam"), + docvalues.CreateEnumString("skey"), + }, + }, + }, + }, + "kexalgorithms": { + Documentation: `Specifies the permitted KEX (Key Exchange) algorithms that will be used and their preference order. The selected algorithm will be the first algorithm in this list that the server also supports. Multiple algorithms must be comma-separated. + If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a + ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ character, then the specified algorithms will be placed at the head of the default set. + The default is: + +sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com, +mlkem768x25519-sha256, +curve25519-sha256,curve25519-sha256@libssh.org, +ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, +diffie-hellman-group-exchange-sha256, +diffie-hellman-group16-sha512, +diffie-hellman-group18-sha512, +diffie-hellman-group14-sha256 + + The list of supported key exchange algorithms may also be obtained using 'ssh -Q kex'.`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("curve25519-sha256"), + docvalues.CreateEnumString("curve25519-sha256@libssh.org"), + docvalues.CreateEnumString("diffie-hellman-group1-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha1"), + docvalues.CreateEnumString("diffie-hellman-group14-sha256"), + docvalues.CreateEnumString("diffie-hellman-group16-sha512"), + docvalues.CreateEnumString("diffie-hellman-group18-sha512"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha1"), + docvalues.CreateEnumString("diffie-hellman-group-exchange-sha256"), + docvalues.CreateEnumString("ecdh-sha2-nistp256"), + docvalues.CreateEnumString("ecdh-sha2-nistp384"), + docvalues.CreateEnumString("ecdh-sha2-nistp521"), + docvalues.CreateEnumString("sntrup761x25519-sha512@openssh.com"), + }), + }, + "knownhostscommand": { + Documentation: `Specifies a command to use to obtain a list of host keys, in addition to those listed in UserKnownHostsFile and GlobalKnownHostsFile. This command is executed after the files have been read. It may write host key lines to standard output in identical format to the usual files (described in the VERIFYING HOST KEYS section in ssh(1)). Arguments to KnownHostsCommand accept the tokens described in the TOKENS section. The command may be invoked multiple times per connection: once when preparing the preference list of host key algorithms to use, again to obtain the host key for the requested host name and, if CheckHostIP is enabled, one more time to obtain the host key matching the server's address. If the command exits abnormally or returns a non-zero exit status then the connection is terminated.`, + Value: docvalues.StringValue{}, + }, + "localcommand": { + Documentation: `Specifies a command to execute on the local machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to LocalCommand accept the tokens described in the TOKENS section. + The command is run synchronously and does not have access to the session of the ssh(1) that spawned it. It should not be used for interactive commands. + This directive is ignored unless PermitLocalCommand has been enabled.`, + Value: docvalues.StringValue{}, + }, + "localforward": { + Documentation: `Specifies that a TCP port on the local machine be forwarded over the secure channel to the specified host and port from the remote machine. The first argument specifies the listener and may be + [bind_address:]port or a Unix domain socket path. The second argument is the destination and may be host:hostport or a Unix domain socket path if the remote host supports it. + IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + docvalues.KeyValueAssignmentValue{ + Key: docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, + }, + }, + }, + }, + }, + "loglevel": { + Documentation: `Gives the verbosity level that is used when logging messages from ssh(1). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. DEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of verbose output.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("QUIET"), + docvalues.CreateEnumString("FATAL"), + docvalues.CreateEnumString("ERROR"), + docvalues.CreateEnumString("INFO"), + docvalues.CreateEnumString("VERBOSE"), + docvalues.CreateEnumString("DEBUG"), + docvalues.CreateEnumString("DEBUG1"), + docvalues.CreateEnumString("DEBUG2"), + docvalues.CreateEnumString("DEBUG3"), + }, + }, + }, + "logverbose": { + Documentation: `Specify one or more overrides to LogLevel. An override consists of one or more pattern lists that matches the source file, function and line number to force detailed logging for. For example, an override pattern of: + + kex.c:*:1000,*:kex_exchange_identification():*,packet.c:* + + would enable detailed logging for line 1000 of kex.c, everything in the kex_exchange_identification() function, and all code in the packet.c file. This option is intended for debugging and no overrides are enabled by default.`, + Value: docvalues.StringValue{}, + }, + "macs": { + Documentation: `Specifies the MAC (message authentication code) algorithms in order of preference. The MAC algorithm is used for data integrity protection. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified algorithms will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified algorithms will be placed at the head of the default set. + The algorithms that contain '-etm' calculate the MAC after encryption (encrypt-then-mac). These are considered safer and their use recommended. + The default is: + +umac-64-etm@openssh.com,umac-128-etm@openssh.com, +hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com, +hmac-sha1-etm@openssh.com, +umac-64@openssh.com,umac-128@openssh.com, +hmac-sha2-256,hmac-sha2-512,hmac-sha1 + + The list of available MAC algorithms may also be obtained using 'ssh -Q mac'.`, + Value: prefixPlusMinusCaret([]docvalues.EnumString{ + docvalues.CreateEnumString("hmac-md5"), + docvalues.CreateEnumString("hmac-md5-96"), + docvalues.CreateEnumString("hmac-sha1"), + docvalues.CreateEnumString("hmac-sha1-96"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-256"), + docvalues.CreateEnumString("hmac-sha2-512"), + docvalues.CreateEnumString("umac-64@openssh.com"), + docvalues.CreateEnumString("umac-128@openssh.com"), + docvalues.CreateEnumString("hmac-md5-etm@openssh.com"), + docvalues.CreateEnumString("hmac-md5-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha1-96-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-256-etm@openssh.com"), + docvalues.CreateEnumString("hmac-sha2-512-etm@openssh.com"), + docvalues.CreateEnumString("umac-64-etm@openssh.com"), + docvalues.CreateEnumString("umac-128-etm@openssh.com"), + }), + }, + "nohostauthenticationforlocalhost": { + Documentation: `Disable host authentication for localhost (loopback addresses). The argument to this keyword must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "numberofpasswordprompts": { + Documentation: `Specifies the number of password prompts before giving up. The argument to this keyword must be an integer. The default is 3.`, + Value: docvalues.PositiveNumberValue(), + }, + "obscurekeystroketiming": { + Documentation: `Specifies whether ssh(1) should try to obscure inter-keystroke timings from passive observers of network traffic. If enabled, then for interactive sessions, ssh(1) will send keystrokes at fixed intervals of a few tens of milliseconds and will send fake keystroke packets for some time after typing ceases. The argument to this keyword must be yes, no or an interval specifier of the form interval:milliseconds (e.g. interval:80 for 80 milliseconds). The default is to obscure keystrokes using a 20ms packet interval. Note that smaller intervals will result in higher fake keystroke packet rates.`, + Value: docvalues.OrValue{ + Values: []docvalues.DeprecatedValue{ + booleanEnumValue, + docvalues.RegexValue{ + Regex: *regexp.MustCompile(`^interval:[0-9]+$`), + }, + }, + }, + }, + "passwordauthentication": { + Documentation: `Specifies whether to use password authentication. The argument to this keyword must be yes (the default) or no.`, + Value: booleanEnumValue, + }, + "permitlocalcommand": { + Documentation: `Allow local command execution via the LocalCommand option or using the !command escape sequence in ssh(1). The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "permitremoteopen": { + Documentation: `Specifies the destinations to which remote TCP port forwarding is permitted when RemoteForward is used as a SOCKS proxy. The forwarding specification must be one of the following forms: + + PermitRemoteOpen host:port PermitRemoteOpen IPv4_addr:port PermitRemoteOpen [IPv6_addr]:port + + Multiple forwards may be specified by separating them with whitespace. An argument of any can be used to remove all restrictions and permit any forwarding requests. An argument of none can be used to prohibit all forwarding requests. The wildcard ‘*’ can be used for host or port to allow all hosts or ports respectively. Otherwise, no pattern matching or address lookups are performed on supplied names.`, + // TODO: Improve + Value: docvalues.StringValue{}, + }, + "pkcs11provider": { + Documentation: `Specifies which PKCS#11 provider to use or none to indicate that no provider should be used (the default). The argument to this keyword is a path to the PKCS#11 shared library ssh(1) should use to communicate with a PKCS#11 token providing keys for user authentication.`, + Value: booleanEnumValue, + }, + // TODO: Show warning + "port": { + Documentation: `Specifies the port number to connect on the remote host. The default is 22.`, + Value: docvalues.NumberValue{Min: &ZERO, Max: &MAX_PORT}, + }, + "preferredauthentications": { + Documentation: `Specifies the order in which the client should try authentication methods. This allows a client to prefer one method (e.g. keyboard-interactive) over another method (e.g. password). The default is: + +gssapi-with-mic,hostbased,publickey,keyboard-interactive,password`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("gssapi-with-mic"), + docvalues.CreateEnumString("hostbased"), + docvalues.CreateEnumString("publickey"), + docvalues.CreateEnumString("keyboard-interactive"), + docvalues.CreateEnumString("password"), + }, + }, + }, + "proxycommand": { + Documentation: `Specifies the command to use to connect to the server. The command string extends to the end of the line, and is executed using the user's shell ‘exec’ directive to avoid a lingering shell process. + Arguments to ProxyCommand accept the tokens described in the TOKENS section. The command can be basically anything, and should read from its standard input and write to its standard output. It should eventually connect an sshd(8) server running on some machine, or execute sshd + -i somewhere. Host key management will be done using the Hostname of the host being connected (defaulting to the name typed by the user). Setting the command to none disables this option entirely. Note that CheckHostIP is not available for connects with a proxy command. + This directive is useful in conjunction with nc(1) and its proxy support. For example, the following directive would connect via an HTTP proxy at 192.0.2.0: + + ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p`, + Value: docvalues.StringValue{}, + }, + "proxyjump": { + Documentation: `Specifies one or more jump proxies as either + [user@]host[:port] or an ssh URI. Multiple proxies may be separated by comma characters and will be visited sequentially. Setting this option will cause ssh(1) to connect to the target host by first making a ssh(1) connection to the specified ProxyJump host and then establishing a TCP forwarding to the ultimate target from there. Setting the host to none disables this option entirely. + Note that this option will compete with the ProxyCommand option - whichever is specified first will prevent later instances of the other from taking effect. + Note also that the configuration for the destination host + (either supplied via the command-line or the configuration file) is not generally applied to jump hosts. ~/.ssh/config should be used if specific configuration is required for jump hosts.`, + Value: docvalues.StringValue{}, + }, + "proxyusefdpass": { + Documentation: `Specifies that ProxyCommand will pass a connected file descriptor back to ssh(1) instead of continuing to execute and pass data. The default is no.`, + Value: booleanEnumValue, + }, + "pubkeyacceptedalgorithms": { + Documentation: `Specifies the signature algorithms that will be used for public key authentication as a comma-separated list of patterns. If the specified list begins with a ‘+’ character, then the algorithms after it will be appended to the default instead of replacing it. If the specified list begins with a ‘-’ character, then the specified algorithms (including wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a + ‘^’ character, then the specified algorithms will be placed at the head of the default set. The default for this option is: + +ssh-ed25519-cert-v01@openssh.com, +ecdsa-sha2-nistp256-cert-v01@openssh.com, +ecdsa-sha2-nistp384-cert-v01@openssh.com, +ecdsa-sha2-nistp521-cert-v01@openssh.com, +sk-ssh-ed25519-cert-v01@openssh.com, +sk-ecdsa-sha2-nistp256-cert-v01@openssh.com, +rsa-sha2-512-cert-v01@openssh.com, +rsa-sha2-256-cert-v01@openssh.com, +ssh-ed25519, +ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, +sk-ssh-ed25519@openssh.com, +sk-ecdsa-sha2-nistp256@openssh.com, +rsa-sha2-512,rsa-sha2-256 + + The list of available signature algorithms may also be obtained using 'ssh -Q PubkeyAcceptedAlgorithms'.`, + Value: docvalues.CustomValue{ + FetchValue: func(_ docvalues.CustomValueContext) docvalues.DeprecatedValue { + options, _ := ssh.QueryOpenSSHOptions("PubkeyAcceptedAlgorithms") + + return prefixPlusMinusCaret(options) + }, + }, + }, + "pubkeyauthentication": { + Documentation: `Specifies whether to try public key authentication. The argument to this keyword must be yes (the default), no, unbound or host-bound. The final two options enable public key authentication while respectively disabling or enabling the OpenSSH host-bound authentication protocol extension required for restricted ssh-agent(1) forwarding.`, + Value: booleanEnumValue, + }, + "rekeylimit": { + Documentation: `Specifies the maximum amount of data that may be transmitted or received before the session key is renegotiated, optionally followed by a maximum amount of time that may pass before the session key is renegotiated. The first argument is specified in bytes and may have a suffix of + ‘K’, ‘M’, or ‘G’ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between + ‘1G’ and ‘4G’, depending on the cipher. The optional second value is specified in seconds and may use any of the units documented in the TIME FORMATS section of sshd_config(5). The default value for RekeyLimit is default none, which means that rekeying is performed after the cipher's default amount of data has been sent or received and no time based rekeying is done.`, + Value: docvalues.KeyValueAssignmentValue{ + Separator: " ", + ValueIsOptional: true, + Key: docvalues.DataAmountValue{}, + Value: docvalues.TimeFormatValue{}, + }, + }, + "remotecommand": { + Documentation: `Specifies a command to execute on the remote machine after successfully connecting to the server. The command string extends to the end of the line, and is executed with the user's shell. Arguments to RemoteCommand accept the tokens described in the TOKENS section.`, + Value: docvalues.StringValue{}, + }, + "remoteforward": { + Documentation: `Specifies that a TCP port on the remote machine be forwarded over the secure channel. The remote port may either be forwarded to a specified host and port from the local machine, or may act as a SOCKS 4/5 proxy that allows a remote client to connect to arbitrary destinations from the local machine. The first argument is the listening specification and may be + [bind_address:]port or, if the remote host supports it, a Unix domain socket path. If forwarding to a specific destination then the second argument must be host:hostport or a Unix domain socket path, otherwise if no destination argument is specified then the remote forwarding will be established as a SOCKS proxy. When acting as a SOCKS proxy, the destination of the connection can be restricted by PermitRemoteOpen. + IPv6 addresses can be specified by enclosing addresses in square brackets. Multiple forwardings may be specified, and additional forwardings can be given on the command line. Privileged ports can be forwarded only when logging in as root on the remote machine. Unix domain socket paths may use the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. + If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. + If the bind_address is not specified, the default is to only bind to loopback addresses. If the bind_address is + ‘*’ or an empty string, then the forwarding is requested to listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).`, + Value: docvalues.StringValue{}, + }, + "requesttty": { + Documentation: `Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and -T flags for ssh(1).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("force"), + docvalues.CreateEnumString("auto"), + }, + }, + }, + "requiredrsasize": { + Documentation: `Specifies the minimum RSA key size (in bits) that ssh(1) will accept. User authentication keys smaller than this limit will be ignored. Servers that present host keys smaller than this limit will cause the connection to be terminated. The default is 1024 bits. Note that this limit may only be raised from the default.`, + Value: docvalues.PositiveNumberValue(), + }, + "revokedhostkeys": { + Documentation: `Specifies revoked host public keys. Keys listed in this file will be refused for host authentication. Note that if this file does not exist or is not readable, then host authentication will be refused for all hosts. Keys may be specified as a text file, listing one public key per line, or as an OpenSSH Key Revocation List (KRL) as generated by ssh-keygen(1). For more information on KRLs, see the KEY REVOCATION LISTS section in ssh-keygen(1). Arguments to RevokedHostKeys may use the tilde syntax to refer to a user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section.`, + Value: docvalues.StringValue{}, + }, + "securitykeyprovider": { + Documentation: `Specifies a path to a library that will be used when loading any FIDO authenticator-hosted keys, overriding the default of using the built-in USB HID support. + If the specified value begins with a ‘$’ character, then it will be treated as an environment variable containing the path to the library.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + "sendenv": { + Documentation: `Specifies what variables from the local environ(7) should be sent to the server. The server must also support it, and the server must be configured to accept these environment variables. Note that the TERM environment variable is always sent whenever a pseudo-terminal is requested as it is required by the protocol. Refer to AcceptEnv in sshd_config(5) for how to configure the server. Variables are specified by name, which may contain wildcard characters. Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives. + See PATTERNS for more information on patterns. + It is possible to clear previously set SendEnv variable names by prefixing patterns with -. The default is not to send any environment variables.`, + Value: docvalues.StringValue{}, + }, + "serveralivecountmax": { + Documentation: `Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive (below). The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become unresponsive. + The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds.`, + Value: docvalues.PositiveNumberValue(), + }, + "serveraliveinterval": { + Documentation: `Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server.`, + Value: docvalues.PositiveNumberValue(), + }, + "sessiontype": { + Documentation: `May be used to either request invocation of a subsystem on the remote system, or to prevent the execution of a remote command at all. The latter is useful for just forwarding ports. The argument to this keyword must be none (same as the -N option), subsystem (same as the -s option) or default (shell or command execution).`, + Value: docvalues.StringValue{}, + }, + "setenv": { + Documentation: `Directly specify one or more environment variables and their contents to be sent to the server. Similarly to SendEnv, with the exception of the TERM variable, the server must be prepared to accept the environment variable.`, + Value: docvalues.StringValue{}, + }, + "stdinnull": { + Documentation: `Redirects stdin from /dev/null (actually, prevents reading from stdin). Either this or the equivalent -n option must be used when ssh is run in the background. The argument to this keyword must be yes (same as the -n option) or no (the default).`, + Value: booleanEnumValue, + }, + "streamlocalbindmask": { + Documentation: `Sets the octal file creation mode mask (umask) used when creating a Unix-domain socket file for local or remote port forwarding. This option is only used for port forwarding to a Unix-domain socket file. + The default value is 0177, which creates a Unix-domain socket file that is readable and writable only by the owner. Note that not all operating systems honor the file mode on Unix-domain socket files.`, + Value: docvalues.MaskValue(), + }, + "streamlocalbindunlink": { + Documentation: `Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new one. If the socket file already exists and StreamLocalBindUnlink is not enabled, ssh will be unable to forward the port to the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file. + The argument must be yes or no (the default).`, + Value: booleanEnumValue, + }, + "stricthostkeychecking": { + Documentation: `If this flag is set to yes, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against man-in-the-middle (MITM) attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. + If this flag is set to accept-new then ssh will automatically add new host keys to the user's known_hosts file, but will not permit connections to hosts with changed host keys. If this flag is set to no or off, ssh will automatically add new host keys to the user known hosts files and allow connections to hosts with changed hostkeys to proceed, subject to some restrictions. If this flag is set to ask (the default), new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("accept-new"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("off"), + docvalues.CreateEnumString("ask"), + }, + }, + }, + "syslogfacility": { + Documentation: `Gives the facility code that is used when logging messages from ssh(1). The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is USER.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("DAEMON"), + docvalues.CreateEnumString("USER"), + docvalues.CreateEnumString("AUTH"), + docvalues.CreateEnumString("LOCAL0"), + docvalues.CreateEnumString("LOCAL1"), + docvalues.CreateEnumString("LOCAL2"), + docvalues.CreateEnumString("LOCAL3"), + docvalues.CreateEnumString("LOCAL4"), + docvalues.CreateEnumString("LOCAL5"), + docvalues.CreateEnumString("LOCAL6"), + docvalues.CreateEnumString("LOCAL7"), + }, + }, + }, + "tcpkeepalive": { + Documentation: `Specifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. However, this means that connections will die if the route is down temporarily, and some people find it annoying. + The default is yes (to send TCP keepalive messages), and the client will notice if the network goes down or the remote host dies. This is important in scripts, and many users want it too. + To disable TCP keepalive messages, the value should be set to no. See also ServerAliveInterval for protocol-level keepalives.`, + Value: booleanEnumValue, + }, + "tag": { + Documentation: `Specify a configuration tag name that may be later used by a Match directive to select a block of configuration.`, + Value: docvalues.StringValue{}, + }, + "tunnel": { + Documentation: `Request tun(4) device forwarding between the client and the server. The argument must be yes, point-to-point (layer 3), ethernet (layer 2), or no (the default). Specifying yes requests the default tunnel mode, which is point-to-point.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("point-to-point"), + docvalues.CreateEnumString("ethernet"), + docvalues.CreateEnumString("no"), + }, + }, + }, + "tunneldevice": { + Documentation: `Specifies the tun(4) devices to open on the client (local_tun) and the server (remote_tun). + The argument must be local_tun[:remote_tun]. The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. The default is any:any.`, + Value: docvalues.StringValue{}, + }, + "updatehostkeys": { + Documentation: `Specifies whether ssh(1) should accept notifications of additional hostkeys from the server sent after authentication has completed and add them to UserKnownHostsFile. The argument must be yes, no or ask. This option allows learning alternate hostkeys for a server and supports graceful key rotation by allowing a server to send replacement public keys before old ones are removed. + Additional hostkeys are only accepted if the key used to authenticate the host was already trusted or explicitly accepted by the user, the host was authenticated via UserKnownHostsFile (i.e. not GlobalKnownHostsFile) and the host was authenticated using a plain key and not a certificate. + UpdateHostKeys is enabled by default if the user has not overridden the default UserKnownHostsFile setting and has not enabled VerifyHostKeyDNS, otherwise UpdateHostKeys will be set to no. + If UpdateHostKeys is set to ask, then the user is asked to confirm the modifications to the known_hosts file. Confirmation is currently incompatible with ControlPersist, and will be disabled if it is enabled. + Presently, only sshd(8) from OpenSSH 6.8 and greater support the + 'hostkeys@openssh.com' protocol extension used to inform the client of all the server's hostkeys.`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + }, + }, + }, + "user": { + Documentation: `Specifies the user to log in as. This can be useful when a different user name is used on different machines. This saves the trouble of having to remember to give the user name on the command line.`, + Value: docvalues.UserValue("", false), + }, + "userknownhostsfile": { + Documentation: `Specifies one or more files to use for the user host key database, separated by whitespace. Each filename may use tilde notation to refer to the user's home directory, the tokens described in the TOKENS section and environment variables as described in the ENVIRONMENT VARIABLES section. A value of none causes ssh(1) to ignore any user-specific known hosts files. The default is + ~/.ssh/known_hosts, + ~/.ssh/known_hosts2.`, + Value: docvalues.ArrayValue{ + Separator: " ", + SubValue: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, + }, + "verifyhostkeydns": { + Documentation: `Specifies whether to verify the remote key using DNS and SSHFP resource records. If this option is set to yes, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to ask. If this option is set to ask, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option. The default is no. + See also VERIFYING HOST KEYS in ssh(1).`, + Value: docvalues.EnumValue{ + EnforceValues: true, + Values: []docvalues.EnumString{ + docvalues.CreateEnumString("yes"), + docvalues.CreateEnumString("no"), + docvalues.CreateEnumString("ask"), + }, + }, + }, + "visualhostkey": { + Documentation: `If this flag is set to yes, an ASCII art representation of the remote host key fingerprint is printed in addition to the fingerprint string at login and for unknown host keys. If this flag is set to no (the default), no fingerprint strings are printed at login and only the fingerprint string will be printed for unknown host keys.`, + Value: booleanEnumValue, + }, + "xauthlocation": { + Documentation: `Specifies the full pathname of the xauth(1) program. The default is /usr/X11R6/bin/xauth.`, + Value: docvalues.PathValue{ + RequiredType: docvalues.PathTypeFile, + }, + }, +} diff --git a/server/handlers/ssh_config/fields/fields_formatted.go b/server/handlers/ssh_config/fields/fields_formatted.go new file mode 100644 index 0000000..b09147a --- /dev/null +++ b/server/handlers/ssh_config/fields/fields_formatted.go @@ -0,0 +1,106 @@ +// Contains the recommended formatting for each field +package fields + +var FieldsNameFormattedMap = map[NormalizedOptionName]string{ + "host": "Host", + "match": "Match", + "addkeystoagent": "AddKeysToAgent", + "addressfamily": "AddressFamily", + "batchmode": "BatchMode", + "bindaddress": "BindAddress", + "bindinterface": "BindInterface", + "canonicaldomains": "CanonicalDomains", + "canonicalizefallbacklocal": "CanonicalizeFallbackLocal", + "canonicalizehostname": "CanonicalizeHostname", + "canonicalizemaxdots": "CanonicalizeMaxDots", + "canonicalizepermittedcnames": "CanonicalizePermittedCNAMEs", + "casignaturealgorithms": "CASignatureAlgorithms", + "certificatefile": "CertificateFile", + "channeltimeout": "ChannelTimeout", + "checkhostip": "CheckHostIP", + "ciphers": "Ciphers", + "clearallforwardings": "ClearAllForwardings", + "compression": "Compression", + "connectionattempts": "ConnectionAttempts", + "connecttimeout": "ConnectTimeout", + "controlmaster": "ControlMaster", + "controlpath": "ControlPath", + "controlpersist": "ControlPersist", + "dynamicforward": "DynamicForward", + "enableescapecommandline": "EnableEscapeCommandline", + "enablesshkeysign": "EnableSSHKeysign", + "escapechar": "EscapeChar", + "exitonforwardfailure": "ExitOnForwardFailure", + "fingerprinthash": "FingerprintHash", + "forkafterauthentication": "ForkAfterAuthentication", + "forwardagent": "ForwardAgent", + "forwardx11": "ForwardX11", + "forwardx11timeout": "ForwardX11Timeout", + "forwardx11trusted": "ForwardX11Trusted", + "gatewayports": "GatewayPorts", + "globalknownhostsfile": "GlobalKnownHostsFile", + "gssapiauthentication": "GSSAPIAuthentication", + "gssapidelegatecredentials": "GSSAPIDelegateCredentials", + "hashknownhosts": "HashKnownHosts", + "hostbasedacceptedalgorithms": "HostbasedAcceptedAlgorithms", + "hostbasedauthentication": "HostbasedAuthentication", + "hostkeyalgorithms": "HostKeyAlgorithms", + "hostkeyalias": "HostKeyAlias", + "hostname": "Hostname", + "identitiesonly": "IdentitiesOnly", + "identityagent": "IdentityAgent", + "identityfile": "IdentityFile", + "ignoreunknown": "IgnoreUnknown", + "include": "Include", + "ipqos": "IPQoS", + "kbdinteractiveauthentication": "KbdInteractiveAuthentication", + "kbdinteractivedevices": "KbdInteractiveDevices", + "kexalgorithms": "KexAlgorithms", + "knownhostscommand": "KnownHostsCommand", + "localcommand": "LocalCommand", + "localforward": "LocalForward", + "loglevel": "LogLevel", + "logverbose": "LogVerbose", + "macs": "MACs", + "nohostauthenticationforlocalhost": "NoHostAuthenticationForLocalhost", + "numberofpasswordprompts": "NumberOfPasswordPrompts", + "obscurekeystroketiming": "ObscureKeystrokeTiming", + "passwordauthentication": "PasswordAuthentication", + "permitlocalcommand": "PermitLocalCommand", + "permitremoteopen": "PermitRemoteOpen", + "pkcs11provider": "PKCS11Provider", + "port": "Port", + "preferredauthentications": "PreferredAuthentications", + "proxycommand": "ProxyCommand", + "proxyjump": "ProxyJump", + "proxyusefdpass": "ProxyUseFdpass", + "pubkeyacceptedalgorithms": "PubkeyAcceptedAlgorithms", + "pubkeyauthentication": "PubkeyAuthentication", + "rekeylimit": "RekeyLimit", + "remotecommand": "RemoteCommand", + "remoteforward": "RemoteForward", + "requesttty": "RequestTTY", + "requiredrsasize": "RequiredRSASize", + "revokedhostkeys": "RevokedHostKeys", + "securitykeyprovider": "SecurityKeyProvider", + "sendenv": "SendEnv", + "serveralivecountmax": "ServerAliveCountMax", + "serveraliveinterval": "ServerAliveInterval", + "sessiontype": "SessionType", + "setenv": "SetEnv", + "stdinnull": "StdinNull", + "streamlocalbindmask": "StreamLocalBindMask", + "streamlocalbindunlink": "StreamLocalBindUnlink", + "stricthostkeychecking": "StrictHostKeyChecking", + "syslogfacility": "SyslogFacility", + "tcpkeepalive": "TCPKeepAlive", + "tag": "Tag", + "tunnel": "Tunnel", + "tunneldevice": "TunnelDevice", + "updatehostkeys": "UpdateHostKeys", + "user": "User", + "userknownhostsfile": "UserKnownHostsFile", + "verifyhostkeydns": "VerifyHostKeyDNS", + "visualhostkey": "VisualHostKey", + "xauthlocation": "XAuthLocation", +} diff --git a/server/handlers/ssh_config/fields/match.go b/server/handlers/ssh_config/fields/match.go new file mode 100644 index 0000000..8803e85 --- /dev/null +++ b/server/handlers/ssh_config/fields/match.go @@ -0,0 +1,39 @@ +package fields + +import ( + docvalues "config-lsp/doc-values" + matchparser "config-lsp/handlers/ssh_config/match-parser" +) + +var MatchExecField = docvalues.StringValue{} +var MatchLocalNetworkField = docvalues.IPAddressValue{ + AllowIPv4: true, + AllowIPv6: true, + AllowRange: false, +} +var MatchHostField = docvalues.StringValue{} +var MatchOriginalHostField = docvalues.StringValue{} +var MatchTypeTaggedField = docvalues.StringValue{} +var MatchUserField = docvalues.UserValue("", false) +var MatchTypeLocalUserField = docvalues.UserValue("", false) + +var MatchValueFieldMap = map[matchparser.MatchCriteriaType]docvalues.DeprecatedValue{ + matchparser.MatchCriteriaTypeExec: MatchExecField, + matchparser.MatchCriteriaTypeLocalNetwork: MatchLocalNetworkField, + matchparser.MatchCriteriaTypeHost: MatchHostField, + matchparser.MatchCriteriaTypeOriginalHost: MatchOriginalHostField, + matchparser.MatchCriteriaTypeTagged: MatchTypeTaggedField, + matchparser.MatchCriteriaTypeUser: MatchUserField, + matchparser.MatchCriteriaTypeLocalUser: MatchTypeLocalUserField, +} + +var MatchAllArgumentAllowedPreviousOptions = map[matchparser.MatchCriteriaType]struct{}{ + matchparser.MatchCriteriaTypeCanonical: {}, + matchparser.MatchCriteriaTypeFinal: {}, +} + +var MatchSingleOptionCriterias = map[matchparser.MatchCriteriaType]struct{}{ + matchparser.MatchCriteriaTypeAll: {}, + matchparser.MatchCriteriaTypeCanonical: {}, + matchparser.MatchCriteriaTypeFinal: {}, +} diff --git a/server/handlers/ssh_config/fields/options.go b/server/handlers/ssh_config/fields/options.go new file mode 100644 index 0000000..ccf83b2 --- /dev/null +++ b/server/handlers/ssh_config/fields/options.go @@ -0,0 +1,20 @@ +package fields + +var AllowedDuplicateOptions = map[NormalizedOptionName]struct{}{ + "certificatefile": {}, + "match": {}, + "host": {}, +} + +// A list of +//