Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Misc Toolshed tweaks #4990

Merged
merged 7 commits into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion RELEASE-NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@ END TEMPLATE-->
* IoC now contains an `IMeterFactory` implementation that you can use to instantiate metric meters.
* `net.mtu_ipv6` CVar allows specifying a different MTU value for IPv6.
* Allows `player:entity` to take a parameter representing the player name.
* Added an `ICommonSession` parser for toolshed commands.

### Bugfixes

*None yet*
* Fixed some issues where toolshed commands were generating completions for the wrong arguments

### Other

Expand Down
1 change: 1 addition & 0 deletions Resources/Locale/en-US/commands.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ cmd-parse-failure-uid = {$arg} is not a valid entity UID.
cmd-parse-failure-mapid = {$arg} is not a valid MapId.
cmd-parse-failure-grid = {$arg} is not a valid grid.
cmd-parse-failure-entity-exist = UID {$arg} does not correspond to an existing entity.
cmd-parse-failure-session = There is no session with username: {$username}

cmd-error-file-not-found = Could not find file: {$file}.
cmd-error-dir-not-found = Could not find directory: {$dir}.
Expand Down
4 changes: 4 additions & 0 deletions Robust.Shared/Toolshed/Syntax/Expression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ public static bool TryParse(bool doAutocomplete,

if (parserContext.EatTerminator())
break;

// Prevent auto completions from dumping a list of all commands at the end of any complete command.
if (parserContext.Index == parserContext.MaxIndex + 1)
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
break;
}

if (error is OutOfInputError && noCommand)
Expand Down
2 changes: 1 addition & 1 deletion Robust.Shared/Toolshed/ToolshedCommand.Entities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected bool HasComp<T>(EntityUid entityUid)
/// A shorthand for attempting to retrieve the given component for an entity.
/// </summary>
[PublicAPI, MethodImpl(MethodImplOptions.AggressiveInlining)]
protected bool TryComp<T>(EntityUid? entity, [NotNullWhen(true)] out T? component)
protected bool TryComp<T>([NotNullWhen(true)] EntityUid? entity, [NotNullWhen(true)] out T? component)
where T: IComponent
=> EntityManager.TryGetComponent(entity, out component);

Expand Down
57 changes: 14 additions & 43 deletions Robust.Shared/Toolshed/ToolshedCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Reflection;
using Robust.Shared.Toolshed.Errors;
using Robust.Shared.Toolshed.Syntax;
Expand Down Expand Up @@ -47,6 +48,7 @@ namespace Robust.Shared.Toolshed;
public abstract partial class ToolshedCommand
{
[Dependency] protected readonly ToolshedManager Toolshed = default!;
[Dependency] protected readonly ILocalizationManager Loc = default!;

/// <summary>
/// The user-facing name of the command.
Expand Down Expand Up @@ -98,46 +100,18 @@ protected ToolshedCommand()
SubCommand = null
};

var impls = GetGenericImplementations();
Dictionary<string, SortedDictionary<string, Type>> parameters = new();

foreach (var impl in impls)
foreach (var impl in GetGenericImplementations())
{
var myParams = new SortedDictionary<string, Type>();
string? subCmd = null;
if (impl.GetCustomAttribute<CommandImplementationAttribute>() is {SubCommand: { } x})
{
subCmd = x;
HasSubCommands = true;
_implementors[x] =
new ToolshedCommandImplementor
{
Owner = this,
SubCommand = x
};
}

foreach (var param in impl.GetParameters())
{
if (param.GetCustomAttribute<CommandArgumentAttribute>() is not null)
{
if (parameters.ContainsKey(param.Name!))
continue;
if (impl.GetCustomAttribute<CommandImplementationAttribute>() is not {SubCommand: { } x})
continue;

myParams.Add(param.Name!, param.ParameterType);
}
}

if (parameters.TryGetValue(subCmd ?? "", out var existing))
{
if (!existing.SequenceEqual(existing))
Copy link
Member Author

@ElectroJr ElectroJr Mar 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was previously bugged because existing.SequenceEqual(existing) is always true. After I fixed it, many commands started erroring so I though the feature was implemented, but I misunderstood it.

If I understand correctly now, it works as long as the (sub)command name & piped type are unique, so I changed the parameters dictionary key to a (string, Type?) tuple

HasSubCommands = true;
_implementors[x] =
new ToolshedCommandImplementor
{
throw new NotImplementedException("All command implementations of a given subcommand must share the same parameters!");
}
}
else
parameters.Add(subCmd ?? "", myParams);

Owner = this,
SubCommand = x
};
}
}

Expand Down Expand Up @@ -184,14 +158,11 @@ internal sealed class CommandArgumentBundle
public required Type[] TypeArguments;
}

internal readonly record struct CommandDiscriminator(Type? PipedType, Type[] TypeArguments) : IEquatable<CommandDiscriminator?>
internal readonly record struct CommandDiscriminator(Type? PipedType, Type[] TypeArguments)
{
public bool Equals(CommandDiscriminator? other)
public bool Equals(CommandDiscriminator other)
{
if (other is not {} value)
return false;

return value.PipedType == PipedType && value.TypeArguments.SequenceEqual(TypeArguments);
return other.PipedType == PipedType && other.TypeArguments.SequenceEqual(TypeArguments);
}

public override int GetHashCode()
Expand Down
17 changes: 14 additions & 3 deletions Robust.Shared/Toolshed/ToolshedCommandImplementor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public bool TryParseArguments(
return false;
}

autocomplete = null;
args = new();
foreach (var argument in impl.ConsoleGetArguments())
{
Expand All @@ -124,19 +125,29 @@ public bool TryParseArguments(
{
error?.Contextualize(parserContext.Input, (start, parserContext.Index));
args = null;
autocomplete = null;
if (doAutocomplete)

// Only generate auto-completions if the parsing error happened for the last argument.
if (doAutocomplete && parserContext.Index == parserContext.MaxIndex + 1)
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
{
parserContext.Restore(chkpoint);
autocomplete = _toolshedManager.TryAutocomplete(parserContext, argument.ParameterType, null);
}
return false;
}
args[argument.Name!] = parsed;

if (!doAutocomplete || parserContext.Index != parserContext.MaxIndex + 1)
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
continue;

// This was the end of the input, so we want to get completions for the current argument, not the next argument.
doAutocomplete = false;
var chkpoint2 = parserContext.Save();
parserContext.Restore(chkpoint);
autocomplete = _toolshedManager.TryAutocomplete(parserContext, argument.ParameterType, null);
parserContext.Restore(chkpoint2);
}

error = null;
autocomplete = null;
return true;
}

Expand Down
1 change: 0 additions & 1 deletion Robust.Shared/Toolshed/TypeParsers/EntityTypeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Threading.Tasks;
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Toolshed.Errors;
using Robust.Shared.Toolshed.Syntax;
Expand Down
2 changes: 2 additions & 0 deletions Robust.Shared/Toolshed/TypeParsers/PrototypeTypeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public override bool TryParse(ParserContext parserContext, [NotNullWhen(true)] o
public readonly record struct Prototype<T>(T Value) : IAsType<string>
where T : class, IPrototype
{
public ProtoId<T> Id => Value.ID;

public string AsType()
{
return Value.ID;
Expand Down
63 changes: 63 additions & 0 deletions Robust.Shared/Toolshed/TypeParsers/SessionTypeParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Player;
using Robust.Shared.Toolshed.Errors;
using Robust.Shared.Toolshed.Syntax;
using Robust.Shared.Utility;

namespace Robust.Shared.Toolshed.TypeParsers;

/// <summary>
/// Parse a username to an <see cref="ICommonSession"/>
/// </summary>
internal sealed class SessionTypeParser : TypeParser<ICommonSession>
{
[Dependency] private ISharedPlayerManager _player = default!;

public override bool TryParse(ParserContext parser, [NotNullWhen(true)] out object? result, out IConError? error)
{
var start = parser.Index;
var word = parser.GetWord();
error = null;
result = null;

if (word == null)
{
error = new OutOfInputError();
return false;
}

if (_player.TryGetSessionByUsername(word, out var session))
{
result = session;
return true;
}

error = new InvalidUsername(Loc.GetString("cmd-parse-failure-session", ("username", word)));
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
error.Contextualize(parser.Input, (start, parser.Index));
return false;
}

public override async ValueTask<(CompletionResult? result, IConError? error)> TryAutocomplete(ParserContext parserContext,
string? argName)
{
var opts = CompletionHelper.SessionNames(true, _player);
return (CompletionResult.FromHintOptions(opts, "<Session>"), null);
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
}

public record InvalidUsername(string msg) : IConError
{
public FormattedMessage DescribeInner()
{
return FormattedMessage.FromMarkup(msg);
}

public string? Expression { get; set; }
public Vector2i? IssueSpan { get; set; }
public StackTrace? Trace { get; set; }
}
}
6 changes: 4 additions & 2 deletions Robust.Shared/Toolshed/TypeParsers/TypeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using JetBrains.Annotations;
using Robust.Shared.Console;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Toolshed.Errors;
using Robust.Shared.Toolshed.Syntax;
Expand All @@ -26,8 +27,9 @@ public abstract class TypeParser<T> : ITypeParser
where T: notnull
{
[Dependency] private readonly ILogManager _log = default!;
[Dependency] protected readonly ILocalizationManager Loc = default!;

protected ISawmill _sawmill = default!;
protected ISawmill Log = default!;

public virtual Type Parses => typeof(T);

Expand All @@ -37,6 +39,6 @@ public abstract class TypeParser<T> : ITypeParser

public virtual void PostInject()
{
_sawmill = _log.GetSawmill(GetType().PrettyName());
Log = _log.GetSawmill(GetType().PrettyName());
}
}
Loading