1
0
mirror of https://github.com/SquidDev-CC/CC-Tweaked synced 2025-10-17 06:57:38 +00:00

Compare commits

..

38 Commits

Author SHA1 Message Date
Jonathan Coates
9e6e0c8b88 Bump CC:T to 1.103.0 2023-02-09 21:02:09 +00:00
Jonathan Coates
5502412181 Improve display of runtime errors (#1320)
- Bump Cobalt to 0.6.0. We now track both line and column numbers of
   each bytecode instruction, allowing us to map an error to a concrete
   position.

 - `loadfile` (and similar functions) now use the full path, rather than
   the file name. Cobalt truncates this to 30 characters (rather than
   the previous 60) so this should be less noisy.

 - The shell, edit and Lua REPL now display the corresponding source
   code alongside an error.

   Note this is incredibly limited right now - it won't cope with errors
   which cross coroutine boundaries. Supporting this is on the roadmap,
   but requires some careful API design.
2023-02-09 20:53:50 +00:00
Jonathan Coates
62e3c5f9aa Queue key presses for a short period after pressing a computer shortcut
Fixes #1326
2023-02-09 20:10:20 +00:00
Jonathan Coates
7e54a40fa9 Add a couple of missing version annotations 2023-02-09 20:09:57 +00:00
Jonathan Coates
8ac42566ec Be a little more robust in turtle item rendering
See #1328. Also some holiday cleanup, because my commit discipline is
terrible.
2023-02-09 20:07:55 +00:00
Jonathan Coates
66b20d2bdb Don't dye/undye turtles when right clicked
While it's a nice immersive interaction, it's far too easy to trigger by
accident. Dying/undying can now only be done via crafting and the
cauldron.

Closes #1321
2023-02-08 20:14:07 +00:00
Jonathan Coates
81dad421d5 Allow undying items using a sponge
It's much less aggressive than dunking it in a cauldron, so won't damage
any of your precious electronics.

I had this idea back in 2017 (dan200/ComputerCraft#230). Can't believe
it took me almost 6 years to implement.
2023-02-08 20:13:58 +00:00
Jonathan Coates
3075d3cea8 Fxi teh spolling of handshakder 2023-02-07 20:59:45 +00:00
Jonathan Coates
cdab8f429e Clarify Minecraft' shift+right click behaviour
Closes #1323
2023-02-07 08:45:17 +00:00
Jonathan Coates
2e5cd29e12 Use tags to what items turtle.place() can .use()
In older versions we just used a hard-coded list of items and
superclasses. This was somewhat ugly, and so in 1.19.3 I tried to make
this code more generic.

However, this has a lot of unintended consequences - for instance
turtles can now throw ender pearls, which is definitely not intended!

By using a tag, we can emulate the old behaviour, while still allowing
modders and pack devs to add additional items if needed.
2023-02-04 18:14:18 +00:00
Jonathan Coates
22cadd6730 Various improvements to our Lua parser
- Encode the DFA as a virtual machine (identical to lrgrep) rather than
   compiling it to a series of Lua functions. While this is a little
   slower and uglier, it's much more space efficient, shaving off 16Kb.

 - Minimise the DFA properly. This only shaves off a few states, but
   every little helps.

 - Run the error handling code from a non-reduced parser stack. This was
   incredibly nasty to get right (and positions are still not correctly
   handled), but it fixes several broken error messages.
2023-02-04 12:46:51 +00:00
Jonathan Coates
366052ec48 Merge pull request #1316 from LelouBil/patch-1
Fix word error in rednet documentation
2023-02-03 19:39:13 +00:00
Jonathan Coates
3224e0bf8b Fix a few typos in the documentation
- Move modem recipes out of the usage section.
 - Add missing argument names to BinaryWriableHandle.write. Illuaminate
   really should catch this, but for now I did a grep and couldn't find
   any more instances of this.
2023-02-03 19:29:16 +00:00
Weblate
fb4b097a66 Translations for Toki Pona
Co-authored-by: wackbyte <wackbyte@protonmail.com>
2023-02-03 04:55:48 +00:00
Bilel MEDIMEGH
67f3d91850 Fix word error in rednet documentation
Replaced "The name this protocol exposes for the given protocol" into "The name this **computer** exposes for the given protocol"
2023-01-30 18:19:06 +01:00
Jonathan Coates
1e3a930543 Copy pocket upgrades items before dropping them
We were modifying the stack, meaning the crafting item would end up
empty!
2023-01-26 22:40:03 +00:00
Jonathan Coates
b21e2f4e63 Update Cobalt to fix yielding inside __len
Closes #1307
2023-01-26 09:43:10 +00:00
Jonathan Coates
a12b405acf Custom parse errors for Lua (#1298)
- Add several (internal) modules for lexing and parsing Lua code. These
   allow us to provide (hopefully) higher quality error messages than
   Lua's built-in messages.

 - `shell.run`, `edit` and `lua` now use this parser when fed invalid
   code. This allows us to provide better syntax errors, while not
   having any impact on the happy path.

   Note this does not affect any other mechanism for loading code 
   (`load`, `require`, `dofile`).

There's still a lot of work to do here in improving error message
quality, but hopefully this provides a good starting point.
2023-01-25 20:35:43 +00:00
Jonathan Coates
e076818b29 Bump Cobalt for even more verbose VM logging
See #1307
2023-01-25 18:47:27 +00:00
Jonathan Coates
1554c7b397 Always expose nbt from turtle.getItemDetail
- Document the thread safety of DetailRegistry a little better.

 - Turtles now duplicate their inventory to the "previous
   inventory" (now called inventorySnapshot) immediately, rather than
   when the block is ticked.

   This is slightly more resource intensive, but I don't think it's so
   bad we need to worry.

 - As this snapshot is now always up-to-date, we can read it from the
   computer thread. Given the item is immutable, it's safe to read NBT
   from it.

   _Technically_ this is not safe under the Java memory model, but in
   practice I don't think we'll observe the wrong value.

Closes #1306
2023-01-25 18:37:14 +00:00
Jonathan Coates
6cd32a6368 Fix a few typos
Just ran[^1] over the codebase. Turns out we'd duplicated one of the
changelog entries entirely - I suspect due to a version merge gone
wrong!

[^1]: https://github.com/crate-ci/typos/
2023-01-24 18:47:29 +00:00
Jonathan Coates
7335a892b5 Expose test methods to required libraries
This allows us to use stub everywhere, rather than having to pass it
around as an argument.
2023-01-24 18:27:30 +00:00
Weblate
83eddc6636 Translations for Toki Pona
Translations for Italian

Co-authored-by: Alessandro <ale.proto00@gmail.com>
Co-authored-by: wackbyte <wackbyte@protonmail.com>
2023-01-24 05:55:48 +00:00
Jonathan Coates
d066d175bf Attach a speaker peripheral inside its docs
This required a version bump to cct-javadoc to allow using attributes
inside <pre> blocks.
2023-01-22 12:24:36 +00:00
Jonathan Coates
9873ccfa0d Send the original rednet message to the current computer
We were incorrectly enquing the modem payload, not the underlying rednet
message.

Closes #1308.
2023-01-21 08:23:00 +00:00
Weblate
da7a50368d Added translation for Toki Pona
Co-authored-by: wackbyte <wackbyte@protonmail.com>
2023-01-18 14:59:35 +00:00
Jonathan Coates
8cfbfe7ceb Make errors messages in edit more obvious
See #1222.
2023-01-17 21:43:26 +00:00
ouroborus
67244b17af Update event docs (#1304) 2023-01-17 21:17:47 +00:00
Jonathan Coates
9e1de23f4a Log internal Cobalt VM errors
See #1307
2023-01-17 20:37:16 +00:00
Jonathan Coates
86b60855d6 Enforce version bounds for the Kotlin stdlib
We were pulling in an ancient version of the jdk8 stdlib via
kotlinx.coroutines, hence the conflict in versions.
2023-01-17 20:28:31 +00:00
Jonathan Coates
db6b6fd173 Bump Kotlin version to 1.8 2023-01-17 19:33:49 +00:00
Jonathan Coates
2014e9527e Some event typo fixes 2023-01-16 22:53:58 +00:00
Emma
f43b839056 Add support for shebangs (#1273) 2023-01-14 22:12:04 +00:00
Jonathan Coates
f561572509 Bump CC:T to 1.102.2 2023-01-14 20:07:01 +00:00
Jonathan Coates
edb21f33be Mount drives on the main thread
When the peripheral is attached, we add the computer to the map and
queue the actual disk to be mounted next tick. This avoids the
thread-safety issues with mutating the item (and creating disk ids) that
might be caused by doing it on the computer thread.

The mount is now also managed separately to the MediaStack, as that was
meant to be an immutable snapshot of the item!

Fixes #1282
2023-01-14 17:51:49 +00:00
Jonathan Coates
02b68b259e Correctly track coverage for startup.lua too 2023-01-12 22:26:39 +00:00
Jonathan Coates
28a55349a9 Move coverage to the Java side
While slightly irritating (requires Cobalt magic), it's much, much
faster.
2023-01-12 21:02:33 +00:00
Jonathan Coates
2457a31728 Fix printouts crashing in item frames 2023-01-09 18:28:44 +00:00
157 changed files with 5821 additions and 801 deletions

View File

@@ -34,7 +34,7 @@ abstract class CheckChangelog : DefaultTask() {
var ok = true
// Check we're targetting the current version
// Check we're targeting the current version
var whatsNew = whatsNew.get().asFile.readLines()
if (whatsNew[0] != "New features in CC: Tweaked $version") {
ok = false

View File

@@ -3,19 +3,20 @@ module: [kind=event] alarm
see: os.setAlarm To start an alarm.
---
The @{timer} event is fired when an alarm started with @{os.setAlarm} completes.
The @{alarm} event is fired when an alarm started with @{os.setAlarm} completes.
## Return Values
1. @{string}: The event name.
2. @{number}: The ID of the alarm that finished.
## Example
Starts a timer and then prints its ID:
Starts a timer and then waits for it to complete.
```lua
local alarmID = os.setAlarm(os.time() + 0.05)
local alarm_id = os.setAlarm(os.time() + 0.05)
local event, id
repeat
event, id = os.pullEvent("alarm")
until id == alarmID
until id == alarm_id
print("Alarm with ID " .. id .. " was fired")
```

View File

@@ -3,7 +3,7 @@ module: [kind=event] char
see: key To listen to any key press.
---
The @{char} event is fired when a character is _typed_ on the keyboard.
The @{char} event is fired when a character is typed on the keyboard.
The @{char} event is different to a key press. Sometimes multiple key presses may result in one character being
typed (for instance, on some European keyboards). Similarly, some keys (e.g. <kbd>Ctrl</kbd>) do not have any
@@ -16,9 +16,10 @@ corresponding character. The @{key} should be used if you want to listen to key
## Example
Prints each character the user presses:
```lua
while true do
local event, character = os.pullEvent("char")
print(character .. " was pressed.")
local event, character = os.pullEvent("char")
print(character .. " was pressed.")
end
```

View File

@@ -6,7 +6,7 @@ The @{computer_command} event is fired when the `/computercraft queue` command i
## Return Values
1. @{string}: The event name.
... @{string}: The arguments passed to the command.
2. @{string}<abbr title="Variable number of arguments">&hellip;</abbr>: The arguments passed to the command.
## Example
Prints the contents of messages sent:

View File

@@ -5,9 +5,9 @@ since: 1.101.0
The @{file_transfer} event is queued when a user drags-and-drops a file on an open computer.
This event contains a single argument, that in turn has a single method @{TransferredFiles.getFiles|getFiles}. This
returns the list of files that are being transferred. Each file is a @{fs.BinaryReadHandle|binary file handle} with an
additional @{TransferredFile.getName|getName} method.
This event contains a single argument of type @{TransferredFiles}, which can be used to @{TransferredFiles.getFiles|get
the files to be transferred}. Each file returned is a @{fs.BinaryReadHandle|binary file handle} with an additional
@{TransferredFile.getName|getName} method.
## Return values
1. @{string}: The event name

View File

@@ -11,4 +11,4 @@ This event is normally handled inside @{http.checkURL}, but it can still be seen
1. @{string}: The event name.
2. @{string}: The URL requested to be checked.
3. @{boolean}: Whether the check succeeded.
4. @{string|nil}: If the check failed, a reason explaining why the check failed.
4. <span class="type">@{string}|@{nil}</span>: If the check failed, a reason explaining why the check failed.

View File

@@ -11,7 +11,8 @@ This event is normally handled inside @{http.get} and @{http.post}, but it can s
1. @{string}: The event name.
2. @{string}: The URL of the site requested.
3. @{string}: An error describing the failure.
4. @{http.Response|nil}: A response handle if the connection succeeded, but the server's response indicated failure.
4. <span class="type">@{http.Response}|@{nil}</span>: A response handle if the connection succeeded, but the server's
response indicated failure.
## Example
Prints an error why the website cannot be contacted:

View File

@@ -10,7 +10,7 @@ This event is normally handled inside @{http.get} and @{http.post}, but it can s
## Return Values
1. @{string}: The event name.
2. @{string}: The URL of the site requested.
3. @{http.Response}: The handle for the response text.
3. @{http.Response}: The successful HTTP response.
## Example
Prints the content of a website (this may fail if the request fails):

View File

@@ -10,7 +10,7 @@ The @{modem_message} event is fired when a message is received on an open channe
3. @{number}: The channel that the message was sent on.
4. @{number}: The reply channel set by the sender.
5. @{any}: The message as sent by the sender.
6. @{number}: The distance between the sender and the receiver, in blocks.
6. <span class="type">@{number}|@{nil}</span>: The distance between the sender and the receiver in blocks, or @{nil} if the message was sent between dimensions.
## Example
Wraps a @{modem} peripheral, opens channel 0 for listening, and prints all received messages.
@@ -20,7 +20,9 @@ local modem = peripheral.find("modem") or error("No modem attached", 0)
modem.open(0)
while true do
local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
print(("Message received on side %s on channel %d (reply to %d) from %f blocks away with message %s"):format(side, channel, replyChannel, distance, tostring(message)))
local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
print(("Message received on side %s on channel %d (reply to %d) from %f blocks away with message %s"):format(
side, channel, replyChannel, distance, tostring(message)
))
end
```

View File

@@ -6,10 +6,11 @@ The @{monitor_resize} event is fired when an adjacent or networked monitor's siz
## Return Values
1. @{string}: The event name.
2. @{string}: The side or network ID of the monitor that resized.
2. @{string}: The side or network ID of the monitor that was resized.
## Example
Prints a message when a monitor is resized:
```lua
while true do
local event, side = os.pullEvent("monitor_resize")

View File

@@ -14,7 +14,7 @@ This event is usually handled by @{rednet.receive}, but it can also be pulled ma
1. @{string}: The event name.
2. @{number}: The ID of the sending computer.
3. @{any}: The message sent.
4. @{string|nil}: The protocol of the message, if provided.
4. <span class="type">@{string}|@{nil}</span>: The protocol of the message, if provided.
## Example
Prints a message when one is sent:

View File

@@ -4,6 +4,9 @@ module: [kind=event] redstone
The @{event!redstone} event is fired whenever any redstone inputs on the computer change.
## Return values
1. @{string}: The event name.
## Example
Prints a message when a redstone input changes:
```lua

View File

@@ -10,7 +10,7 @@ The @{task_complete} event is fired when an asynchronous task completes. This is
2. @{number}: The ID of the task that completed.
3. @{boolean}: Whether the command succeeded.
4. @{string}: If the command failed, an error message explaining the failure. (This is not present if the command succeeded.)
...: Any parameters returned from the command.
5. <abbr title="Variable number of arguments">&hellip;</abbr>: Any parameters returned from the command.
## Example
Prints the results of an asynchronous command:

View File

@@ -9,8 +9,12 @@ The @{term_resize} event is fired when the main terminal is resized. For instanc
When this event fires, some parts of the terminal may have been moved or deleted. Simple terminal programs (those
not using @{term.setCursorPos}) can ignore this event, but more complex GUI programs should redraw the entire screen.
## Return values
1. @{string}: The event name.
## Example
Prints :
Print a message each time the terminal is resized.
```lua
while true do
os.pullEvent("term_resize")

View File

@@ -8,6 +8,9 @@ This event is normally handled by @{os.pullEvent}, and will not be returned. How
@{terminate} will be sent even when a filter is provided to @{os.pullEventRaw}. When using @{os.pullEventRaw} with a filter, make sure to check that the event is not @{terminate}.
## Return values
1. @{string}: The event name.
## Example
Prints a message when Ctrl-T is held:
```lua

View File

@@ -10,12 +10,12 @@ The @{timer} event is fired when a timer started with @{os.startTimer} completes
2. @{number}: The ID of the timer that finished.
## Example
Starts a timer and then prints its ID:
Start and wait for a timer to finish.
```lua
local timerID = os.startTimer(2)
local timer_id = os.startTimer(2)
local event, id
repeat
event, id = os.pullEvent("timer")
until id == timerID
until id == timer_id
print("Timer with ID " .. id .. " was fired")
```

View File

@@ -4,6 +4,9 @@ module: [kind=event] turtle_inventory
The @{turtle_inventory} event is fired when a turtle's inventory is changed.
## Return values
1. @{string}: The event name.
## Example
Prints a message when the inventory is changed:
```lua

View File

@@ -25,7 +25,7 @@ single-player or multiplayer. Look for lines that look like this:
```
On 1.95.0 and later, this will be a single entry with `host = "$private"`. On earlier versions, this will be a number of
`[[http.rules]]` with various IP addresses. You will want to remove all of the `[[http.rules]]` entires that have
`[[http.rules]]` with various IP addresses. You will want to remove all of the `[[http.rules]]` entries that have
`action = "deny"`. Then save the file and relaunch Minecraft (Server).
Here's what it should look like after removing:
@@ -54,7 +54,7 @@ like this:
```toml
#A list of wildcards for domains or IP ranges that cannot be accessed through the "http" API on Computers.
#If this is empty then all whitelisted domains will be accessible. Example: "*.github.com" will block access to all subdomains of github.com.
#You can use domain names ("pastebin.com"), wilcards ("*.pastebin.com") or CIDR notation ("127.0.0.0/8").
#You can use domain names ("pastebin.com"), wildcards ("*.pastebin.com") or CIDR notation ("127.0.0.0/8").
blacklist = ["127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fd00::/8"]
```
@@ -65,7 +65,7 @@ Here's what it should look like after removing:
```toml
#A list of wildcards for domains or IP ranges that cannot be accessed through the "http" API on Computers.
#If this is empty then all whitelisted domains will be accessible. Example: "*.github.com" will block access to all subdomains of github.com.
#You can use domain names ("pastebin.com"), wilcards ("*.pastebin.com") or CIDR notation ("127.0.0.0/8").
#You can use domain names ("pastebin.com"), wildcards ("*.pastebin.com") or CIDR notation ("127.0.0.0/8").
blacklist = []
```

View File

@@ -5,8 +5,8 @@ kotlin.stdlib.default.dependency=false
kotlin.jvm.target.validation.mode=error
# Mod properties
isUnstable=true
modVersion=1.102.1
isUnstable=false
modVersion=1.103.0
# Minecraft properties: We want to configure this here so we can read it in settings.gradle
mcVersion=1.19.3

View File

@@ -14,13 +14,13 @@ parchmentMc = "1.19.2"
asm = "9.3"
autoService = "1.0.1"
checkerFramework = "3.12.0"
cobalt = "0.5.9"
cobalt = "0.6.0"
fastutil = "8.5.9"
guava = "31.1-jre"
jetbrainsAnnotations = "23.0.0"
jsr305 = "3.0.2"
kotlin = "1.7.10"
kotlin-coroutines = "1.6.0"
kotlin = "1.8.0"
kotlin-coroutines = "1.6.4"
netty = "4.1.82.Final"
nightConfig = "3.6.5"
slf4j = "1.7.36"
@@ -42,7 +42,7 @@ jqwik = "1.7.0"
junit = "5.9.1"
# Build tools
cctJavadoc = "1.5.3"
cctJavadoc = "1.6.0"
checkstyle = "10.3.4"
curseForgeGradle = "1.0.11"
errorProne-core = "2.14.0"
@@ -51,7 +51,7 @@ fabric-loom = "1.0-SNAPSHOT"
forgeGradle = "5.1.+"
githubRelease = "2.2.12"
ideaExt = "1.1.6"
illuaminate = "0.1.0-12-ga03e9cd"
illuaminate = "0.1.0-13-g689d73d"
librarian = "1.+"
minotaur = "2.+"
mixinGradle = "0.7.+"
@@ -73,8 +73,9 @@ forgeSpi = { module = "net.minecraftforge:forgespi", version.ref = "forgeSpi" }
guava = { module = "com.google.guava:guava", version.ref = "guava" }
jetbrainsAnnotations = { module = "org.jetbrains:annotations", version.ref = "jetbrainsAnnotations" }
jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" }
kotlin-platform = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" }
kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlin-coroutines" }
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin" }
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" }
netty-http = { module = "io.netty:netty-codec-http", version.ref = "netty" }
nightConfig-core = { module = "com.electronwill.night-config:core", version.ref = "nightConfig" }
nightConfig-toml = { module = "com.electronwill.night-config:toml", version.ref = "nightConfig" }

View File

@@ -8,7 +8,11 @@ package dan200.computercraft.api;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
/**
@@ -21,6 +25,15 @@ public class ComputerCraftTags {
public static final TagKey<Item> WIRED_MODEM = make("wired_modem");
public static final TagKey<Item> MONITOR = make("monitor");
/**
* Items which can be {@linkplain Item#use(Level, Player, InteractionHand) used} when calling
* {@code turtle.place()}.
* <p>
* This does not cover items who handle placing inside {@link Item#useOn(UseOnContext)}, as that is always
* called.
*/
public static final TagKey<Item> TURTLE_CAN_PLACE = make("turtle_can_place");
private static TagKey<Item> make(String name) {
return TagKey.create(Registries.ITEM, new ResourceLocation(ComputerCraftAPI.MOD_ID, name));
}

View File

@@ -32,6 +32,8 @@ public interface DetailRegistry<T> {
/**
* Compute basic details about an object. This is cheaper than computing all details operation, and so is suitable
* for when you need to compute the details for a large number of values.
* <p>
* This method <em>MAY</em> be thread safe: consult the instance's documentation for details.
*
* @param object The object to get details for.
* @return The basic details.
@@ -40,6 +42,8 @@ public interface DetailRegistry<T> {
/**
* Compute all details about an object, using {@link #getBasicDetails(Object)} and any registered providers.
* <p>
* This method is <em>NOT</em> thread safe. It should only be called from the computer thread.
*
* @param object The object to get details for.
* @return The computed details.

View File

@@ -15,12 +15,17 @@ import net.minecraft.world.level.block.Block;
public class VanillaDetailRegistries {
/**
* Provides details for {@link ItemStack}s.
* <p>
* This instance's {@link DetailRegistry#getBasicDetails(Object)} is thread safe (assuming the stack is immutable)
* and may be called from the computer thread.
*/
public static final DetailRegistry<ItemStack> ITEM_STACK = ComputerCraftAPIService.get().getItemStackDetailRegistry();
/**
* Provides details for {@link BlockReference}, a reference to a {@link Block} in the world.
* <p>
* This instance's {@link DetailRegistry#getBasicDetails(Object)} is thread safe and may be called from the computer
* thread.
*/
public static final DetailRegistry<BlockReference> BLOCK_IN_WORLD = ComputerCraftAPIService.get().getBlockInWorldDetailRegistry();
}

View File

@@ -15,6 +15,7 @@ import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.Container;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.ApiStatus;
import javax.annotation.Nullable;
@@ -24,6 +25,7 @@ import javax.annotation.Nullable;
* This should not be implemented by your classes. Do not interact with turtles except via this interface and
* {@link ITurtleUpgrade}.
*/
@ApiStatus.NonExtendable
public interface ITurtleAccess {
/**
* Returns the world in which the turtle resides.

View File

@@ -98,7 +98,7 @@ public abstract class TurtleUpgradeDataProvider extends UpgradeDataProvider<ITur
* get the final damage.
*
* @param damageMultiplier The damage multiplier.
* @return The tool builder, for futher use.
* @return The tool builder, for further use.
*/
public ToolBuilder damageMultiplier(float damageMultiplier) {
this.damageMultiplier = damageMultiplier;

View File

@@ -144,7 +144,7 @@ public abstract class UpgradeDataProvider<T extends UpgradeBase, R extends Upgra
}
public List<T> getGeneratedUpgrades() {
if (upgrades == null) throw new IllegalStateException("Upgrades have not beeen generated yet");
if (upgrades == null) throw new IllegalStateException("Upgrades have not been generated yet");
return upgrades;
}

View File

@@ -30,6 +30,7 @@ public class TerminalWidget extends AbstractWidget {
private static final Component DESCRIPTION = Component.translatable("gui.computercraft.terminal");
private static final float TERMINATE_TIME = 0.5f;
private static final float KEY_SUPPRESS_DELAY = 0.2f;
private final Terminal terminal;
private final InputHandler computer;
@@ -79,15 +80,12 @@ public class TerminalWidget extends AbstractWidget {
switch (key) {
case GLFW.GLFW_KEY_T -> {
if (terminateTimer < 0) terminateTimer = 0;
return true;
}
case GLFW.GLFW_KEY_S -> {
if (shutdownTimer < 0) shutdownTimer = 0;
return true;
}
case GLFW.GLFW_KEY_R -> {
if (rebootTimer < 0) rebootTimer = 0;
return true;
}
case GLFW.GLFW_KEY_V -> {
// Ctrl+V for paste
@@ -118,7 +116,7 @@ public class TerminalWidget extends AbstractWidget {
}
}
if (key >= 0 && terminateTimer < 0 && rebootTimer < 0 && shutdownTimer < 0) {
if (key >= 0 && terminateTimer < KEY_SUPPRESS_DELAY && rebootTimer < KEY_SUPPRESS_DELAY && shutdownTimer < KEY_SUPPRESS_DELAY) {
// Queue the "key" event and add to the down set
var repeat = keysDown.get(key);
keysDown.set(key);

View File

@@ -15,7 +15,6 @@ import dan200.computercraft.client.render.TurtleBlockEntityRenderer;
import dan200.computercraft.client.turtle.TurtleUpgradeModellers;
import dan200.computercraft.shared.turtle.items.TurtleItem;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.resources.ResourceLocation;
@@ -71,13 +70,16 @@ public final class TurtleModelParts {
}
public Combination getCombination(ItemStack stack) {
var turtle = (TurtleItem) stack.getItem();
var christmas = Holiday.getCurrent() == Holiday.CHRISTMAS;
if (!(stack.getItem() instanceof TurtleItem turtle)) {
return new Combination(false, null, null, null, christmas, false);
}
var colour = turtle.getColour(stack);
var leftUpgrade = turtle.getUpgrade(stack, TurtleSide.LEFT);
var rightUpgrade = turtle.getUpgrade(stack, TurtleSide.RIGHT);
var overlay = turtle.getOverlay(stack);
var christmas = HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS;
var label = turtle.getLabel(stack);
var flip = label != null && (label.equals("Dinnerbone") || label.equals("Grumm"));

View File

@@ -17,7 +17,6 @@ import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.turtle.blocks.TurtleBlockEntity;
import dan200.computercraft.shared.util.DirectionUtil;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.MultiBufferSource;
@@ -112,7 +111,7 @@ public class TurtleBlockEntityRenderer implements BlockEntityRenderer<TurtleBloc
renderModel(transform, buffer, lightmapCoord, overlayLight, getTurtleModel(family, colour != -1), colour == -1 ? null : new int[]{ colour });
// Render the overlay
var overlayModel = getTurtleOverlayModel(overlay, HolidayUtil.getCurrentHoliday() == Holiday.CHRISTMAS);
var overlayModel = getTurtleOverlayModel(overlay, Holiday.getCurrent() == Holiday.CHRISTMAS);
if (overlayModel != null) {
renderModel(transform, buffer, lightmapCoord, overlayLight, overlayModel, null);
}

View File

@@ -65,6 +65,7 @@ class RecipeProvider extends net.minecraft.data.recipes.RecipeProvider {
addSpecial(add, ModRegistry.RecipeSerializers.PRINTOUT.get());
addSpecial(add, ModRegistry.RecipeSerializers.DISK.get());
addSpecial(add, ModRegistry.RecipeSerializers.DYEABLE_ITEM.get());
addSpecial(add, ModRegistry.RecipeSerializers.DYEABLE_ITEM_CLEAR.get());
addSpecial(add, ModRegistry.RecipeSerializers.TURTLE_UPGRADE.get());
addSpecial(add, ModRegistry.RecipeSerializers.POCKET_COMPUTER_UPGRADE.get());
}

View File

@@ -15,6 +15,7 @@ import net.minecraft.tags.ItemTags;
import net.minecraft.tags.TagBuilder;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
@@ -85,6 +86,10 @@ class TagProvider {
ModRegistry.Items.WIRELESS_MODEM_ADVANCED.get(), ModRegistry.Items.POCKET_COMPUTER_ADVANCED.get(),
ModRegistry.Items.MONITOR_ADVANCED.get()
);
tags.tag(ComputerCraftTags.Items.TURTLE_CAN_PLACE)
.add(Items.GLASS_BOTTLE)
.addTag(ItemTags.BOATS);
}
/**

View File

@@ -19,6 +19,7 @@ import dan200.computercraft.shared.command.arguments.ComputerArgumentType;
import dan200.computercraft.shared.command.arguments.ComputersArgumentType;
import dan200.computercraft.shared.command.arguments.RepeatArgumentType;
import dan200.computercraft.shared.command.arguments.TrackingFieldArgumentType;
import dan200.computercraft.shared.common.ClearColourRecipe;
import dan200.computercraft.shared.common.ColourableRecipe;
import dan200.computercraft.shared.common.DefaultBundledRedstoneProvider;
import dan200.computercraft.shared.common.HeldItemMenu;
@@ -351,6 +352,7 @@ public final class ModRegistry {
}
public static final RegistryEntry<SimpleCraftingRecipeSerializer<ColourableRecipe>> DYEABLE_ITEM = simple("colour", ColourableRecipe::new);
public static final RegistryEntry<SimpleCraftingRecipeSerializer<ClearColourRecipe>> DYEABLE_ITEM_CLEAR = simple("clear_colour", ClearColourRecipe::new);
public static final RegistryEntry<TurtleRecipe.Serializer> TURTLE = REGISTRY.register("turtle", TurtleRecipe.Serializer::new);
public static final RegistryEntry<SimpleCraftingRecipeSerializer<TurtleUpgradeRecipe>> TURTLE_UPGRADE = simple("turtle_upgrade", TurtleUpgradeRecipe::new);
public static final RegistryEntry<SimpleCraftingRecipeSerializer<PocketComputerUpgradeRecipe>> POCKET_COMPUTER_UPGRADE = simple("pocket_computer_upgrade", PocketComputerUpgradeRecipe::new);

View File

@@ -0,0 +1,84 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2022. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.shared.common;
import dan200.computercraft.shared.ModRegistry;
import net.minecraft.core.NonNullList;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.crafting.CraftingBookCategory;
import net.minecraft.world.item.crafting.CustomRecipe;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.level.Level;
/**
* Craft a wet sponge with a {@linkplain IColouredItem dyable item} to remove its dye.
*/
public final class ClearColourRecipe extends CustomRecipe {
public ClearColourRecipe(ResourceLocation id, CraftingBookCategory category) {
super(id, category);
}
@Override
public boolean matches(CraftingContainer inv, Level world) {
var hasColourable = false;
var hasSponge = false;
for (var i = 0; i < inv.getContainerSize(); i++) {
var stack = inv.getItem(i);
if (stack.isEmpty()) continue;
if (stack.getItem() instanceof IColouredItem colourable) {
if (hasColourable) return false;
if (colourable.getColour(stack) == -1) return false;
hasColourable = true;
} else if (stack.getItem() == Items.WET_SPONGE) {
if (hasSponge) return false;
hasSponge = true;
} else {
return false;
}
}
return hasColourable && hasSponge;
}
@Override
public ItemStack assemble(CraftingContainer inv) {
var colourable = ItemStack.EMPTY;
for (var i = 0; i < inv.getContainerSize(); i++) {
var stack = inv.getItem(i);
if (stack.getItem() instanceof IColouredItem) colourable = stack;
}
if (colourable.isEmpty()) return ItemStack.EMPTY;
var stack = ((IColouredItem) colourable.getItem()).withColour(colourable, -1);
stack.setCount(1);
return stack;
}
@Override
public NonNullList<ItemStack> getRemainingItems(CraftingContainer container) {
var remaining = NonNullList.withSize(container.getContainerSize(), ItemStack.EMPTY);
for (var i = 0; i < remaining.size(); i++) {
if (container.getItem(i).getItem() == Items.WET_SPONGE) remaining.set(i, new ItemStack(Items.WET_SPONGE));
}
return remaining;
}
@Override
public boolean canCraftInDimensions(int x, int y) {
return x * y >= 2;
}
@Override
public RecipeSerializer<ClearColourRecipe> getSerializer() {
return ModRegistry.RecipeSerializers.DYEABLE_ITEM_CLEAR.get();
}
}

View File

@@ -74,7 +74,7 @@ public final class ColourableRecipe extends CustomRecipe {
}
@Override
public RecipeSerializer<?> getSerializer() {
public RecipeSerializer<ColourableRecipe> getSerializer() {
return ModRegistry.RecipeSerializers.DYEABLE_ITEM.get();
}
}

View File

@@ -25,14 +25,9 @@ import java.util.*;
* Data providers for items.
*/
public class ItemDetails {
public static <T extends Map<? super String, Object>> T fillBasicSafe(T data, ItemStack stack) {
public static void fillBasic(Map<? super String, Object> data, ItemStack stack) {
data.put("name", DetailHelpers.getId(RegistryWrappers.ITEMS, stack.getItem()));
data.put("count", stack.getCount());
return data;
}
public static void fillBasic(Map<? super String, Object> data, ItemStack stack) {
fillBasicSafe(data, stack);
var hash = NBTUtil.getNBTHash(stack.getTag());
if (hash != null) data.put("nbt", hash);
}

View File

@@ -82,10 +82,10 @@ public class UpgradesLoadedMessage implements NetworkMessage<ClientNetworkContex
var serialiser = entry.getValue().serialiser();
@SuppressWarnings("unchecked")
var unwrapedSerialiser = (UpgradeSerialiser<T>) serialiser;
var unwrappedSerialiser = (UpgradeSerialiser<T>) serialiser;
buf.writeResourceLocation(Objects.requireNonNull(registry.getKey(serialiser), "Serialiser is not registered!"));
unwrapedSerialiser.toNetwork(buf, entry.getValue().upgrade());
unwrappedSerialiser.toNetwork(buf, entry.getValue().upgrade());
buf.writeUtf(entry.getValue().modId());
}

View File

@@ -6,6 +6,7 @@
package dan200.computercraft.shared.peripheral.diskdrive;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import dan200.computercraft.api.filesystem.Mount;
import dan200.computercraft.api.filesystem.WritableMount;
import dan200.computercraft.api.peripheral.IComputerAccess;
import dan200.computercraft.api.peripheral.IPeripheral;
@@ -47,11 +48,14 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
private final NonNullList<ItemStack> inventory = NonNullList.withSize(1, ItemStack.EMPTY);
private MediaStack media = MediaStack.EMPTY;
private @Nullable Mount mount;
private boolean recordPlaying = false;
// In order to avoid main-thread calls in the peripheral, we set flags to mark which operation should be performed,
// then read them when ticking.
private final AtomicReference<RecordCommand> recordQueued = new AtomicReference<>(null);
private final AtomicBoolean ejectQueued = new AtomicBoolean(false);
private final AtomicBoolean mountQueued = new AtomicBoolean(false);
public DiskDriveBlockEntity(BlockEntityType<DiskDriveBlockEntity> type, BlockPos pos, BlockState state) {
super(type, pos, state);
@@ -109,6 +113,12 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
}
}
}
if (mountQueued.get()) {
synchronized (this) {
mountAll();
}
}
}
@Override
@@ -124,9 +134,9 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
private void updateItem() {
var newDisk = getDiskStack();
if (ItemStack.isSame(newDisk, media.stack)) return;
if (ItemStack.isSameItemSameTags(newDisk, media.stack)) return;
var media = new MediaStack(newDisk.copy());
var media = MediaStack.of(newDisk);
if (newDisk.isEmpty()) {
updateBlockState(DiskDriveState.EMPTY);
@@ -146,12 +156,10 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
recordPlaying = false;
}
mount = null;
this.media = media;
// Mount new disk
if (!this.media.stack.isEmpty()) {
for (var computer : computers.entrySet()) mountDisk(computer.getKey(), computer.getValue(), this.media);
}
mountAll();
}
}
@@ -163,11 +171,30 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
return media;
}
/**
* Set the current disk stack, mounting/unmounting if needed.
*
* @param stack The new disk stack.
*/
void setDiskStack(ItemStack stack) {
setItem(0, stack);
setChanged();
}
/**
* Update the current disk stack, assuming the underlying item does not change. Unlike
* {@link #setDiskStack(ItemStack)} this will not change any mounts.
*
* @param stack The new disk stack.
*/
void updateDiskStack(ItemStack stack) {
setItem(0, stack);
if (!ItemStack.isSameItemSameTags(stack, media.stack)) {
media = MediaStack.of(stack);
super.setChanged();
}
}
@Nullable
String getDiskMountPath(IComputerAccess computer) {
synchronized (this) {
@@ -176,15 +203,21 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
}
}
void mount(IComputerAccess computer) {
/**
* Attach a computer to this disk drive. This sets up the {@link MountInfo} map and flags us to mount next tick. We
* don't mount here, as that might require mutating the current stack.
*
* @param computer The computer to attach.
*/
void attach(IComputerAccess computer) {
synchronized (this) {
var info = new MountInfo();
computers.put(computer, info);
mountDisk(computer, info, media);
mountQueued.set(true);
}
}
void unmount(IComputerAccess computer) {
void detach(IComputerAccess computer) {
synchronized (this) {
unmountDisk(computer, computers.remove(computer));
}
@@ -202,10 +235,35 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
ejectQueued.set(true);
}
/**
* Add our mount to all computers.
*/
@GuardedBy("this")
private void mountDisk(IComputerAccess computer, MountInfo info, MediaStack disk) {
var mount = disk.getMount((ServerLevel) getLevel());
if (mount != null) {
private void mountAll() {
doMountAll();
mountQueued.set(false);
}
/**
* The worker for {@link #mountAll()}. This is responsible for creating the mount and placing it on all computers.
*/
@GuardedBy("this")
private void doMountAll() {
if (computers.isEmpty() || media.media == null) return;
if (mount == null) {
var stack = getDiskStack();
mount = media.media.createDataMount(stack, (ServerLevel) level);
setDiskStack(stack);
}
if (mount == null) return;
for (var entry : computers.entrySet()) {
var computer = entry.getKey();
var info = entry.getValue();
if (info.mountPath != null) continue;
if (mount instanceof WritableMount writable) {
// Try mounting at the lowest numbered "disk" name we can
var n = 1;
@@ -221,11 +279,9 @@ public final class DiskDriveBlockEntity extends AbstractContainerBlockEntity {
n++;
}
}
} else {
info.mountPath = null;
}
computer.queueEvent("disk", computer.getAttachmentName());
computer.queueEvent("disk", computer.getAttachmentName());
}
}
private static void unmountDisk(IComputerAccess computer, MountInfo info) {

View File

@@ -84,11 +84,12 @@ public class DiskDrivePeripheral implements IPeripheral {
var media = diskDrive.getMedia();
if (media.media == null) return;
var stack = media.stack.copy();
// We're on the main thread so the stack and media should be in sync.
var stack = diskDrive.getDiskStack();
if (!media.media.setLabel(stack, label.map(StringUtil::normaliseLabel).orElse(null))) {
throw new LuaException("Disk label cannot be changed");
}
diskDrive.setDiskStack(stack);
diskDrive.updateDiskStack(stack);
}
/**
@@ -178,12 +179,12 @@ public class DiskDrivePeripheral implements IPeripheral {
@Override
public void attach(IComputerAccess computer) {
diskDrive.mount(computer);
diskDrive.attach(computer);
}
@Override
public void detach(IComputerAccess computer) {
diskDrive.unmount(computer);
diskDrive.detach(computer);
}
@Override

View File

@@ -5,10 +5,8 @@
*/
package dan200.computercraft.shared.peripheral.diskdrive;
import dan200.computercraft.api.filesystem.Mount;
import dan200.computercraft.api.media.IMedia;
import dan200.computercraft.impl.MediaProviders;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.item.ItemStack;
@@ -17,18 +15,22 @@ import javax.annotation.Nullable;
/**
* An immutable snapshot of the current disk. This allows us to read the stack in a thread-safe manner.
*/
class MediaStack {
static final MediaStack EMPTY = new MediaStack(ItemStack.EMPTY);
final class MediaStack {
static final MediaStack EMPTY = new MediaStack(ItemStack.EMPTY, null);
final ItemStack stack;
final @Nullable IMedia media;
@Nullable
private Mount mount;
MediaStack(ItemStack stack) {
private MediaStack(ItemStack stack, @Nullable IMedia media) {
this.stack = stack;
media = MediaProviders.get(stack);
this.media = media;
}
public static MediaStack of(ItemStack stack) {
if (stack.isEmpty()) return EMPTY;
var freshStack = stack.copy();
return new MediaStack(freshStack, MediaProviders.get(freshStack));
}
@Nullable
@@ -40,12 +42,4 @@ class MediaStack {
String getAudioTitle() {
return media != null ? media.getAudioTitle(stack) : null;
}
@Nullable
public Mount getMount(ServerLevel level) {
if (media == null) return null;
if (mount == null) mount = media.createDataMount(stack, level);
return mount;
}
}

View File

@@ -52,6 +52,15 @@ import java.util.Set;
* <li><strong>Wired modems:</strong> These send messages to other any other wired modems connected to the same network
* (using <em>Networking Cable</em>). They also can be used to attach additional peripherals to a computer.</li></ul>
*
* ## Recipes
* <div class="recipe-container">
* <mc-recipe recipe="computercraft:wireless_modem_normal"></mc-recipe>
* <mc-recipe recipe="computercraft:wireless_modem_advanced"></mc-recipe>
* <mc-recipe recipe="computercraft:wired_modem"></mc-recipe>
* <mc-recipe recipe="computercraft:cable"></mc-recipe>
* <mc-recipe recipe="computercraft:wired_modem_full_from"></mc-recipe>
* </div>
*
* @cc.module modem
* @cc.see modem_message Queued when a modem receives a message on an {@link #open(int) open channel}.
* @cc.see rednet A networking API built on top of the modem peripheral.
@@ -74,14 +83,6 @@ import java.util.Set;
* print("Received a reply: " .. tostring(message))
* }</pre>
* <p>
* ## Recipes
* <div class="recipe-container">
* <mc-recipe recipe="computercraft:wireless_modem_normal"></mc-recipe>
* <mc-recipe recipe="computercraft:wireless_modem_advanced"></mc-recipe>
* <mc-recipe recipe="computercraft:wired_modem"></mc-recipe>
* <mc-recipe recipe="computercraft:cable"></mc-recipe>
* <mc-recipe recipe="computercraft:wired_modem_full_from"></mc-recipe>
* </div>
*/
public abstract class ModemPeripheral implements IPeripheral, PacketSender, PacketReceiver {
private @Nullable PacketNetwork network;

View File

@@ -242,7 +242,7 @@ public abstract class SpeakerPeripheral implements IPeripheral {
* @throws LuaException If the sound name was invalid.
* @cc.usage Play a creeper hiss with the speaker.
*
* <pre>{@code
* <pre data-peripheral="speaker">{@code
* local speaker = peripheral.find("speaker")
* speaker.playSound("entity.creeper.primed")
* }</pre>
@@ -294,7 +294,7 @@ public abstract class SpeakerPeripheral implements IPeripheral {
* @cc.since 1.100
* @cc.usage Read an audio file, decode it using @{cc.audio.dfpwm}, and play it using the speaker.
*
* <pre>{@code
* <pre data-peripheral="speaker">{@code
* local dfpwm = require("cc.audio.dfpwm")
* local speaker = peripheral.find("speaker")
*

View File

@@ -69,7 +69,7 @@ public class PocketAPI implements ILuaAPI {
if (newUpgrade == null) return new Object[]{ false, "Cannot find a valid upgrade" };
// Remove the current upgrade
if (previousUpgrade != null) storeItem(player, previousUpgrade.getCraftingItem());
if (previousUpgrade != null) storeItem(player, previousUpgrade.getCraftingItem().copy());
// Set the new upgrade
computer.setUpgrade(newUpgrade);
@@ -88,14 +88,13 @@ public class PocketAPI implements ILuaAPI {
public final Object[] unequipBack() {
var entity = computer.getEntity();
if (!(entity instanceof Player player)) return new Object[]{ false, "Cannot find player" };
var inventory = player.getInventory();
var previousUpgrade = computer.getUpgrade();
if (previousUpgrade == null) return new Object[]{ false, "Nothing to unequip" };
computer.setUpgrade(null);
storeItem(player, previousUpgrade.getCraftingItem());
storeItem(player, previousUpgrade.getCraftingItem().copy());
return new Object[]{ true };
}

View File

@@ -7,16 +7,13 @@ package dan200.computercraft.shared.turtle.apis;
import dan200.computercraft.api.detail.VanillaDetailRegistries;
import dan200.computercraft.api.lua.*;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.TurtleCommand;
import dan200.computercraft.api.turtle.TurtleCommandResult;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.core.apis.IAPIEnvironment;
import dan200.computercraft.core.metrics.Metrics;
import dan200.computercraft.shared.details.ItemDetails;
import dan200.computercraft.shared.turtle.core.*;
import java.util.HashMap;
import java.util.Optional;
/**
@@ -70,9 +67,9 @@ import java.util.Optional;
*/
public class TurtleAPI implements ILuaAPI {
private final IAPIEnvironment environment;
private final ITurtleAccess turtle;
private final TurtleAccessInternal turtle;
public TurtleAPI(IAPIEnvironment environment, ITurtleAccess turtle) {
public TurtleAPI(IAPIEnvironment environment, TurtleAccessInternal turtle) {
this.environment = environment;
this.turtle = turtle;
}
@@ -136,7 +133,7 @@ public class TurtleAPI implements ILuaAPI {
}
/**
* Rotate the turtle 90 degress to the left.
* Rotate the turtle 90 degrees to the left.
*
* @return The turtle command result.
* @cc.treturn boolean Whether the turtle could successfully turn.
@@ -148,7 +145,7 @@ public class TurtleAPI implements ILuaAPI {
}
/**
* Rotate the turtle 90 degress to the right.
* Rotate the turtle 90 degrees to the right.
*
* @return The turtle command result.
* @cc.treturn boolean Whether the turtle could successfully turn.
@@ -555,7 +552,7 @@ public class TurtleAPI implements ILuaAPI {
* @throws LuaException If the refuel count is out of range.
* @cc.treturn [1] true If the turtle was refuelled.
* @cc.treturn [2] false If the turtle was not refuelled.
* @cc.treturn [2] string The reason the turtle was not refuelled (
* @cc.treturn [2] string The reason the turtle was not refuelled.
* @cc.usage Refuel a turtle from the currently selected slot.
* <pre>{@code
* local level = turtle.getFuelLevel()
@@ -652,7 +649,7 @@ public class TurtleAPI implements ILuaAPI {
* previous upgrade is removed and placed into the turtle's inventory. If there is no item in the slot, the previous
* upgrade is removed, but no new one is equipped.
*
* @return Whether an item was equiped or not.
* @return Whether an item was equipped or not.
* @cc.treturn [1] true If the item was equipped.
* @cc.treturn [2] false If we could not equip the item.
* @cc.treturn [2] string The reason equipping this item failed.
@@ -671,7 +668,7 @@ public class TurtleAPI implements ILuaAPI {
* previous upgrade is removed and placed into the turtle's inventory. If there is no item in the slot, the previous
* upgrade is removed, but no new one is equipped.
*
* @return Whether an item was equiped or not.
* @return Whether an item was equipped or not.
* @cc.treturn [1] true If the item was equipped.
* @cc.treturn [2] false If we could not equip the item.
* @cc.treturn [2] string The reason equipping this item failed.
@@ -760,20 +757,15 @@ public class TurtleAPI implements ILuaAPI {
@LuaFunction
public final MethodResult getItemDetail(ILuaContext context, Optional<Integer> slot, Optional<Boolean> detailed) throws LuaException {
int actualSlot = checkSlot(slot).orElse(turtle.getSelectedSlot());
return detailed.orElse(false)
? context.executeMainThreadTask(() -> getItemDetail(actualSlot, true))
: MethodResult.of(getItemDetail(actualSlot, false));
}
private Object[] getItemDetail(int slot, boolean detailed) {
var stack = turtle.getInventory().getItem(slot);
if (stack.isEmpty()) return new Object[]{ null };
var table = detailed
? VanillaDetailRegistries.ITEM_STACK.getDetails(stack)
: ItemDetails.fillBasicSafe(new HashMap<>(), stack);
return new Object[]{ table };
if (detailed.orElse(false)) {
return context.executeMainThreadTask(() -> {
var stack = turtle.getInventory().getItem(actualSlot);
return new Object[]{ stack.isEmpty() ? null : VanillaDetailRegistries.ITEM_STACK.getDetails(stack) };
});
} else {
var stack = turtle.getItemSnapshot(actualSlot);
return MethodResult.of(stack.isEmpty() ? null : VanillaDetailRegistries.ITEM_STACK.getBasicDetails(stack));
}
}

View File

@@ -29,14 +29,10 @@ import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.DyeItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
@@ -56,7 +52,7 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
}
private final NonNullList<ItemStack> inventory = NonNullList.withSize(INVENTORY_SIZE, ItemStack.EMPTY);
private final NonNullList<ItemStack> previousInventory = NonNullList.withSize(INVENTORY_SIZE, ItemStack.EMPTY);
private final NonNullList<ItemStack> inventorySnapshot = NonNullList.withSize(INVENTORY_SIZE, ItemStack.EMPTY);
private boolean inventoryChanged = false;
private TurtleBrain brain = new TurtleBrain(this);
private MoveState moveState = MoveState.NOT_MOVED;
@@ -78,7 +74,7 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
getFamily(), Config.turtleTermWidth,
Config.turtleTermHeight
);
computer.addAPI(new TurtleAPI(computer.getAPIEnvironment(), getAccess()));
computer.addAPI(new TurtleAPI(computer.getAPIEnvironment(), brain));
brain.setupComputer(computer);
return computer;
}
@@ -88,42 +84,6 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
if (!hasMoved()) super.unload();
}
@Override
public InteractionResult use(Player player, InteractionHand hand) {
// Apply dye
var currentItem = player.getItemInHand(hand);
if (!currentItem.isEmpty()) {
if (currentItem.getItem() instanceof DyeItem dyeItem) {
// Dye to change turtle colour
if (!getLevel().isClientSide) {
var dye = dyeItem.getDyeColor();
if (brain.getDyeColour() != dye) {
brain.setDyeColour(dye);
if (!player.isCreative()) {
currentItem.shrink(1);
}
}
}
return InteractionResult.sidedSuccess(getLevel().isClientSide);
} else if (currentItem.getItem() == Items.WATER_BUCKET && brain.getColour() != -1) {
// Water to remove turtle colour
if (!getLevel().isClientSide) {
if (brain.getColour() != -1) {
brain.setColour(-1);
if (!player.isCreative()) {
player.setItemInHand(hand, new ItemStack(Items.BUCKET));
player.getInventory().setChanged();
}
}
}
return InteractionResult.sidedSuccess(getLevel().isClientSide);
}
}
// Open GUI or whatever
return super.use(player, hand);
}
@Override
protected boolean canNameWithTag(Player player) {
return true;
@@ -141,11 +101,7 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
if (inventoryChanged) {
var computer = getServerComputer();
if (computer != null) computer.queueEvent("turtle_inventory");
inventoryChanged = false;
for (var n = 0; n < getContainerSize(); n++) {
previousInventory.set(n, getItem(n).copy());
}
}
}
@@ -178,13 +134,13 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
// Read inventory
var nbttaglist = nbt.getList("Items", Tag.TAG_COMPOUND);
inventory.clear();
previousInventory.clear();
inventorySnapshot.clear();
for (var i = 0; i < nbttaglist.size(); i++) {
var tag = nbttaglist.getCompound(i);
var slot = tag.getByte("Slot") & 0xff;
if (slot < getContainerSize()) {
inventory.set(slot, ItemStack.of(tag));
previousInventory.set(slot, inventory.get(slot).copy());
inventorySnapshot.set(slot, inventory.get(slot).copy());
}
}
@@ -273,7 +229,7 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
void setOwningPlayer(GameProfile player) {
brain.setOwningPlayer(player);
setChanged();
onTileEntityChange();
}
// IInventory
@@ -283,16 +239,20 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
return inventory;
}
public ItemStack getItemSnapshot(int slot) {
return slot >= 0 && slot < inventorySnapshot.size() ? inventorySnapshot.get(slot) : ItemStack.EMPTY;
}
@Override
public void setChanged() {
super.setChanged();
if (!inventoryChanged) {
for (var n = 0; n < getContainerSize(); n++) {
if (!ItemStack.matches(getItem(n), previousInventory.get(n))) {
inventoryChanged = true;
break;
}
}
for (var slot = 0; slot < getContainerSize(); slot++) {
var item = getItem(slot);
if (ItemStack.matches(item, inventorySnapshot.get(slot))) continue;
inventoryChanged = true;
inventorySnapshot.set(slot, item.copy());
}
}
@@ -340,7 +300,7 @@ public class TurtleBlockEntity extends AbstractComputerBlockEntity implements Ba
public void transferStateFrom(TurtleBlockEntity copy) {
super.transferStateFrom(copy);
Collections.copy(inventory, copy.inventory);
Collections.copy(previousInventory, copy.previousInventory);
Collections.copy(inventorySnapshot, copy.inventorySnapshot);
inventoryChanged = copy.inventoryChanged;
brain = copy.brain;
brain.setOwner(this);

View File

@@ -0,0 +1,27 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2022. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.shared.turtle.core;
import dan200.computercraft.api.turtle.ITurtleAccess;
import net.minecraft.world.item.ItemStack;
/**
* An internal version of {@link ITurtleAccess}.
* <p>
* This exposes additional functionality we don't want in the public API, but where we don't want access to the full
* {@link TurtleBrain} interface.
*/
public interface TurtleAccessInternal extends ITurtleAccess {
/**
* Get an immutable snapshot of an item in the inventory. This is a thread-safe version of
* {@code getInventory().getItem()}.
*
* @param slot The slot
* @return The current item. This should NOT be modified.
* @see net.minecraft.world.Container#getItem(int)
*/
ItemStack getItemSnapshot(int slot);
}

View File

@@ -10,7 +10,10 @@ import com.mojang.authlib.GameProfile;
import dan200.computercraft.api.lua.ILuaCallback;
import dan200.computercraft.api.lua.MethodResult;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.api.turtle.*;
import dan200.computercraft.api.turtle.ITurtleUpgrade;
import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommand;
import dan200.computercraft.api.turtle.TurtleSide;
import dan200.computercraft.core.computer.ComputerSide;
import dan200.computercraft.core.util.Colour;
import dan200.computercraft.impl.TurtleUpgrades;
@@ -21,7 +24,6 @@ import dan200.computercraft.shared.container.InventoryDelegate;
import dan200.computercraft.shared.turtle.blocks.TurtleBlockEntity;
import dan200.computercraft.shared.util.BlockEntityHelpers;
import dan200.computercraft.shared.util.Holiday;
import dan200.computercraft.shared.util.HolidayUtil;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
@@ -34,6 +36,7 @@ import net.minecraft.world.Container;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.item.DyeColor;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.phys.AABB;
@@ -47,7 +50,7 @@ import java.util.function.Predicate;
import static dan200.computercraft.shared.common.IColouredItem.NBT_COLOUR;
import static dan200.computercraft.shared.util.WaterloggableHelpers.WATERLOGGED;
public class TurtleBrain implements ITurtleAccess {
public class TurtleBrain implements TurtleAccessInternal {
public static final String NBT_RIGHT_UPGRADE = "RightUpgrade";
public static final String NBT_RIGHT_UPGRADE_DATA = "RightUpgradeNbt";
public static final String NBT_LEFT_UPGRADE = "LeftUpgrade";
@@ -456,7 +459,7 @@ public class TurtleBrain implements ITurtleAccess {
return overlay;
}
public void setOverlay(ResourceLocation overlay) {
public void setOverlay(@Nullable ResourceLocation overlay) {
if (!Objects.equal(this.overlay, overlay)) {
this.overlay = overlay;
BlockEntityHelpers.updateBlock(owner);
@@ -735,7 +738,7 @@ public class TurtleBrain implements ITurtleAccess {
// Advance valentines day easter egg
if (world.isClientSide && animation == TurtleAnimation.MOVE_FORWARD && animationProgress == 4) {
// Spawn love pfx if valentines day
var currentHoliday = HolidayUtil.getCurrentHoliday();
var currentHoliday = Holiday.getCurrent();
if (currentHoliday == Holiday.VALENTINES) {
var position = getVisualPosition(1.0f);
if (position != null) {
@@ -768,6 +771,11 @@ public class TurtleBrain implements ITurtleAccess {
return previous + (next - previous) * f;
}
@Override
public ItemStack getItemSnapshot(int slot) {
return owner.getItemSnapshot(slot);
}
private static final class CommandCallback implements ILuaCallback {
final MethodResult pull = MethodResult.pullEvent("turtle_response", this);
private final int command;

View File

@@ -8,7 +8,6 @@ package dan200.computercraft.shared.turtle.core;
import dan200.computercraft.api.turtle.*;
import dan200.computercraft.impl.TurtleUpgrades;
import dan200.computercraft.shared.turtle.TurtleUtil;
import net.minecraft.world.item.ItemStack;
public class TurtleEquipCommand implements TurtleCommand {
private final TurtleSide side;
@@ -19,32 +18,22 @@ public class TurtleEquipCommand implements TurtleCommand {
@Override
public TurtleCommandResult execute(ITurtleAccess turtle) {
// Determine the upgrade to replace
var oldUpgrade = turtle.getUpgrade(side);
// Determine the upgrade to equipLeft
ITurtleUpgrade newUpgrade;
ItemStack newUpgradeStack;
var selectedStack = turtle.getInventory().getItem(turtle.getSelectedSlot());
if (!selectedStack.isEmpty()) {
newUpgradeStack = selectedStack.copy();
newUpgrade = TurtleUpgrades.instance().get(newUpgradeStack);
newUpgrade = TurtleUpgrades.instance().get(selectedStack);
if (newUpgrade == null) return TurtleCommandResult.failure("Not a valid upgrade");
} else {
newUpgradeStack = null;
newUpgrade = null;
}
// Determine the upgrade to replace
ItemStack oldUpgradeStack;
var oldUpgrade = turtle.getUpgrade(side);
if (oldUpgrade != null) {
var craftingItem = oldUpgrade.getCraftingItem();
oldUpgradeStack = !craftingItem.isEmpty() ? craftingItem.copy() : null;
} else {
oldUpgradeStack = null;
}
// Do the swapping:
if (newUpgradeStack != null) turtle.getInventory().removeItem(turtle.getSelectedSlot(), 1);
if (oldUpgradeStack != null) TurtleUtil.storeItemOrDrop(turtle, oldUpgradeStack);
if (newUpgrade != null) turtle.getInventory().removeItem(turtle.getSelectedSlot(), 1);
if (oldUpgrade != null) TurtleUtil.storeItemOrDrop(turtle, oldUpgrade.getCraftingItem().copy());
turtle.setUpgrade(side, newUpgrade);
// Animate

View File

@@ -6,6 +6,7 @@
package dan200.computercraft.shared.turtle.core;
import com.google.common.base.Splitter;
import dan200.computercraft.api.ComputerCraftTags;
import dan200.computercraft.api.turtle.ITurtleAccess;
import dan200.computercraft.api.turtle.TurtleAnimation;
import dan200.computercraft.api.turtle.TurtleCommand;
@@ -21,9 +22,7 @@ import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SignItem;
import net.minecraft.world.item.*;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
@@ -209,7 +208,7 @@ public class TurtlePlaceCommand implements TurtleCommand {
// We special case some items which we allow to place "normally". Yes, this is very ugly.
var item = stack.getItem();
if (item.getUseDuration(stack) == 0) {
if (item instanceof BucketItem || item instanceof PlaceOnWaterBlockItem || stack.is(ComputerCraftTags.Items.TURTLE_CAN_PLACE)) {
return turtlePlayer.player().gameMode.useItem(turtlePlayer.player(), turtlePlayer.player().level, stack, InteractionHand.MAIN_HAND);
}

View File

@@ -5,10 +5,30 @@
*/
package dan200.computercraft.shared.util;
import java.time.LocalDateTime;
import java.time.Month;
public enum Holiday {
NONE,
/**
* 14th February.
*/
VALENTINES,
APRIL_FOOLS_DAY,
HALLOWEEN,
CHRISTMAS,
/**
* 24th-26th December.
*
* @see net.minecraft.client.renderer.blockentity.ChestRenderer
*/
CHRISTMAS;
public static Holiday getCurrent() {
var calendar = LocalDateTime.now();
var month = calendar.getMonth();
var day = calendar.getDayOfMonth();
if (month == Month.FEBRUARY && day == 14) return VALENTINES;
if (month == Month.DECEMBER && day >= 24 && day <= 26) return CHRISTMAS;
return NONE;
}
}

View File

@@ -1,27 +0,0 @@
/*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2022. Do not distribute without permission.
* Send enquiries to dratcliffe@gmail.com
*/
package dan200.computercraft.shared.util;
import java.util.Calendar;
public final class HolidayUtil {
private HolidayUtil() {
}
public static Holiday getCurrentHoliday() {
return getHoliday(Calendar.getInstance());
}
private static Holiday getHoliday(Calendar calendar) {
var month = calendar.get(Calendar.MONTH);
var day = calendar.get(Calendar.DAY_OF_MONTH);
if (month == Calendar.FEBRUARY && day == 14) return Holiday.VALENTINES;
if (month == Calendar.APRIL && day == 1) return Holiday.APRIL_FOOLS_DAY;
if (month == Calendar.OCTOBER && day == 31) return Holiday.HALLOWEEN;
if (month == Calendar.DECEMBER && day >= 24 && day <= 30) return Holiday.CHRISTMAS;
return Holiday.NONE;
}
}

View File

@@ -178,8 +178,8 @@ public final class WorldUtil {
}
@Override
public VoxelShape getBlockShape(BlockState state, BlockGetter levle, BlockPos pos) {
return block.get(state, levle, pos, CollisionContext.empty());
public VoxelShape getBlockShape(BlockState state, BlockGetter level, BlockPos pos) {
return block.get(state, level, pos, CollisionContext.empty());
}
}
}

View File

@@ -143,5 +143,44 @@
"gui.computercraft.config.term_sizes.computer.width.tooltip": "Intervallo: 1 ~ 255",
"gui.computercraft.config.turtle.need_fuel.tooltip": "Imposta se la Tartaruga richiede del carburante per muoversi.",
"gui.computercraft.config.command_require_creative": "Il computer Comando richiede la modalità creativa",
"tracking_field.computercraft.http_requests.name": "Richieste HTTP"
"tracking_field.computercraft.http_requests.name": "Richieste HTTP",
"gui.computercraft.config.command_require_creative.tooltip": "Richiede che i giocatori siano in modalità creativa e che siano operatori in ordine per interagire con\ni computer di commando. Questo è il comportamento predefinito dei blocchi di comando.",
"gui.computercraft.config.disable_lua51_features.tooltip": "Imposta a \"true\" per disattivare le funzionalità di Lua 5.1 che saranno rimosse in un\naggiornamento futuro. Utile per assicurare futura compatibilità con i tuoi programmi.",
"gui.computercraft.config.execution": "Esecuzione",
"gui.computercraft.config.execution.max_main_computer_time": "Limite di tempo nei tick del server dei computer",
"gui.computercraft.config.execution.max_main_computer_time.tooltip": "Il tempo massimo ideale che un computer può eseguire in un tick, in millisecondi.\nNota, potremmo andare ben sopra questo limite, perché non c'è modo di sapere\nquanto impiega, questa configurazione mira ad essere il limite maggiore del tempo medio.\nRange: > 1",
"gui.computercraft.config.execution.max_main_global_time": "Limite tempo globale dei tick del server",
"gui.computercraft.config.execution.tooltip": "Controlla comportamento esecuzione dei computer. Questo è largamente utilizzato\nper ritoccare la performance dei server, e generale non dovrebbe essere toccato.",
"gui.computercraft.config.floppy_space_limit.tooltip": "Limite di spazio di archiviazione per i dischi floppy, in byte.",
"gui.computercraft.config.http.bandwidth": "Banda larga",
"gui.computercraft.config.http.bandwidth.global_download": "Limite download globale",
"gui.computercraft.config.http.bandwidth.global_download.tooltip": "Numero di byte che possono essere scaricati in un secondo. Questo è condiviso tra tutti i computer. (bytes/s).\nRange: > 1",
"gui.computercraft.config.http.bandwidth.global_upload": "Limite upload globale",
"gui.computercraft.config.http.bandwidth.global_upload.tooltip": "Numero di byte che possono essere caricati in un secondo. Questo è condiviso tra tutti i computer. (bytes/s).\nRange: > 1",
"gui.computercraft.config.http.bandwidth.tooltip": "Limita la banda larga usato dai computer.",
"gui.computercraft.config.http.max_requests.tooltip": "Il numero di richieste http che un computer può fare alla volta. Ulteriori richieste\nverranno messe in coda, ed inviate quando le richieste correnti sono terminate.\nImposta a 0 per illimitato.\nRange: > 0",
"gui.computercraft.config.http.max_websockets.tooltip": "Il numero di websocket che un computer può avere aperte allo stesso momento.\nImposta a 0 per illimitato.\nRange: > 1",
"gui.computercraft.config.http.rules": "Concedi/nega regole",
"gui.computercraft.config.maximum_open_files.tooltip": "Imposta quanti file possono essere aperti allo stesso momento su un computer. Imposta a 0 per illimitato.\nRange: > 0",
"gui.computercraft.config.monitor_distance": "Distanza monitor",
"gui.computercraft.config.monitor_distance.tooltip": "Distanza massima che i monitor vengono renderizzati. Questo è predefinito al limite\nstandard dei tile entity, ma può essere esteso se desideri construire monitor più grandi.\nRange: 16 ~ 1024",
"gui.computercraft.config.monitor_renderer": "Renderizzatore monitor",
"gui.computercraft.config.peripheral.command_block_enabled.tooltip": "Attiva il supporto ai blocchi di comando come periferiche",
"gui.computercraft.config.peripheral.max_notes_per_tick.tooltip": "Quantità massima di note che un altoparlante può riprodurre allo stesso momento.\nRange: > 1",
"gui.computercraft.config.peripheral.modem_high_altitude_range.tooltip": "La distanza massima dei modem wireless all'altitudine massima durante il meteo soleggiato. in metri.\nRange: 0 ~ 100000",
"gui.computercraft.config.peripheral.modem_high_altitude_range_during_storm.tooltip": "La distanza massima dei modem wireless all'altitudine massima durante una tempesta. in metri.\nRange: 0 ~ 100000",
"gui.computercraft.config.peripheral.modem_range.tooltip": "La distanza massima dei modem wireless ad altitudini basse durante il meteo soleggiato. in metri.\nRange: 0 ~ 100000",
"gui.computercraft.config.peripheral.modem_range_during_storm.tooltip": "La distanza massima dei modem wireless ad altitudini basse durante una tempesta. in metri.\nRange: 0 ~ 100000",
"gui.computercraft.config.peripheral.monitor_bandwidth": "Banda larga monitor",
"gui.computercraft.config.computer_space_limit.tooltip": "Limite di spazio di archiviazione per i computer e le tartarughe, in byte.",
"gui.computercraft.config.default_computer_settings.tooltip": "Una lista di impostazioni predefinite per i nuovi computer, separate da virgola.\nEsempio: \"shell.autocomplete=false,lua.autocomplete=false,edit.autocomplete=false\"\ndisattiverà tutti gli autocompletamenti.",
"gui.computercraft.config.execution.computer_threads.tooltip": "Imposta la quantità di thread che possono eseguire i computer. Un numero più alto significa\nche più computer possono essere eseguiti alla volta, ma può indurre a lag. Alcune mod potrebbero\nnon funzionare con numeri di thread maggiore a 1. Usare con cautela.\nRange: > 1",
"gui.computercraft.config.execution.max_main_global_time.tooltip": "Il limite massimo di tempo che può essere usato per eseguire task in un singolo tick,\nin millisecondi.\nNota, potremmo andare ben sopra questo limite, perché non c'è modo di sapere\nquanto impiega, questa configurazione mira ad essere il limite maggiore del tempo medio.\nRange: > 1",
"gui.computercraft.config.http.enabled.tooltip": "Attiva l'API \"http\" sui computer. Questo disabilita i programmi \"pastebin\" e \"wget\", \nche molti utenti dipendono. È raccomandato lasciarlo attivo ed utlizzare l'opzione \n\"rules\" per imporre controlli più adeguati.",
"gui.computercraft.config.http.rules.tooltip": "Una lista di regole che controllano il comportamento dell'API \"http\" per specifici domini\no indirizzi IP. Ogni regola è un elemento con un 'host' da confrontare, e una serie di\nproprietà. Le regole sono valutate in ordine, cioè le prime regole sovvrascrivono le successive.\nL'host può essere un dominio (\"pastebin.com\"), wildcard (\"*.pastebin.com\") oppure\nuna notazione CIDR (\"127.0.0.0/8\").\nSe non è presente nessuna regola, il dominio è bloccato.",
"gui.computercraft.config.http.tooltip": "Controlla l'API HTTP",
"gui.computercraft.config.http.websocket_enabled.tooltip": "Attiva l'uso di websocket http. Questo richiede che l'opzione \"http_enable\" sia attiva.",
"gui.computercraft.config.log_computer_errors.tooltip": "Registra le eccezioni lanciate dalle periferiche e altri oggetti di Lua. Questo rende più facile\nper gli autori di mod per il debug di problemi, ma potrebbe risultare in spam di log durante\nl'uso di metodi buggati.",
"gui.computercraft.config.monitor_renderer.tooltip": "Il renderizzatore da usare per i monitor. Generalmente si dovrebbe lasciare su \"best\", se\ni monitor hanno problemi di performance, puoi sperimentare con renderizzatori alternativi.\nValori concessi: BEST, TBO, VBO",
"gui.computercraft.config.peripheral.monitor_bandwidth.tooltip": "Il limite di quanti dati dei monitor possono essere inviati *al tick*. Nota:\n - La banda larga è misurata prima della compressione, così che il dato inviato al client è\n più piccolo."
}

View File

@@ -0,0 +1,128 @@
{
"block.computercraft.disk_drive": "tomo pi lipu sona",
"block.computercraft.printer": "ilo sitelen",
"block.computercraft.monitor_normal": "ilo lukin",
"block.computercraft.monitor_advanced": "ilo lukin wawa",
"block.computercraft.speaker": "ilo kalama",
"commands.computercraft.generic.exception": "pakala awen ala (%s)",
"block.computercraft.computer_command": "ilo sona pi toki wawa",
"block.computercraft.turtle_advanced": "ilo sona pali wawa",
"block.computercraft.turtle_normal": "ilo sona pali",
"block.computercraft.computer_advanced": "ilo sona wawa",
"block.computercraft.computer_normal": "ilo sona",
"argument.computercraft.argument_expected": "mi wile e ijo",
"block.computercraft.turtle_advanced.upgraded": "ilo sona pali wawa (%s)",
"block.computercraft.turtle_normal.upgraded": "ilo sona pali (%s)",
"commands.computercraft.dump.action": "o lukin e sona mute pi ilo sona ni",
"commands.computercraft.generic.no_position": "<lon ala>",
"chat.computercraft.wired_modem.peripheral_connected": "ijo sona \"%s\" li linja tawa kulupu",
"chat.computercraft.wired_modem.peripheral_disconnected": "ijo sona \"%s\" li linja ala tawa kulupu",
"block.computercraft.wired_modem": "ilo toki linja",
"block.computercraft.wired_modem_full": "ilo toki linja",
"block.computercraft.wireless_modem_normal": "ilo toki linja ala",
"commands.computercraft.generic.additional_rows": "mute %d…",
"argument.computercraft.computer.no_matching": "mi ken ala alasa e ilo sona pi nimi '%s'",
"commands.computercraft.dump.open_path": "o lukin e lipu pi ilo sona ni",
"commands.computercraft.dump.synopsis": "mi pana e sona pi ilo sona.",
"block.computercraft.cable": "linja toki",
"block.computercraft.wireless_modem_advanced": "ilo toki pi ma End",
"commands.computercraft.generic.position": "%s, %s, %s",
"commands.computercraft.help.no_children": "toki wawa '%s' li jo ala e toki wawa insa",
"commands.computercraft.help.no_command": "toki wawa '%s' li lon ala",
"commands.computercraft.help.desc": "mi pana e toki ni",
"commands.computercraft.help.synopsis": "mi pana e sona pi toki wawa ale",
"commands.computercraft.reload.done": "mi kama open sin e ante nasin",
"commands.computercraft.shutdown.done": "mi kama pini e ilo sona %s/%s",
"commands.computercraft.shutdown.synopsis": "mi pini weka e ilo sona.",
"commands.computercraft.queue.synopsis": "mi pana e toki computer_command tawa ilo sona pi toki wawa",
"commands.computercraft.tp.desc": "o tawa ilo sona. ilo sona la, sina ken pana e nanpa pi ijo (sama 123) anu nanpa (sama #123).",
"commands.computercraft.synopsis": "mi jo e toki wawa ante tawa ni: sina lawa e ilo sona.",
"commands.computercraft.tp.action": "o tawa pi ilo sona",
"commands.computercraft.tp.not_player": "jan ala la, mi ken ala open e sitelen pi ilo sona",
"commands.computercraft.track.dump.computer": "ilo sona",
"commands.computercraft.tp.synopsis": "mi tawa pi ilo sona e sina.",
"commands.computercraft.tp.not_there": "mi ken ala alasa e ilo sona pi lon ma",
"commands.computercraft.track.desc": "ilo sona la, mi sitelen e tenpo pali e mute toki. toki wawa /forge track la, mi pana pi nasin sama e sona. mi pona tawa alasa pi tenpo ike.",
"commands.computercraft.track.dump.no_timings": "mi ken ala alasa e tenpo",
"commands.computercraft.track.stop.synopsis": "mi pini e sitelen sona ale",
"commands.computercraft.track.start.synopsis": "mi open sitelen sona e ilo sona ale",
"commands.computercraft.track.stop.action": "o luka tawa ni: mi pini sitelen sona",
"commands.computercraft.track.stop.not_enabled": "tenpo ni la, mi sitelen ala sona e ilo sona",
"commands.computercraft.track.dump.synopsis": "mi pana e sona tan sitelen sona pi sin mute",
"commands.computercraft.track.stop.desc": "ilo sona la, mi pini sitelen sona e tenpo pali e mute toki",
"commands.computercraft.track.synopsis": "mi sitelen tenpo pali e ilo sona.",
"commands.computercraft.track.dump.desc": "mi pana e sona tan sitelen sona pi sin mute.",
"commands.computercraft.view.action": "o lukin e ilo sona ni",
"commands.computercraft.view.synopsis": "o lukin e sitelen pi ilo sona.",
"commands.computercraft.turn_on.done": "mi kama open e ilo sona %s/%s",
"commands.computercraft.turn_on.synopsis": "mi open weka e ilo sona.",
"commands.computercraft.view.not_player": "jan ala la, mi ken ala open e sitelen pi ilo sona",
"gui.computercraft.config.command_require_creative": "ilo sona pi toki wawa li wile e jan sewi",
"gui.computercraft.config.execution.computer_threads": "linja pi ilo sona",
"gui.computercraft.config.http.bandwidth": "mute sona",
"gui.computercraft.config.http": "ijo HTTP",
"gui.computercraft.config.execution": "pali",
"gui.computercraft.config.monitor_renderer": "nasin sitelen pi ilo lukin",
"gui.computercraft.config.term_sizes.pocket_computer.width": "suli poka pi ilo sitelen",
"gui.computercraft.config.term_sizes": "suli pi ilo sitelen",
"gui.computercraft.config.term_sizes.computer": "ilo sona",
"gui.computercraft.config.term_sizes.monitor": "ilo lukin",
"gui.computercraft.config.term_sizes.pocket_computer": "ilo sona lili",
"gui.computercraft.config.term_sizes.pocket_computer.height": "suli sewi pi ilo sitelen",
"gui.computercraft.config.term_sizes.computer.height": "suli sewi pi ilo sitelen",
"gui.computercraft.config.term_sizes.computer.width": "suli poka pi ito sitelen",
"gui.computercraft.config.term_sizes.computer.tooltip": "suli pi ilo sitelen pi ilo sona.",
"gui.computercraft.config.peripheral.monitor_bandwidth": "mute sona pi ilo lukin",
"gui.computercraft.config.peripheral.modem_range": "suli ken ilo pi ilo toki (pona)",
"gui.computercraft.config.peripheral.modem_high_altitude_range": "suli ken ilo pi ilo toki (sewi mute)",
"item.computercraft.printed_page": "lipu pi ilo sitelen",
"item.computercraft.printed_pages": "lipu mute pi ilo sitelen",
"item.computercraft.treasure_disk": "lipu sona",
"gui.computercraft.tooltip.turn_on": "o open e ilo sona ni",
"gui.computercraft.tooltip.computer_id": "nanpa pi ilo sona: %s",
"gui.computercraft.tooltip.turn_off": "o pini e ilo sona ni",
"item.computercraft.pocket_computer_advanced": "ilo sona lili wawa",
"item.computercraft.pocket_computer_advanced.upgraded": "ilo sona lili wawa (%s)",
"item.computercraft.pocket_computer_normal": "ilo sona lili",
"item.computercraft.pocket_computer_normal.upgraded": "ilo sona lili (%s)",
"gui.computercraft.terminal": "ilo sitelen pi ilo sona",
"itemGroup.computercraft": "ComputerCraft",
"tracking_field.computercraft.computer_tasks.name": "pali",
"tracking_field.computercraft.turtle_ops.name": "pali pi ilo sona pali",
"upgrade.computercraft.speaker.adjective": "kalama",
"tracking_field.computercraft.count": "%s (mute)",
"tracking_field.computercraft.coroutines_created.name": "open linja",
"tracking_field.computercraft.coroutines_dead.name": "pini linja",
"tracking_field.computercraft.max": "%s (sewi)",
"upgrade.minecraft.crafting_table.adjective": "pali",
"upgrade.minecraft.diamond_axe.adjective": "ilo kipisi",
"upgrade.minecraft.diamond_hoe.adjective": "ilo kasi",
"upgrade.computercraft.wireless_modem_normal.adjective": "toki linja ala",
"upgrade.minecraft.diamond_pickaxe.adjective": "ilo pakala",
"upgrade.minecraft.diamond_shovel.adjective": "ilo ma",
"upgrade.minecraft.diamond_sword.adjective": "utala",
"block.computercraft.turtle_advanced.upgraded_twice": "ilo sona pali wawa (%s, %s)",
"block.computercraft.turtle_normal.upgraded_twice": "ilo sona pali (%s, %s)",
"gui.computercraft.config.turtle": "ilo sona pali",
"item.computercraft.disk": "lipu sona",
"item.computercraft.printed_book": "lipu suli pi ilo sitelen",
"upgrade.computercraft.wireless_modem_advanced.adjective": "toki pi ma End",
"gui.computercraft.tooltip.disk_id": "nanpa pi lipu sona: %s",
"gui.computercraft.config.peripheral": "ijo sona",
"gui.computercraft.config.peripheral.modem_range_during_storm": "suli ken ilo pi ilo toki (sewi ike)",
"argument.computercraft.tracking_field.no_field": "mi sona ala e nimi '%s'",
"argument.computercraft.computer.many_matching": "mi alasa e ilo sona mute pi nimi '%s' (ijo %s)",
"commands.computercraft.desc": "ilo sona la, toki wawa /computercraft li lawa li luka li pakala ala.",
"commands.computercraft.reload.desc": "mi open sin e ante nasin",
"commands.computercraft.reload.synopsis": "mi open sin e ante nasin",
"commands.computercraft.shutdown.desc": "mi pini e ilo sona pi pana sina anu ale. ilo sona la, sina ken pana e nanpa pi ijo (sama 123) anu nanpa (sama #123) anu nimi (sama \"@ilo sona mi\").",
"gui.computercraft.config.term_sizes.pocket_computer.tooltip": "suli pi ilo sitelen pi ilo sona lili.",
"gui.computercraft.config.peripheral.modem_high_altitude_range_during_storm": "suli ken ilo pi ilo toki (sewi mute, sewi ike)",
"gui.computercraft.pocket_computer_overlay": "sina open e ilo sona lili. o luka e nena ESC tawa pini.",
"commands.computercraft.dump.desc": "sona pi ilo sona la, mi pana e ale anu wan. ilo sona la, sina ken pana e nanpa pi ijo (sama 123) anu nanpa (sama #123) anu nimi (sama \"@ilo sona mi\").",
"commands.computercraft.turn_on.desc": "mi open e ilo sona pi pana sina. ilo sona la, sina ken pana e nanpa pi ijo (sama 123) anu nanpa (sama #123) anu nimi (sama \"@ilo sona mi\").",
"commands.computercraft.track.start.stop": "o toki wawa %s tawa ni: sina pini sitelen sona. sina lukin e sona ni",
"commands.computercraft.track.start.desc": "ilo sona la, mi open sitelen sona e tenpo pali e mute toki. mi weka e sitelen sona pini.",
"commands.computercraft.view.desc": "mi open e sitelen pi ilo sona tawa ni: sina lawa weka e ilo sona. taso, sina ken ala open e jo pi ilo sona pali. ilo sona la, sina ken pana e nanpa pi ijo (sama 123) anu nanpa (sama #123).",
"gui.computercraft.config.disable_lua51_features": "ijo pona pi ilo Lua 5.1 li weka"
}

View File

@@ -8,6 +8,7 @@ package dan200.computercraft.gametest.core;
import com.mojang.brigadier.CommandDispatcher;
import dan200.computercraft.api.ComputerCraftAPI;
import dan200.computercraft.mixin.gametest.TestCommandAccessor;
import dan200.computercraft.shared.ModRegistry;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.gametest.framework.GameTestRegistry;
@@ -81,6 +82,27 @@ class CCTestCommand {
player.getLevel().addFreshEntity(armorStand);
return 0;
}))
.then(literal("give-computer").executes(context -> {
var player = context.getSource().getPlayerOrException();
var pos = StructureUtils.findNearestStructureBlock(player.blockPosition(), 15, player.getLevel());
if (pos == null) return error(context.getSource(), "No nearby test");
var structureBlock = (StructureBlockEntity) player.getLevel().getBlockEntity(pos);
if (structureBlock == null) return error(context.getSource(), "No nearby structure block");
var info = GameTestRegistry.getTestFunction(structureBlock.getStructurePath());
var item = ModRegistry.Items.COMPUTER_ADVANCED.get().create(1, info.getTestName());
if (!player.getInventory().add(item)) {
var itemEntity = player.drop(item, false);
if (itemEntity != null) {
itemEntity.setNoPickUpDelay();
itemEntity.setOwner(player.getUUID());
}
}
return 1;
}))
);
}

View File

@@ -8,6 +8,7 @@ package dan200.computercraft.gametest
import dan200.computercraft.core.apis.FSAPI
import dan200.computercraft.gametest.api.*
import dan200.computercraft.shared.ModRegistry
import dan200.computercraft.shared.media.items.DiskItem
import dan200.computercraft.shared.peripheral.diskdrive.DiskDriveBlock
import dan200.computercraft.shared.peripheral.diskdrive.DiskDriveState
import dan200.computercraft.test.core.assertArrayEquals
@@ -45,10 +46,14 @@ class Disk_Drive_Test {
thenWaitUntil { helper.assertItemEntityPresent(Items.MUSIC_DISC_13, stackAt, 0.0) }
}
/**
* A mount is initially attached, and then removed when the disk is ejected.
*/
@GameTest
fun Adds_removes_mount(helper: GameTestHelper) = helper.sequence {
thenIdle(2)
thenOnComputer {
thenOnComputer { } // Wait for the computer to start up
thenIdle(2) // Let the disk drive tick once to create the mount
thenOnComputer { // Then actually assert things!
getApi<FSAPI>().getDrive("disk").assertArrayEquals("right")
callPeripheral("right", "ejectDisk")
}
@@ -56,6 +61,18 @@ class Disk_Drive_Test {
thenOnComputer { assertEquals(null, getApi<FSAPI>().getDrive("disk")) }
}
/**
* When creating a new mount, the item is with a new disk ID.
*/
@GameTest
fun Creates_disk_id(helper: GameTestHelper) = helper.sequence {
val drivePos = BlockPos(2, 2, 2)
thenWaitUntil {
val drive = helper.getBlockEntity(drivePos, ModRegistry.BlockEntities.DISK_DRIVE.get())
if (DiskItem.getDiskID(drive.getItem(0)) == -1) helper.fail("Disk has no item", drivePos)
}
}
/**
* Check comparators can read the contents of the disk drive
*/

View File

@@ -63,7 +63,7 @@ class Monitor_Test {
}
/**
* Test
* Test monitors render correctly
*/
@GameTestGenerator
fun Render_monitor_tests(): List<TestFunction> {
@@ -72,7 +72,7 @@ class Monitor_Test {
fun addTest(label: String, renderer: MonitorRenderer, time: Long = Times.NOON, tag: String = TestTags.CLIENT) {
if (!TestTags.isEnabled(tag)) return
val className = Monitor_Test::class.java.simpleName.lowercase()
val className = this::class.java.simpleName.lowercase()
val testName = "$className.render_monitor"
tests.add(

View File

@@ -0,0 +1,53 @@
package dan200.computercraft.gametest
import dan200.computercraft.gametest.api.*
import net.minecraft.gametest.framework.GameTestGenerator
import net.minecraft.gametest.framework.GameTestHelper
import net.minecraft.gametest.framework.TestFunction
class Printout_Test {
/**
* Test printouts render correctly
*/
@GameTestGenerator
fun Render_in_frame(): List<TestFunction> {
val tests = mutableListOf<TestFunction>()
fun addTest(label: String, time: Long = Times.NOON, tag: String = TestTags.CLIENT) {
if (!TestTags.isEnabled(tag)) return
val className = this::class.java.simpleName.lowercase()
val testName = "$className.render_in_frame"
tests.add(
TestFunction(
"$testName.$label",
"$testName.$label",
testName,
Timeouts.DEFAULT,
0,
true,
) { renderPrintout(it, time) },
)
}
addTest("noon", Times.NOON)
addTest("midnight", Times.MIDNIGHT)
addTest("sodium", tag = "sodium")
addTest("iris_noon", Times.NOON, tag = "iris")
addTest("iris_midnight", Times.MIDNIGHT, tag = "iris")
return tests
}
private fun renderPrintout(helper: GameTestHelper, time: Long) = helper.sequence {
thenExecute {
helper.level.dayTime = time
helper.positionAtArmorStand()
}
thenScreenshot()
}
}

View File

@@ -80,6 +80,7 @@ object TestHooks {
Monitor_Test::class.java,
Pocket_Computer_Test::class.java,
Printer_Test::class.java,
Printout_Test::class.java,
Recipe_Test::class.java,
Turtle_Test::class.java,
)

View File

@@ -0,0 +1,138 @@
{
DataVersion: 3218,
size: [5, 5, 5],
data: [
{pos: [0, 0, 0], state: "minecraft:polished_andesite"},
{pos: [0, 0, 1], state: "minecraft:polished_andesite"},
{pos: [0, 0, 2], state: "minecraft:polished_andesite"},
{pos: [0, 0, 3], state: "minecraft:polished_andesite"},
{pos: [0, 0, 4], state: "minecraft:polished_andesite"},
{pos: [1, 0, 0], state: "minecraft:polished_andesite"},
{pos: [1, 0, 1], state: "minecraft:polished_andesite"},
{pos: [1, 0, 2], state: "minecraft:polished_andesite"},
{pos: [1, 0, 3], state: "minecraft:polished_andesite"},
{pos: [1, 0, 4], state: "minecraft:polished_andesite"},
{pos: [2, 0, 0], state: "minecraft:polished_andesite"},
{pos: [2, 0, 1], state: "minecraft:polished_andesite"},
{pos: [2, 0, 2], state: "minecraft:polished_andesite"},
{pos: [2, 0, 3], state: "minecraft:polished_andesite"},
{pos: [2, 0, 4], state: "minecraft:polished_andesite"},
{pos: [3, 0, 0], state: "minecraft:polished_andesite"},
{pos: [3, 0, 1], state: "minecraft:polished_andesite"},
{pos: [3, 0, 2], state: "minecraft:polished_andesite"},
{pos: [3, 0, 3], state: "minecraft:polished_andesite"},
{pos: [3, 0, 4], state: "minecraft:polished_andesite"},
{pos: [4, 0, 0], state: "minecraft:polished_andesite"},
{pos: [4, 0, 1], state: "minecraft:polished_andesite"},
{pos: [4, 0, 2], state: "minecraft:polished_andesite"},
{pos: [4, 0, 3], state: "minecraft:polished_andesite"},
{pos: [4, 0, 4], state: "minecraft:polished_andesite"},
{pos: [0, 1, 0], state: "minecraft:air"},
{pos: [0, 1, 1], state: "minecraft:air"},
{pos: [0, 1, 2], state: "minecraft:air"},
{pos: [0, 1, 3], state: "minecraft:air"},
{pos: [0, 1, 4], state: "minecraft:air"},
{pos: [1, 1, 0], state: "minecraft:air"},
{pos: [1, 1, 1], state: "minecraft:air"},
{pos: [1, 1, 2], state: "computercraft:computer_advanced{facing:north,state:on}", nbt: {ComputerId: 1, Label: "disk_drive_test.creates_disk_id", On: 1b, id: "computercraft:computer_advanced"}},
{pos: [1, 1, 3], state: "minecraft:air"},
{pos: [1, 1, 4], state: "minecraft:air"},
{pos: [2, 1, 0], state: "minecraft:air"},
{pos: [2, 1, 1], state: "minecraft:air"},
{pos: [2, 1, 2], state: "computercraft:disk_drive{facing:north,state:full}", nbt: {Item: {Count: 1b, id: "computercraft:disk", tag: {Color: 1118481}}, id: "computercraft:disk_drive"}},
{pos: [2, 1, 3], state: "minecraft:air"},
{pos: [2, 1, 4], state: "minecraft:air"},
{pos: [3, 1, 0], state: "minecraft:air"},
{pos: [3, 1, 1], state: "minecraft:air"},
{pos: [3, 1, 2], state: "minecraft:air"},
{pos: [3, 1, 3], state: "minecraft:air"},
{pos: [3, 1, 4], state: "minecraft:air"},
{pos: [4, 1, 0], state: "minecraft:air"},
{pos: [4, 1, 1], state: "minecraft:air"},
{pos: [4, 1, 2], state: "minecraft:air"},
{pos: [4, 1, 3], state: "minecraft:air"},
{pos: [4, 1, 4], state: "minecraft:air"},
{pos: [0, 2, 0], state: "minecraft:air"},
{pos: [0, 2, 1], state: "minecraft:air"},
{pos: [0, 2, 2], state: "minecraft:air"},
{pos: [0, 2, 3], state: "minecraft:air"},
{pos: [0, 2, 4], state: "minecraft:air"},
{pos: [1, 2, 0], state: "minecraft:air"},
{pos: [1, 2, 1], state: "minecraft:air"},
{pos: [1, 2, 2], state: "minecraft:air"},
{pos: [1, 2, 3], state: "minecraft:air"},
{pos: [1, 2, 4], state: "minecraft:air"},
{pos: [2, 2, 0], state: "minecraft:air"},
{pos: [2, 2, 1], state: "minecraft:air"},
{pos: [2, 2, 2], state: "minecraft:air"},
{pos: [2, 2, 3], state: "minecraft:air"},
{pos: [2, 2, 4], state: "minecraft:air"},
{pos: [3, 2, 0], state: "minecraft:air"},
{pos: [3, 2, 1], state: "minecraft:air"},
{pos: [3, 2, 2], state: "minecraft:air"},
{pos: [3, 2, 3], state: "minecraft:air"},
{pos: [3, 2, 4], state: "minecraft:air"},
{pos: [4, 2, 0], state: "minecraft:air"},
{pos: [4, 2, 1], state: "minecraft:air"},
{pos: [4, 2, 2], state: "minecraft:air"},
{pos: [4, 2, 3], state: "minecraft:air"},
{pos: [4, 2, 4], state: "minecraft:air"},
{pos: [0, 3, 0], state: "minecraft:air"},
{pos: [0, 3, 1], state: "minecraft:air"},
{pos: [0, 3, 2], state: "minecraft:air"},
{pos: [0, 3, 3], state: "minecraft:air"},
{pos: [0, 3, 4], state: "minecraft:air"},
{pos: [1, 3, 0], state: "minecraft:air"},
{pos: [1, 3, 1], state: "minecraft:air"},
{pos: [1, 3, 2], state: "minecraft:air"},
{pos: [1, 3, 3], state: "minecraft:air"},
{pos: [1, 3, 4], state: "minecraft:air"},
{pos: [2, 3, 0], state: "minecraft:air"},
{pos: [2, 3, 1], state: "minecraft:air"},
{pos: [2, 3, 2], state: "minecraft:air"},
{pos: [2, 3, 3], state: "minecraft:air"},
{pos: [2, 3, 4], state: "minecraft:air"},
{pos: [3, 3, 0], state: "minecraft:air"},
{pos: [3, 3, 1], state: "minecraft:air"},
{pos: [3, 3, 2], state: "minecraft:air"},
{pos: [3, 3, 3], state: "minecraft:air"},
{pos: [3, 3, 4], state: "minecraft:air"},
{pos: [4, 3, 0], state: "minecraft:air"},
{pos: [4, 3, 1], state: "minecraft:air"},
{pos: [4, 3, 2], state: "minecraft:air"},
{pos: [4, 3, 3], state: "minecraft:air"},
{pos: [4, 3, 4], state: "minecraft:air"},
{pos: [0, 4, 0], state: "minecraft:air"},
{pos: [0, 4, 1], state: "minecraft:air"},
{pos: [0, 4, 2], state: "minecraft:air"},
{pos: [0, 4, 3], state: "minecraft:air"},
{pos: [0, 4, 4], state: "minecraft:air"},
{pos: [1, 4, 0], state: "minecraft:air"},
{pos: [1, 4, 1], state: "minecraft:air"},
{pos: [1, 4, 2], state: "minecraft:air"},
{pos: [1, 4, 3], state: "minecraft:air"},
{pos: [1, 4, 4], state: "minecraft:air"},
{pos: [2, 4, 0], state: "minecraft:air"},
{pos: [2, 4, 1], state: "minecraft:air"},
{pos: [2, 4, 2], state: "minecraft:air"},
{pos: [2, 4, 3], state: "minecraft:air"},
{pos: [2, 4, 4], state: "minecraft:air"},
{pos: [3, 4, 0], state: "minecraft:air"},
{pos: [3, 4, 1], state: "minecraft:air"},
{pos: [3, 4, 2], state: "minecraft:air"},
{pos: [3, 4, 3], state: "minecraft:air"},
{pos: [3, 4, 4], state: "minecraft:air"},
{pos: [4, 4, 0], state: "minecraft:air"},
{pos: [4, 4, 1], state: "minecraft:air"},
{pos: [4, 4, 2], state: "minecraft:air"},
{pos: [4, 4, 3], state: "minecraft:air"},
{pos: [4, 4, 4], state: "minecraft:air"}
],
entities: [],
palette: [
"minecraft:polished_andesite",
"minecraft:air",
"computercraft:computer_advanced{facing:north,state:on}",
"computercraft:disk_drive{facing:north,state:full}"
]
}

View File

@@ -0,0 +1,139 @@
{
DataVersion: 3218,
size: [5, 5, 5],
data: [
{pos: [0, 0, 0], state: "minecraft:polished_andesite"},
{pos: [0, 0, 1], state: "minecraft:polished_andesite"},
{pos: [0, 0, 2], state: "minecraft:polished_andesite"},
{pos: [0, 0, 3], state: "minecraft:polished_andesite"},
{pos: [0, 0, 4], state: "minecraft:polished_andesite"},
{pos: [1, 0, 0], state: "minecraft:polished_andesite"},
{pos: [1, 0, 1], state: "minecraft:polished_andesite"},
{pos: [1, 0, 2], state: "minecraft:polished_andesite"},
{pos: [1, 0, 3], state: "minecraft:polished_andesite"},
{pos: [1, 0, 4], state: "minecraft:polished_andesite"},
{pos: [2, 0, 0], state: "minecraft:polished_andesite"},
{pos: [2, 0, 1], state: "minecraft:polished_andesite"},
{pos: [2, 0, 2], state: "minecraft:polished_andesite"},
{pos: [2, 0, 3], state: "minecraft:polished_andesite"},
{pos: [2, 0, 4], state: "minecraft:polished_andesite"},
{pos: [3, 0, 0], state: "minecraft:polished_andesite"},
{pos: [3, 0, 1], state: "minecraft:polished_andesite"},
{pos: [3, 0, 2], state: "minecraft:polished_andesite"},
{pos: [3, 0, 3], state: "minecraft:polished_andesite"},
{pos: [3, 0, 4], state: "minecraft:polished_andesite"},
{pos: [4, 0, 0], state: "minecraft:polished_andesite"},
{pos: [4, 0, 1], state: "minecraft:polished_andesite"},
{pos: [4, 0, 2], state: "minecraft:polished_andesite"},
{pos: [4, 0, 3], state: "minecraft:polished_andesite"},
{pos: [4, 0, 4], state: "minecraft:polished_andesite"},
{pos: [0, 1, 0], state: "minecraft:air"},
{pos: [0, 1, 1], state: "minecraft:air"},
{pos: [0, 1, 2], state: "minecraft:air"},
{pos: [0, 1, 3], state: "minecraft:air"},
{pos: [0, 1, 4], state: "minecraft:air"},
{pos: [1, 1, 0], state: "minecraft:air"},
{pos: [1, 1, 1], state: "minecraft:air"},
{pos: [1, 1, 2], state: "minecraft:air"},
{pos: [1, 1, 3], state: "minecraft:air"},
{pos: [1, 1, 4], state: "minecraft:air"},
{pos: [2, 1, 0], state: "minecraft:air"},
{pos: [2, 1, 1], state: "minecraft:air"},
{pos: [2, 1, 2], state: "minecraft:air"},
{pos: [2, 1, 3], state: "minecraft:air"},
{pos: [2, 1, 4], state: "minecraft:polished_andesite"},
{pos: [3, 1, 0], state: "minecraft:air"},
{pos: [3, 1, 1], state: "minecraft:air"},
{pos: [3, 1, 2], state: "minecraft:air"},
{pos: [3, 1, 3], state: "minecraft:air"},
{pos: [3, 1, 4], state: "minecraft:air"},
{pos: [4, 1, 0], state: "minecraft:air"},
{pos: [4, 1, 1], state: "minecraft:air"},
{pos: [4, 1, 2], state: "minecraft:air"},
{pos: [4, 1, 3], state: "minecraft:air"},
{pos: [4, 1, 4], state: "minecraft:air"},
{pos: [0, 2, 0], state: "minecraft:air"},
{pos: [0, 2, 1], state: "minecraft:air"},
{pos: [0, 2, 2], state: "minecraft:air"},
{pos: [0, 2, 3], state: "minecraft:air"},
{pos: [0, 2, 4], state: "minecraft:air"},
{pos: [1, 2, 0], state: "minecraft:air"},
{pos: [1, 2, 1], state: "minecraft:air"},
{pos: [1, 2, 2], state: "minecraft:air"},
{pos: [1, 2, 3], state: "minecraft:air"},
{pos: [1, 2, 4], state: "minecraft:air"},
{pos: [2, 2, 0], state: "minecraft:air"},
{pos: [2, 2, 1], state: "minecraft:air"},
{pos: [2, 2, 2], state: "minecraft:air"},
{pos: [2, 2, 3], state: "minecraft:air"},
{pos: [2, 2, 4], state: "minecraft:polished_andesite"},
{pos: [3, 2, 0], state: "minecraft:air"},
{pos: [3, 2, 1], state: "minecraft:air"},
{pos: [3, 2, 2], state: "minecraft:air"},
{pos: [3, 2, 3], state: "minecraft:air"},
{pos: [3, 2, 4], state: "minecraft:air"},
{pos: [4, 2, 0], state: "minecraft:air"},
{pos: [4, 2, 1], state: "minecraft:air"},
{pos: [4, 2, 2], state: "minecraft:air"},
{pos: [4, 2, 3], state: "minecraft:air"},
{pos: [4, 2, 4], state: "minecraft:air"},
{pos: [0, 3, 0], state: "minecraft:air"},
{pos: [0, 3, 1], state: "minecraft:air"},
{pos: [0, 3, 2], state: "minecraft:air"},
{pos: [0, 3, 3], state: "minecraft:air"},
{pos: [0, 3, 4], state: "minecraft:air"},
{pos: [1, 3, 0], state: "minecraft:air"},
{pos: [1, 3, 1], state: "minecraft:air"},
{pos: [1, 3, 2], state: "minecraft:air"},
{pos: [1, 3, 3], state: "minecraft:air"},
{pos: [1, 3, 4], state: "minecraft:air"},
{pos: [2, 3, 0], state: "minecraft:air"},
{pos: [2, 3, 1], state: "minecraft:air"},
{pos: [2, 3, 2], state: "minecraft:air"},
{pos: [2, 3, 3], state: "minecraft:air"},
{pos: [2, 3, 4], state: "minecraft:air"},
{pos: [3, 3, 0], state: "minecraft:air"},
{pos: [3, 3, 1], state: "minecraft:air"},
{pos: [3, 3, 2], state: "minecraft:air"},
{pos: [3, 3, 3], state: "minecraft:air"},
{pos: [3, 3, 4], state: "minecraft:air"},
{pos: [4, 3, 0], state: "minecraft:air"},
{pos: [4, 3, 1], state: "minecraft:air"},
{pos: [4, 3, 2], state: "minecraft:air"},
{pos: [4, 3, 3], state: "minecraft:air"},
{pos: [4, 3, 4], state: "minecraft:air"},
{pos: [0, 4, 0], state: "minecraft:air"},
{pos: [0, 4, 1], state: "minecraft:air"},
{pos: [0, 4, 2], state: "minecraft:air"},
{pos: [0, 4, 3], state: "minecraft:air"},
{pos: [0, 4, 4], state: "minecraft:air"},
{pos: [1, 4, 0], state: "minecraft:air"},
{pos: [1, 4, 1], state: "minecraft:air"},
{pos: [1, 4, 2], state: "minecraft:air"},
{pos: [1, 4, 3], state: "minecraft:air"},
{pos: [1, 4, 4], state: "minecraft:air"},
{pos: [2, 4, 0], state: "minecraft:air"},
{pos: [2, 4, 1], state: "minecraft:air"},
{pos: [2, 4, 2], state: "minecraft:air"},
{pos: [2, 4, 3], state: "minecraft:air"},
{pos: [2, 4, 4], state: "minecraft:air"},
{pos: [3, 4, 0], state: "minecraft:air"},
{pos: [3, 4, 1], state: "minecraft:air"},
{pos: [3, 4, 2], state: "minecraft:air"},
{pos: [3, 4, 3], state: "minecraft:air"},
{pos: [3, 4, 4], state: "minecraft:air"},
{pos: [4, 4, 0], state: "minecraft:air"},
{pos: [4, 4, 1], state: "minecraft:air"},
{pos: [4, 4, 2], state: "minecraft:air"},
{pos: [4, 4, 3], state: "minecraft:air"},
{pos: [4, 4, 4], state: "minecraft:air"}
],
entities: [
{blockPos: [2, 1, 2], pos: [2.583196949396921d, 1.0d, 2.608974919959593d], nbt: {AbsorptionAmount: 0.0f, Air: 300s, ArmorItems: [{}, {}, {}, {}], Attributes: [{Base: 0.699999988079071d, Name: "minecraft:generic.movement_speed"}], Brain: {memories: {}}, CustomName: '{"text":"printouttest.in_frame_at_night"}', DeathTime: 0s, DisabledSlots: 0, FallDistance: 0.0f, FallFlying: 0b, Fire: -1s, HandItems: [{}, {}], Health: 20.0f, HurtByTimestamp: 0, HurtTime: 0s, Invisible: 1b, Invulnerable: 0b, Marker: 1b, Motion: [0.0d, 0.0d, 0.0d], NoBasePlate: 0b, OnGround: 0b, PortalCooldown: 0, Pos: [221.58319694939692d, -58.0d, 92.60897491995959d], Pose: {}, Rotation: [1.3504658f, 6.7031174f], ShowArms: 0b, Small: 0b, UUID: [I; 1854159985, -991539606, -1317309541, 1483112386], id: "minecraft:armor_stand"}},
{blockPos: [2, 2, 3], pos: [2.5d, 2.5d, 3.96875d], nbt: {Air: 300s, Facing: 2b, FallDistance: 0.0f, Fire: -1s, Fixed: 0b, Invisible: 0b, Invulnerable: 0b, Item: {Count: 1b, id: "computercraft:printed_page", tag: {Color0: "eeeeeeeeeeeeeeeeeeeeeeeee", Color1: "eeeeeeeeeeeeeeeeeeeeeeeee", Color10: "eeeeeeeeeeeeeeeeeeeeeeeee", Color11: "eeeeeeeeeeeeeeeeeeeeeeeee", Color12: "eeeeeeeeeeeeeeeeeeeeeeeee", Color13: "eeeeeeeeeeeeeeeeeeeeeeeee", Color14: "eeeeeeeeeeeeeeeeeeeeeeeee", Color15: "eeeeeeeeeeeeeeeeeeeeeeeee", Color16: "eeeeeeeeeeeeeeeeeeeeeeeee", Color17: "eeeeeeeeeeeeeeeeeeeeeeeee", Color18: "eeeeeeeeeeeeeeeeeeeeeeeee", Color19: "eeeeeeeeeeeeeeeeeeeeeeeee", Color2: "eeeeeeeeeeeeeeeeeeeeeeeee", Color20: "eeeeeeeeeeeeeeeeeeeeeeeee", Color3: "eeeeeeeeeeeeeeeeeeeeeeeee", Color4: "eeeeeeeeeeeeeeeeeeeeeeeee", Color5: "eeeeeeeeeeeeeeeeeeeeeeeee", Color6: "eeeeeeeeeeeeeeeeeeeeeeeee", Color7: "eeeeeeeeeeeeeeeeeeeeeeeee", Color8: "eeeeeeeeeeeeeeeeeeeeeeeee", Color9: "eeeeeeeeeeeeeeeeeeeeeeeee", Pages: 1, Text0: "If you're reading this, ", Text1: "the test failed. ", Text10: " ", Text11: " ", Text12: " ", Text13: " ", Text14: " ", Text15: " ", Text16: " ", Text17: " ", Text18: " ", Text19: " ", Text2: " ", Text20: " ", Text3: " ", Text4: " ", Text5: " ", Text6: " ", Text7: " ", Text8: " ", Text9: " ", Title: "a.lua"}}, ItemDropChance: 1.0f, ItemRotation: 0b, Motion: [0.0d, 0.0d, 0.0d], OnGround: 0b, PortalCooldown: 0, Pos: [221.5d, -56.5d, 93.96875d], Rotation: [-540.0f, 0.0f], TileX: 221, TileY: -57, TileZ: 93, UUID: [I; 1972443954, 193152445, -1823446000, -1684171214], id: "minecraft:item_frame"}}
],
palette: [
"minecraft:polished_andesite",
"minecraft:air"
]
}

View File

@@ -1,140 +0,0 @@
{
DataVersion: 2730,
size: [5, 5, 5],
data: [
{pos: [0, 0, 0], state: "minecraft:polished_andesite"},
{pos: [0, 0, 1], state: "minecraft:polished_andesite"},
{pos: [0, 0, 2], state: "minecraft:polished_andesite"},
{pos: [0, 0, 3], state: "minecraft:polished_andesite"},
{pos: [0, 0, 4], state: "minecraft:polished_andesite"},
{pos: [1, 0, 0], state: "minecraft:polished_andesite"},
{pos: [1, 0, 1], state: "minecraft:polished_andesite"},
{pos: [1, 0, 2], state: "minecraft:polished_andesite"},
{pos: [1, 0, 3], state: "minecraft:polished_andesite"},
{pos: [1, 0, 4], state: "minecraft:polished_andesite"},
{pos: [2, 0, 0], state: "minecraft:polished_andesite"},
{pos: [2, 0, 1], state: "minecraft:polished_andesite"},
{pos: [2, 0, 2], state: "minecraft:polished_andesite"},
{pos: [2, 0, 3], state: "minecraft:polished_andesite"},
{pos: [2, 0, 4], state: "minecraft:polished_andesite"},
{pos: [3, 0, 0], state: "minecraft:polished_andesite"},
{pos: [3, 0, 1], state: "minecraft:polished_andesite"},
{pos: [3, 0, 2], state: "minecraft:polished_andesite"},
{pos: [3, 0, 3], state: "minecraft:polished_andesite"},
{pos: [3, 0, 4], state: "minecraft:polished_andesite"},
{pos: [4, 0, 0], state: "minecraft:polished_andesite"},
{pos: [4, 0, 1], state: "minecraft:polished_andesite"},
{pos: [4, 0, 2], state: "minecraft:polished_andesite"},
{pos: [4, 0, 3], state: "minecraft:polished_andesite"},
{pos: [4, 0, 4], state: "minecraft:polished_andesite"},
{pos: [0, 1, 0], state: "minecraft:white_concrete"},
{pos: [0, 1, 1], state: "minecraft:white_concrete"},
{pos: [0, 1, 2], state: "minecraft:white_concrete"},
{pos: [0, 1, 3], state: "minecraft:white_concrete"},
{pos: [0, 1, 4], state: "minecraft:white_concrete"},
{pos: [1, 1, 0], state: "minecraft:white_concrete"},
{pos: [1, 1, 1], state: "minecraft:air"},
{pos: [1, 1, 2], state: "minecraft:air"},
{pos: [1, 1, 3], state: "minecraft:air"},
{pos: [1, 1, 4], state: "minecraft:white_concrete"},
{pos: [2, 1, 0], state: "minecraft:white_concrete"},
{pos: [2, 1, 1], state: "minecraft:air"},
{pos: [2, 1, 2], state: "minecraft:air"},
{pos: [2, 1, 3], state: "minecraft:air"},
{pos: [2, 1, 4], state: "minecraft:white_concrete"},
{pos: [3, 1, 0], state: "minecraft:white_concrete"},
{pos: [3, 1, 1], state: "minecraft:air"},
{pos: [3, 1, 2], state: "minecraft:air"},
{pos: [3, 1, 3], state: "minecraft:air"},
{pos: [3, 1, 4], state: "minecraft:white_concrete"},
{pos: [4, 1, 0], state: "minecraft:white_concrete"},
{pos: [4, 1, 1], state: "minecraft:white_concrete"},
{pos: [4, 1, 2], state: "minecraft:white_concrete"},
{pos: [4, 1, 3], state: "minecraft:white_concrete"},
{pos: [4, 1, 4], state: "minecraft:white_concrete"},
{pos: [0, 2, 0], state: "minecraft:white_concrete"},
{pos: [0, 2, 1], state: "minecraft:white_concrete"},
{pos: [0, 2, 2], state: "minecraft:white_concrete"},
{pos: [0, 2, 3], state: "minecraft:white_concrete"},
{pos: [0, 2, 4], state: "minecraft:white_concrete"},
{pos: [1, 2, 0], state: "minecraft:white_concrete"},
{pos: [1, 2, 1], state: "minecraft:air"},
{pos: [1, 2, 2], state: "minecraft:air"},
{pos: [1, 2, 3], state: "minecraft:air"},
{pos: [1, 2, 4], state: "minecraft:white_concrete"},
{pos: [2, 2, 0], state: "minecraft:white_concrete"},
{pos: [2, 2, 1], state: "minecraft:air"},
{pos: [2, 2, 2], state: "minecraft:air"},
{pos: [2, 2, 3], state: "minecraft:air"},
{pos: [2, 2, 4], state: "minecraft:white_concrete"},
{pos: [3, 2, 0], state: "minecraft:white_concrete"},
{pos: [3, 2, 1], state: "minecraft:air"},
{pos: [3, 2, 2], state: "minecraft:air"},
{pos: [3, 2, 3], state: "minecraft:air"},
{pos: [3, 2, 4], state: "minecraft:white_concrete"},
{pos: [4, 2, 0], state: "minecraft:white_concrete"},
{pos: [4, 2, 1], state: "minecraft:white_concrete"},
{pos: [4, 2, 2], state: "minecraft:white_concrete"},
{pos: [4, 2, 3], state: "minecraft:white_concrete"},
{pos: [4, 2, 4], state: "minecraft:white_concrete"},
{pos: [0, 3, 0], state: "minecraft:white_concrete"},
{pos: [0, 3, 1], state: "minecraft:white_concrete"},
{pos: [0, 3, 2], state: "minecraft:white_concrete"},
{pos: [0, 3, 3], state: "minecraft:white_concrete"},
{pos: [0, 3, 4], state: "minecraft:white_concrete"},
{pos: [1, 3, 0], state: "minecraft:white_concrete"},
{pos: [1, 3, 1], state: "minecraft:air"},
{pos: [1, 3, 2], state: "minecraft:air"},
{pos: [1, 3, 3], state: "minecraft:air"},
{pos: [1, 3, 4], state: "minecraft:white_concrete"},
{pos: [2, 3, 0], state: "minecraft:white_concrete"},
{pos: [2, 3, 1], state: "minecraft:air"},
{pos: [2, 3, 2], state: "minecraft:air"},
{pos: [2, 3, 3], state: "minecraft:air"},
{pos: [2, 3, 4], state: "minecraft:white_concrete"},
{pos: [3, 3, 0], state: "minecraft:white_concrete"},
{pos: [3, 3, 1], state: "minecraft:air"},
{pos: [3, 3, 2], state: "minecraft:air"},
{pos: [3, 3, 3], state: "minecraft:air"},
{pos: [3, 3, 4], state: "minecraft:white_concrete"},
{pos: [4, 3, 0], state: "minecraft:white_concrete"},
{pos: [4, 3, 1], state: "minecraft:white_concrete"},
{pos: [4, 3, 2], state: "minecraft:white_concrete"},
{pos: [4, 3, 3], state: "minecraft:white_concrete"},
{pos: [4, 3, 4], state: "minecraft:white_concrete"},
{pos: [0, 4, 0], state: "minecraft:white_concrete"},
{pos: [0, 4, 1], state: "minecraft:white_concrete"},
{pos: [0, 4, 2], state: "minecraft:white_concrete"},
{pos: [0, 4, 3], state: "minecraft:white_concrete"},
{pos: [0, 4, 4], state: "minecraft:white_concrete"},
{pos: [1, 4, 0], state: "minecraft:white_concrete"},
{pos: [1, 4, 1], state: "minecraft:white_concrete"},
{pos: [1, 4, 2], state: "minecraft:white_concrete"},
{pos: [1, 4, 3], state: "minecraft:white_concrete"},
{pos: [1, 4, 4], state: "minecraft:white_concrete"},
{pos: [2, 4, 0], state: "minecraft:white_concrete"},
{pos: [2, 4, 1], state: "minecraft:white_concrete"},
{pos: [2, 4, 2], state: "minecraft:white_concrete"},
{pos: [2, 4, 3], state: "minecraft:white_concrete"},
{pos: [2, 4, 4], state: "minecraft:white_concrete"},
{pos: [3, 4, 0], state: "minecraft:white_concrete"},
{pos: [3, 4, 1], state: "minecraft:white_concrete"},
{pos: [3, 4, 2], state: "minecraft:white_concrete"},
{pos: [3, 4, 3], state: "minecraft:white_concrete"},
{pos: [3, 4, 4], state: "minecraft:white_concrete"},
{pos: [4, 4, 0], state: "minecraft:white_concrete"},
{pos: [4, 4, 1], state: "minecraft:white_concrete"},
{pos: [4, 4, 2], state: "minecraft:white_concrete"},
{pos: [4, 4, 3], state: "minecraft:white_concrete"},
{pos: [4, 4, 4], state: "minecraft:white_concrete"}
],
entities: [
{blockPos: [2, 2, 3], pos: [2.5d, 2.5d, 3.96875d], nbt: {Air: 300s, CanUpdate: 1b, Facing: 2b, FallDistance: 0.0f, Fire: -1s, Fixed: 0b, Invisible: 0b, Invulnerable: 0b, Item: {Count: 1b, id: "computercraft:printed_page", tag: {Color0: "eeeeeeeeeeeeeeeeeeeeeeeee", Color1: "eeeeeeeeeeeeeeeeeeeeeeeee", Color10: "eeeeeeeeeeeeeeeeeeeeeeeee", Color11: "eeeeeeeeeeeeeeeeeeeeeeeee", Color12: "eeeeeeeeeeeeeeeeeeeeeeeee", Color13: "eeeeeeeeeeeeeeeeeeeeeeeee", Color14: "eeeeeeeeeeeeeeeeeeeeeeeee", Color15: "eeeeeeeeeeeeeeeeeeeeeeeee", Color16: "eeeeeeeeeeeeeeeeeeeeeeeee", Color17: "eeeeeeeeeeeeeeeeeeeeeeeee", Color18: "eeeeeeeeeeeeeeeeeeeeeeeee", Color19: "eeeeeeeeeeeeeeeeeeeeeeeee", Color2: "eeeeeeeeeeeeeeeeeeeeeeeee", Color20: "eeeeeeeeeeeeeeeeeeeeeeeee", Color3: "eeeeeeeeeeeeeeeeeeeeeeeee", Color4: "eeeeeeeeeeeeeeeeeeeeeeeee", Color5: "eeeeeeeeeeeeeeeeeeeeeeeee", Color6: "eeeeeeeeeeeeeeeeeeeeeeeee", Color7: "eeeeeeeeeeeeeeeeeeeeeeeee", Color8: "eeeeeeeeeeeeeeeeeeeeeeeee", Color9: "eeeeeeeeeeeeeeeeeeeeeeeee", Pages: 1, Text0: "If you're reading this, ", Text1: "the test failed. ", Text10: " ", Text11: " ", Text12: " ", Text13: " ", Text14: " ", Text15: " ", Text16: " ", Text17: " ", Text18: " ", Text19: " ", Text2: " ", Text20: " ", Text3: " ", Text4: " ", Text5: " ", Text6: " ", Text7: " ", Text8: " ", Text9: " ", Title: "a.lua"}}, ItemDropChance: 1.0f, ItemRotation: 0b, Motion: [0.0d, 0.0d, 0.0d], OnGround: 0b, PortalCooldown: 0, Pos: [10.5d, 7.5d, 44.96875d], Rotation: [180.0f, 0.0f], TileX: 10, TileY: 7, TileZ: 44, UUID: [I; 1043973837, -2076424529, -1762893135, -165665834], id: "minecraft:item_frame"}},
{blockPos: [2, 1, 2], pos: [2.583196949396914d, 1.0d, 2.6089749199596d], nbt: {AbsorptionAmount: 0.0f, Air: 300s, ArmorItems: [{}, {}, {}, {}], Attributes: [{Base: 0.699999988079071d, Name: "minecraft:generic.movement_speed"}], Brain: {memories: {}}, CanUpdate: 1b, CustomName: '{"text":"printouttest.in_frame_at_night"}', DeathTime: 0s, DisabledSlots: 0, FallDistance: 0.0f, FallFlying: 0b, Fire: -1s, HandItems: [{}, {}], Health: 20.0f, HurtByTimestamp: 0, HurtTime: 0s, Invisible: 1b, Invulnerable: 0b, Marker: 1b, Motion: [0.0d, 0.0d, 0.0d], NoBasePlate: 0b, OnGround: 0b, PortalCooldown: 0, Pos: [10.583196949396914d, 6.0d, 43.6089749199596d], Pose: {}, Rotation: [1.3504658f, 6.7031174f], ShowArms: 0b, Small: 0b, UUID: [I; -1917933016, 1390888530, -2109873447, -2136052677], id: "minecraft:armor_stand"}}
],
palette: [
"minecraft:polished_andesite",
"minecraft:white_concrete",
"minecraft:air"
]
}

View File

@@ -20,6 +20,7 @@ dependencies {
implementation(libs.asm)
testFixturesImplementation(libs.slf4j)
testFixturesApi(platform(libs.kotlin.platform))
testFixturesApi(libs.bundles.test)
testFixturesApi(libs.bundles.kotlin)

View File

@@ -15,10 +15,12 @@ public final class Logging {
public static final Marker COMPUTER_ERROR = MarkerFactory.getMarker("COMPUTER_ERROR");
public static final Marker HTTP_ERROR = MarkerFactory.getMarker("COMPUTER_ERROR.HTTP");
public static final Marker JAVA_ERROR = MarkerFactory.getMarker("COMPUTER_ERROR.JAVA");
public static final Marker VM_ERROR = MarkerFactory.getMarker("COMPUTER_ERROR.VM");
static {
HTTP_ERROR.add(COMPUTER_ERROR);
JAVA_ERROR.add(COMPUTER_ERROR);
VM_ERROR.add(COMPUTER_ERROR);
}
private Logging() {

View File

@@ -117,7 +117,7 @@ public class RedstoneAPI implements ILuaAPI {
*
* @param side The side to set.
* @param value The signal strength between 0 and 15.
* @throws LuaException If {@code value} is not betwene 0 and 15.
* @throws LuaException If {@code value} is not between 0 and 15.
* @cc.since 1.51
*/
@LuaFunction({ "setAnalogOutput", "setAnalogueOutput" })

View File

@@ -42,8 +42,8 @@ public class BinaryWritableHandle extends HandleGeneric {
*
* @param arguments The value to write.
* @throws LuaException If the file has been closed.
* @cc.tparam [1] number The byte to write.
* @cc.tparam [2] string The string to write.
* @cc.tparam [1] number charcode The byte to write.
* @cc.tparam [2] string contents The string to write.
* @cc.changed 1.80pr1 Now accepts a string to write multiple bytes.
*/
@LuaFunction

View File

@@ -51,7 +51,7 @@ public class EncodedWritableHandle extends HandleGeneric {
}
/**
* Write a string of characters to the file, follwing them with a new line character.
* Write a string of characters to the file, following them with a new line character.
*
* @param args The value to write.
* @throws LuaException If the file has been closed.

View File

@@ -17,8 +17,8 @@ import java.net.URI;
* A version of {@link WebSocketClientHandshaker13} which doesn't add the {@link HttpHeaderNames#ORIGIN} header to the
* original HTTP request.
*/
public class NoOriginWebSocketHanshakder extends WebSocketClientHandshaker13 {
public NoOriginWebSocketHanshakder(URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) {
public class NoOriginWebSocketHandshaker extends WebSocketClientHandshaker13 {
public NoOriginWebSocketHandshaker(URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) {
super(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength);
}

View File

@@ -133,7 +133,7 @@ public class Websocket extends Resource<Websocket> {
}
var subprotocol = headers.get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
WebSocketClientHandshaker handshaker = new NoOriginWebSocketHanshakder(
WebSocketClientHandshaker handshaker = new NoOriginWebSocketHandshaker(
uri, WebSocketVersion.V13, subprotocol, true, headers,
options.websocketMessage <= 0 ? MAX_MESSAGE_SIZE : options.websocketMessage
);

View File

@@ -83,6 +83,11 @@ public class CobaltLuaMachine implements ILuaMachine {
}
});
})
.errorReporter((e, msg) -> {
if (LOG.isErrorEnabled(Logging.VM_ERROR)) {
LOG.error(Logging.VM_ERROR, "Error occurred in the Lua runtime. Computer will continue to execute:\n{}", msg.get(), e);
}
})
.build();
globals = new LuaTable();

View File

@@ -7,7 +7,7 @@ local expect
do
local h = fs.open("rom/modules/main/cc/expect.lua", "r")
local f, err = loadstring(h.readAll(), "@expect.lua")
local f, err = loadstring(h.readAll(), "@/rom/modules/main/cc/expect.lua")
h.close()
if not f then error(err) end
@@ -467,7 +467,7 @@ function loadfile(filename, mode, env)
local file = fs.open(filename, "r")
if not file then return nil, "File not found" end
local func, err = load(file.readAll(), "@" .. fs.getName(filename), mode, env)
local func, err = load(file.readAll(), "@/" .. fs.combine(filename), mode, env)
file.close()
return func, err
end
@@ -700,7 +700,7 @@ settings.define("motd.path", {
settings.define("lua.warn_against_use_of_local", {
default = true,
description = [[Print a message when input in the Lua REPL starts with the word 'local'. Local variables defined in the Lua REPL are be inaccessable on the next input.]],
description = [[Print a message when input in the Lua REPL starts with the word 'local'. Local variables defined in the Lua REPL are be inaccessible on the next input.]],
type = "boolean",
})
settings.define("lua.function_args", {

View File

@@ -52,7 +52,7 @@ This table also accepts the following options:
return fs.complete(str, "", {
include_files = true,
include_dirs = false,
included_hidden = false,
include_hidden = false,
})
end)
]]

View File

@@ -16,7 +16,7 @@ function path()
return sPath
end
--- Sets the colon-seperated list of directories where help files are searched
--- Sets the colon-separated list of directories where help files are searched
-- for to `newPath`
--
-- @tparam string newPath The new path to use.

View File

@@ -1,6 +1,6 @@
--[[- A simple way to run several functions at once.
Functions are not actually executed simultaniously, but rather this API will
Functions are not actually executed simultaneously, but rather this API will
automatically switch between them whenever they yield (e.g. whenever they call
@{coroutine.yield}, or functions that call that - such as @{os.pullEvent} - or
functions that call that, etc - basically, anything that causes the function

View File

@@ -17,12 +17,13 @@ You can list the names of all peripherals with the `peripherals` program, or the
@{peripheral.getNames} function.
It's also possible to use peripherals which are further away from your computer
through the use of @{modem|Wired Modems}. Place one modem against your computer,
run Networking Cable to your peripheral, and then place another modem against
that block. You can then right click the modem to use (or *attach*) the
peripheral. This will print a peripheral name to chat, which can then be used
just like a direction name to access the peripheral. You can click on the message
to copy the name to your clipboard.
through the use of @{modem|Wired Modems}. Place one modem against your computer
(you may need to sneak and right click), run Networking Cable to your
peripheral, and then place another modem against that block. You can then right
click the modem to use (or *attach*) the peripheral. This will print a
peripheral name to chat, which can then be used just like a direction name to
access the peripheral. You can click on the message to copy the name to your
clipboard.
## Using peripherals

View File

@@ -193,7 +193,7 @@ function send(recipient, message, protocol)
local sent = false
if recipient == os.getComputerID() then
-- Loopback to ourselves
os.queueEvent("rednet_message", os.getComputerID(), message_wrapper, protocol)
os.queueEvent("rednet_message", os.getComputerID(), message, protocol)
sent = true
else
-- Send on all open modems, to the target and to repeaters
@@ -217,9 +217,10 @@ end
channel. The message will be received by every device listening to rednet.
@param message The message to send. This should not contain coroutines or
functions, as they will be converted to @{nil}. @tparam[opt] string protocol
The "protocol" to send this message under. When using @{rednet.receive} one can
filter to only receive messages sent under a particular protocol.
functions, as they will be converted to @{nil}.
@tparam[opt] string protocol The "protocol" to send this message under. When
using @{rednet.receive} one can filter to only receive messages sent under a
particular protocol.
@see rednet.receive
@changed 1.6 Added protocol parameter.
@usage Broadcast the words "Hello, world!" to every computer using rednet.
@@ -318,7 +319,7 @@ different, or if they only join a given network after "registering" themselves
before doing so (eg while offline or part of a different network).
@tparam string protocol The protocol this computer provides.
@tparam string hostname The name this protocol exposes for the given protocol.
@tparam string hostname The name this computer exposes for the given protocol.
@throws If trying to register a hostname which is reserved, or currently in use.
@see rednet.unhost
@see rednet.lookup

View File

@@ -157,7 +157,7 @@ function pagedPrint(text, free_lines)
-- Removed the redirector
term.redirect(oldTerm)
-- Propogate errors
-- Propagate errors
if not ok then
error(err, 0)
end

View File

@@ -1,3 +1,25 @@
# New features in CC: Tweaked 1.103.0
* The shell now supports hashbangs (`#!`) (emmachase).
* Error messages in `edit` are now displayed in red on advanced computers.
* `turtle.getItemDetail` now always includes the `nbt` hash.
* Improvements to the display of errors in the shell and REPL.
* Turtles, pocket computers, and disks can be undyed by careful application (i.e. crafting) of a sponge.
* Turtles can no longer be dyed/undyed by right clicking.
Several bug fixes:
* Several documentation improvements and fixes (ouroborus, LelouBil)
* Fix rednet queueing the wrong message when sending a message to the current computer.
* Fix the Lua VM crashing when a `__len` metamethod yields.
* `pocket.{un,}equipBack` now correctly copies the stack when unequipping an upgrade.
* Fix `key` events not being queued while pressing computer shortcuts.
# New features in CC: Tweaked 1.102.2
Several bug fixes:
* Fix printouts crashing in item frames
* Fix disks not being assigned an ID when placed in a disk drive.
# New features in CC: Tweaked 1.102.1
Several bug fixes:
@@ -255,7 +277,7 @@ And several bug fixes:
And several bug fixes:
* Fix NPE when using a treasure disk when no treasure disks are available.
* Prevent command computers discarding command ouput when certain game rules are off.
* Prevent command computers discarding command output when certain game rules are off.
* Fix turtles not updating peripherals when upgrades are unequipped (Ronan-H).
* Fix computers not shutting down on fatal errors within the Lua VM.
* Speakers now correctly stop playing when broken, and sound follows noisy turtles and pocket computers.
@@ -265,32 +287,6 @@ And several bug fixes:
* Correctly render the transparent background on pocket/normal computers.
* Don't apply CraftTweaker actions twice on single-player worlds.
# New features in CC: Tweaked 1.97.0
* Update several translations (Anavrins, Jummit, Naheulf).
* Add button to view a computer's folder to `/computercraft dump`.
* Allow cleaning dyed turtles in a cauldron.
* Add scale subcommand to `monitor` program (MCJack123).
* Add option to make `textutils.serialize` not write an indent (magiczocker10).
* Allow comparing vectors using `==` (fatboychummy).
* Improve HTTP error messages for SSL failures.
* Allow `craft` program to craft unlimited items (fatboychummy).
* Impose some limits on various command queues.
* Add buttons to shutdown and terminate to computer GUIs.
* Add program subcompletion to several programs (Wojbie).
* Update the `help` program to accept and (partially) highlight markdown files.
* Remove config option for the debug API.
* Allow setting the subprotocol header for websockets.
And several bug fixes:
* Fix NPE when using a treasure disk when no treasure disks are available.
* Prevent command computers discarding command ouput when certain game rules are off.
* Fix turtles not updating peripherals when upgrades are unequipped (Ronan-H).
* Fix computers not shutting down on fatal errors within the Lua VM.
* Speakers now correctly stop playing when broken, and sound follows noisy turtles and pocket computers.
* Update the `wget` to be more resiliant in the face of user-errors.
* Fix exiting `paint` typing "e" in the shell.
# New features in CC: Tweaked 1.96.0
* Use lightGrey for folders within the "list" program.
@@ -342,7 +338,7 @@ Several bug fixes:
# New features in CC: Tweaked 1.95.0
* Optimise the paint program's initial render.
* Several documentation improvments (Gibbo3771, MCJack123).
* Several documentation improvements (Gibbo3771, MCJack123).
* `fs.combine` now accepts multiple arguments.
* Add a setting (`bios.strict_globals`) to error when accidentally declaring a global. (Lupus590).
* Add an improved help viewer which allows scrolling up and down (MCJack123).
@@ -382,7 +378,7 @@ And several bug fixes:
* Update Swedish translations (Granddave).
* Printers use item tags to check dyes.
* HTTP rules may now be targetted for a specific port.
* HTTP rules may now be targeted for a specific port.
* Don't propagate adjacent redstone signals through computers.
And several bug fixes:
@@ -502,7 +498,7 @@ And several bug fixes:
- Add `utf8` lib.
- Mirror Lua's behaviour of tail calls more closely. Native functions are no longer tail called, and tail calls are displayed in the stack trace.
- `table.unpack` now uses `__len` and `__index` metamethods.
- Parser errors now include the token where the error occured.
- Parser errors now include the token where the error occurred.
* Add `textutils.unserializeJSON`. This can be used to decode standard JSON and stringified-NBT.
* The `settings` API now allows "defining" settings. This allows settings to specify a default value and description.
* Enable the motd on non-pocket computers.
@@ -510,7 +506,7 @@ And several bug fixes:
* Add Danish and Korean translations (ChristianLW, mindy15963)
* Fire `mouse_up` events in the monitor program.
* Allow specifying a timeout to `websocket.receive`.
* Increase the maximimum limit for websocket messages.
* Increase the maximum limit for websocket messages.
* Optimise capacity checking of computer/disk folders.
And several bug fixes:

View File

@@ -1,2 +1,2 @@
io is a standard Lua5.1 API, reimplemented for CraftOS. Not all the features are availiable.
io is a standard Lua5.1 API, reimplemented for CraftOS. Not all the features are available.
Refer to http://www.lua.org/manual/5.1/ for more information.

View File

@@ -7,5 +7,5 @@ To terminate a program stuck in a loop, hold Ctrl+T for 1 second.
To quickly shutdown a computer, hold Ctrl+S for 1 second.
To quickly reboot a computer, hold Ctrl+R for 1 second.
To learn about the programming APIs availiable, type "apis" or "help apis".
To learn about the programming APIs available, type "apis" or "help apis".
If you get stuck, visit the forums at http://www.computercraft.info/ for advice and tutorials.

View File

@@ -1,4 +1,4 @@
turtle is an api availiable on Turtles, which controls their movement.
turtle is an api available on Turtles, which controls their movement.
Functions in the Turtle API:
turtle.forward()
turtle.back()

View File

@@ -1,18 +1,17 @@
New features in CC: Tweaked 1.102.1
New features in CC: Tweaked 1.103.0
* The shell now supports hashbangs (`#!`) (emmachase).
* Error messages in `edit` are now displayed in red on advanced computers.
* `turtle.getItemDetail` now always includes the `nbt` hash.
* Improvements to the display of errors in the shell and REPL.
* Turtles, pocket computers, and disks can be undyed by careful application (i.e. crafting) of a sponge.
* Turtles can no longer be dyed/undyed by right clicking.
Several bug fixes:
* Fix crash on Fabric when refuelling with a non-fuel item (emmachase).
* Fix crash when calling `pocket.equipBack()` with a wireless modem.
* Fix turtles dropping their inventory when moving (emmachase).
* Fix crash when inserting items into a full inventory (emmachase).
* Simplify wired cable breaking code, fixing items sometimes not dropping.
* Correctly handle double chests being treated as single threads under Fabric.
* Fix `mouse_up` not being fired under Fabric.
* Fix full-block Wired modems not connecting to adjacent cables when placed.
* Hide the search tab from the `itemGroups` item details.
* Fix speakers playing too loudly.
* Change where turtles drop items from, reducing the chance that items clip through blocks.
* Fix the `computer_threads` config option not applying under Fabric.
* Fix stack overflow in logging code.
* Several documentation improvements and fixes (ouroborus, LelouBil)
* Fix rednet queueing the wrong message when sending a message to the current computer.
* Fix the Lua VM crashing when a `__len` metamethod yields.
* `pocket.{un,}equipBack` now correctly copies the stack when unequipping an upgrade.
* Fix `key` events not being queued while pressing computer shortcuts.
Type "help changelog" to see the full version history.

View File

@@ -0,0 +1,173 @@
--[[- A pretty-printer for Lua errors.
:::warning
This is an internal module and SHOULD NOT be used in your own code. It may
be removed or changed at any time.
:::
This consumes a list of messages and "annotations" and displays the error to the
terminal.
@see cc.internal.syntax.errors For errors produced by the parser.
@local
]]
local pretty = require "cc.pretty"
local expect = require "cc.expect"
local expect, field = expect.expect, expect.field
local wrap = require "cc.strings".wrap
--- Write a message to the screen.
-- @tparam cc.pretty.Doc|string msg The message to write.
local function display(msg)
if type(msg) == "table" then pretty.print(msg) else print(msg) end
end
-- Write a message to the screen, aligning to the current cursor position.
-- @tparam cc.pretty.Doc|string msg The message to write.
local function display_here(msg, preamble)
expect(1, msg, "string", "table")
local x = term.getCursorPos()
local width, height = term.getSize()
width = width - x + 1
local function newline()
local _, y = term.getCursorPos()
if y >= height then
term.scroll(1)
else
y = y + 1
end
preamble(y)
term.setCursorPos(x, y)
end
if type(msg) == "string" then
local lines = wrap(msg, width)
term.write(lines[1])
for i = 2, #lines do
newline()
term.write(lines[i])
end
else
local def_colour = term.getTextColour()
local function display_impl(doc)
expect(1, doc, "table")
local kind = doc.tag
if kind == "nil" then return
elseif kind == "text" then
-- TODO: cc.strings.wrap doesn't support a leading indent. We should
-- fix that!
-- Might also be nice to add a wrap_iter, which returns an iterator over
-- start_pos, end_pos instead.
if doc.colour then term.setTextColour(doc.colour) end
local x1 = term.getCursorPos()
local lines = wrap((" "):rep(x1 - x) .. doc.text, width)
term.write(lines[1]:sub(x1 - x + 1))
for i = 2, #lines do
newline()
term.write(lines[i])
end
if doc.colour then term.setTextColour(def_colour) end
elseif kind == "concat" then
for i = 1, doc.n do display_impl(doc[i]) end
else
error("Unknown doc " .. kind)
end
end
display_impl(msg)
end
print()
end
--- A list of colours we can use for error messages.
local error_colours = { colours.red, colours.green, colours.magenta, colours.orange }
--- The accent line used to denote a block of code.
local code_accent = pretty.text("\x95", colours.cyan)
--[[-
@tparam { get_pos = function, get_line = function } context
The context where the error was reported. This effectively acts as a view
over the underlying source, exposing the following functions:
- `get_pos`: Get the line and column of an opaque position.
- `get_line`: Get the source code for an opaque position.
@tparam table message The message to display, as produced by @{cc.internal.syntax.errors}.
]]
return function(context, message)
expect(1, context, "table")
expect(2, message, "table")
field(context, "get_pos", "function")
field(context, "get_line", "function")
if #message == 0 then error("Message is empty", 2) end
local error_colour = 1
local width = term.getSize()
for msg_idx = 1, #message do
if msg_idx > 1 then print() end
local msg = message[msg_idx]
if type(msg) == "table" and msg.tag == "annotate" then
local line, col = context.get_pos(msg.start_pos)
local end_line, end_col = context.get_pos(msg.end_pos)
local contents = context.get_line(msg.start_pos)
-- Pick a starting column. We pick the left-most position which fits
-- in one of the following:
-- - 10 characters after the start column.
-- - 5 characters after the end column.
-- - The end of the line.
if line ~= end_line then end_col = #contents end
local start_col = math.max(1, math.min(col + 10, end_col + 5, #contents + 1) - width + 1)
-- Pick a colour for this annotation.
local colour = colours.toBlit(error_colours[error_colour])
error_colour = (error_colour % #error_colours) + 1
-- Print the line number and snippet of code. We display french
-- quotes on either side of the string if it is truncated.
local str_start, str_end = start_col, start_col + width - 2
local prefix, suffix = "", ""
if start_col > 1 then
str_start = str_start + 1
prefix = pretty.text("\xab", colours.grey)
end
if str_end < #contents then
str_end = str_end - 1
suffix = pretty.text("\xbb", colours.grey)
end
pretty.print(code_accent .. pretty.text("Line " .. line, colours.cyan))
pretty.print(code_accent .. prefix .. pretty.text(contents:sub(str_start, str_end), colours.lightGrey) .. suffix)
-- Print a line highlighting the region of text.
local _, y = term.getCursorPos()
pretty.write(code_accent)
local indicator_end = end_col
if end_col > str_end then indicator_end = str_end end
local indicator_len = indicator_end - col + 1
term.setCursorPos(col - start_col + 2, y)
term.blit(("\x83"):rep(indicator_len), colour:rep(indicator_len), ("f"):rep(indicator_len))
print()
-- And then print the annotation's message, if present.
if msg.msg ~= "" then
term.blit("\x95", colour, "f")
display_here(msg.msg, function(y)
term.setCursorPos(1, y)
term.blit("\x95", colour, "f")
end)
end
else
display(msg)
end
end
end

View File

@@ -0,0 +1,119 @@
--[[- Internal tools for working with errors.
:::warning
This is an internal module and SHOULD NOT be used in your own code. It may
be removed or changed at any time.
:::
@local
]]
local expect = require "cc.expect".expect
local error_printer = require "cc.internal.error_printer"
local function find_frame(thread, file, line)
-- Scan the first 16 frames for something interesting.
for offset = 0, 15 do
local frame = debug.getinfo(thread, offset, "Sl")
if not frame then break end
if frame.short_src == file and frame.what ~= "C" and frame.currentline == line then
return frame
end
end
end
--[[- Attempt to call the provided function `func` with the provided arguments.
@tparam function func The function to call.
@param ... Arguments to this function.
@treturn[1] true If the function ran successfully.
@treturn[2] false If the function failed.
@return[2] The error message
@treturn[2] coroutine The thread where the error occurred.
]]
local function try(func, ...)
expect(1, func, "function")
local co = coroutine.create(func)
local ok, result = coroutine.resume(co, ...)
while coroutine.status(co) ~= "dead" do
local event = table.pack(os.pullEventRaw(result))
if result == nil or event[1] == result or event[1] == "terminate" then
ok, result = coroutine.resume(co, table.unpack(event, 1, event.n))
end
end
if not ok then return false, result, co end
return true
end
--[[- Report additional context about an error.
@param err The error to report.
@tparam coroutine thread The coroutine where the error occurred.
@tparam[opt] { [string] = string } source_map Map of chunk names to their contents.
]]
local function report(err, thread, source_map)
expect(2, thread, "thread")
expect(3, source_map, "table", "nil")
if type(err) ~= "string" then return end
local file, line = err:match("^([^:]+):(%d+):")
if not file then return end
line = tonumber(line)
local frame = find_frame(thread, file, line)
if not frame or not frame.currentcolumn then return end
local column = frame.currentcolumn
local line_contents
if source_map and source_map[frame.source] then
-- File exists in the source map.
local pos, contents = 1, source_map[frame.source]
-- Try to remap our position. The interface for this only makes sense
-- for single line sources, but that's sufficient for where we need it
-- (the REPL).
if type(contents) == "table" then
column = column - contents.offset
contents = contents.contents
end
for _ = 1, line - 1 do
local next_pos = contents:find("\n", pos)
if not next_pos then return end
pos = next_pos + 1
end
local end_pos = contents:find("\n", pos)
line_contents = contents:sub(pos, end_pos and end_pos - 1 or #contents)
elseif frame.source:sub(1, 2) == "@/" then
-- Read the file from disk.
local handle = fs.open(frame.source:sub(3), "r")
if not handle then return end
for _ = 1, line - 1 do handle.readLine() end
line_contents = handle.readLine()
end
-- Could not determine the line. Bail.
if not line_contents or #line_contents == "" then return end
error_printer({
get_pos = function() return line, column end,
get_line = function() return line_contents end,
}, {
{ tag = "annotate", start_pos = column, end_pos = column, msg = "" },
})
end
return {
try = try,
report = report,
}

View File

@@ -0,0 +1,552 @@
--[[- The error messages reported by our lexer and parser.
:::warning
This is an internal module and SHOULD NOT be used in your own code. It may
be removed or changed at any time.
:::
This provides a list of factory methods which take source positions and produce
appropriate error messages targeting that location. These error messages can
then be displayed to the user via @{cc.internal.error_printer}.
@local
]]
local pretty = require "cc.pretty"
local expect = require "cc.expect".expect
local tokens = require "cc.internal.syntax.parser".tokens
local function annotate(start_pos, end_pos, msg)
if msg == nil and (type(end_pos) == "string" or type(end_pos) == "table" or type(end_pos) == "nil") then
end_pos, msg = start_pos, end_pos
end
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, msg, "string", "table", "nil")
return { tag = "annotate", start_pos = start_pos, end_pos = end_pos, msg = msg or "" }
end
--- Format a string as a non-highlighted block of code.
--
-- @tparam string msg The code to format.
-- @treturn cc.pretty.Doc The formatted code.
local function code(msg) return pretty.text(msg, colours.lightGrey) end
--- Maps tokens to a more friendly version.
local token_names = setmetatable({
-- Specific tokens.
[tokens.IDENT] = "identifier",
[tokens.NUMBER] = "number",
[tokens.STRING] = "string",
[tokens.EOF] = "end of file",
-- Symbols and keywords
[tokens.ADD] = code("+"),
[tokens.AND] = code("and"),
[tokens.BREAK] = code("break"),
[tokens.CBRACE] = code("}"),
[tokens.COLON] = code(":"),
[tokens.COMMA] = code(","),
[tokens.CONCAT] = code(".."),
[tokens.CPAREN] = code(")"),
[tokens.CSQUARE] = code("]"),
[tokens.DIV] = code("/"),
[tokens.DO] = code("do"),
[tokens.DOT] = code("."),
[tokens.DOTS] = code("..."),
[tokens.ELSE] = code("else"),
[tokens.ELSEIF] = code("elseif"),
[tokens.END] = code("end"),
[tokens.EQ] = code("=="),
[tokens.EQUALS] = code("="),
[tokens.FALSE] = code("false"),
[tokens.FOR] = code("for"),
[tokens.FUNCTION] = code("function"),
[tokens.GE] = code(">="),
[tokens.GT] = code(">"),
[tokens.IF] = code("if"),
[tokens.IN] = code("in"),
[tokens.LE] = code("<="),
[tokens.LEN] = code("#"),
[tokens.LOCAL] = code("local"),
[tokens.LT] = code("<"),
[tokens.MOD] = code("%"),
[tokens.MUL] = code("*"),
[tokens.NE] = code("~="),
[tokens.NIL] = code("nil"),
[tokens.NOT] = code("not"),
[tokens.OBRACE] = code("{"),
[tokens.OPAREN] = code("("),
[tokens.OR] = code("or"),
[tokens.OSQUARE] = code("["),
[tokens.POW] = code("^"),
[tokens.REPEAT] = code("repeat"),
[tokens.RETURN] = code("return"),
[tokens.SEMICOLON] = code(";"),
[tokens.SUB] = code("-"),
[tokens.THEN] = code("then"),
[tokens.TRUE] = code("true"),
[tokens.UNTIL] = code("until"),
[tokens.WHILE] = code("while"),
}, { __index = function(_, name) error("No such token " .. tostring(name), 2) end })
local errors = {}
--------------------------------------------------------------------------------
-- Lexer errors
--------------------------------------------------------------------------------
--[[- A string which ends without a closing quote.
@tparam number start_pos The start position of the string.
@tparam number end_pos The end position of the string.
@tparam string quote The kind of quote (`"` or `'`).
@return The resulting parse error.
]]
function errors.unfinished_string(start_pos, end_pos, quote)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, quote, "string")
return {
"This string is not finished. Are you missing a closing quote (" .. code(quote) .. ")?",
annotate(start_pos, "String started here."),
annotate(end_pos, "Expected a closing quote here."),
}
end
--[[- A string which ends with an escape sequence (so a literal `"foo\`). This
is slightly different from @{unfinished_string}, as we don't want to suggest
adding a quote.
@tparam number start_pos The start position of the string.
@tparam number end_pos The end position of the string.
@tparam string quote The kind of quote (`"` or `'`).
@return The resulting parse error.
]]
function errors.unfinished_string_escape(start_pos, end_pos, quote)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, quote, "string")
return {
"This string is not finished.",
annotate(start_pos, "String started here."),
annotate(end_pos, "An escape sequence was started here, but with nothing following it."),
}
end
--[[- A long string was never finished.
@tparam number start_pos The start position of the long string delimiter.
@tparam number end_pos The end position of the long string delimiter.
@tparam number ;em The length of the long string delimiter, excluding the first `[`.
@return The resulting parse error.
]]
function errors.unfinished_long_string(start_pos, end_pos, len)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, len, "number")
return {
"This string was never finished.",
annotate(start_pos, end_pos, "String was started here."),
"We expected a closing delimiter (" .. code("]" .. ("="):rep(len - 1) .. "]") .. ") somewhere after this string was started.",
}
end
--[[- Malformed opening to a long string (i.e. `[=`).
@tparam number start_pos The start position of the long string delimiter.
@tparam number end_pos The end position of the long string delimiter.
@tparam number len The length of the long string delimiter, excluding the first `[`.
@return The resulting parse error.
]]
function errors.malformed_long_string(start_pos, end_pos, len)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, len, "number")
return {
"Incorrect start of a long string.",
annotate(start_pos, end_pos),
"Tip: If you wanted to start a long string here, add an extra " .. code("[") .. " here.",
}
end
--[[- Malformed nesting of a long string.
@tparam number start_pos The start position of the long string delimiter.
@tparam number end_pos The end position of the long string delimiter.
@return The resulting parse error.
]]
function errors.nested_long_str(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
code("[[") .. " cannot be nested inside another " .. code("[[ ... ]]"),
annotate(start_pos, end_pos),
}
end
--[[- A malformed numeric literal.
@tparam number start_pos The start position of the number.
@tparam number end_pos The end position of the number.
@return The resulting parse error.
]]
function errors.malformed_number(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"This isn't a valid number.",
annotate(start_pos, end_pos),
"Numbers must be in one of the following formats: " .. code("123") .. ", "
.. code("3.14") .. ", " .. code("23e35") .. ", " .. code("0x01AF") .. ".",
}
end
--[[- A long comment was never finished.
@tparam number start_pos The start position of the long string delimiter.
@tparam number end_pos The end position of the long string delimiter.
@tparam number len The length of the long string delimiter, excluding the first `[`.
@return The resulting parse error.
]]
function errors.unfinished_long_comment(start_pos, end_pos, len)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
expect(3, len, "number")
return {
"This comment was never finished.",
annotate(start_pos, end_pos, "Comment was started here."),
"We expected a closing delimiter (" .. code("]" .. ("="):rep(len - 1) .. "]") .. ") somewhere after this comment was started.",
}
end
--[[- `&&` was used instead of `and`.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.wrong_and(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"Unexpected character.",
annotate(start_pos, end_pos),
"Tip: Replace this with " .. code("and") .. " to check if both values are true.",
}
end
--[[- `||` was used instead of `or`.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.wrong_or(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"Unexpected character.",
annotate(start_pos, end_pos),
"Tip: Replace this with " .. code("or") .. " to check if either value is true.",
}
end
--[[- `!=` was used instead of `~=`.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.wrong_ne(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"Unexpected character.",
annotate(start_pos, end_pos),
"Tip: Replace this with " .. code("~=") .. " to check if two values are not equal.",
}
end
--[[- An unexpected character was used.
@tparam number pos The position of this character.
@return The resulting parse error.
]]
function errors.unexpected_character(pos)
expect(1, pos, "number")
return {
"Unexpected character.",
annotate(pos, "This character isn't usable in Lua code."),
}
end
--------------------------------------------------------------------------------
-- Expression parsing errors
--------------------------------------------------------------------------------
--[[- A fallback error when we expected an expression but received another token.
@tparam number token The token id.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.expected_expression(token, start_pos, end_pos)
expect(1, token, "number")
expect(2, start_pos, "number")
expect(3, end_pos, "number")
return {
"Unexpected " .. token_names[token] .. ". Expected an expression.",
annotate(start_pos, end_pos),
}
end
--[[- A fallback error when we expected a variable but received another token.
@tparam number token The token id.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.expected_var(token, start_pos, end_pos)
expect(1, token, "number")
expect(2, start_pos, "number")
expect(3, end_pos, "number")
return {
"Unexpected " .. token_names[token] .. ". Expected a variable name.",
annotate(start_pos, end_pos),
}
end
--[[- `=` was used in an expression context.
@tparam number start_pos The start position of the `=` token.
@tparam number end_pos The end position of the `=` token.
@return The resulting parse error.
]]
function errors.use_double_equals(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"Unexpected " .. code("=") .. " in expression.",
annotate(start_pos, end_pos),
"Tip: Replace this with " .. code("==") .. " to check if two values are equal.",
}
end
--[[- `=` was used after an expression inside a table.
@tparam number start_pos The start position of the `=` token.
@tparam number end_pos The end position of the `=` token.
@return The resulting parse error.
]]
function errors.table_key_equals(start_pos, end_pos)
expect(1, start_pos, "number")
expect(2, end_pos, "number")
return {
"Unexpected " .. code("=") .. " in expression.",
annotate(start_pos, end_pos),
"Tip: Wrap the preceding expression in " .. code("[") .. " and " .. code("]") .. " to use it as a table key.",
}
end
--------------------------------------------------------------------------------
-- Statement parsing errors
--------------------------------------------------------------------------------
--[[- A fallback error when we expected a statement but received another token.
@tparam number token The token id.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.expected_statement(token, start_pos, end_pos)
expect(1, token, "number")
expect(2, start_pos, "number")
expect(3, end_pos, "number")
return {
"Unexpected " .. token_names[token] .. ". Expected a statement.",
annotate(start_pos, end_pos),
}
end
--[[- `local function` was used with a table identifier.
@tparam number local_start The start position of the `local` token.
@tparam number local_end The end position of the `local` token.
@tparam number dot_start The start position of the `.` token.
@tparam number dot_end The end position of the `.` token.
@return The resulting parse error.
]]
function errors.local_function_dot(local_start, local_end, dot_start, dot_end)
expect(1, local_start, "number")
expect(2, local_end, "number")
expect(3, dot_start, "number")
expect(4, dot_end, "number")
return {
"Cannot use " .. code("local function") .. " with a table key.",
annotate(dot_start, dot_end, code(".") .. " appears here."),
annotate(local_start, local_end, "Tip: " .. "Try removing this " .. code("local") .. " keyword."),
}
end
--[[- A statement of the form `x.y z`
@tparam number pos The position right after this name.
@return The resulting parse error.
]]
function errors.standalone_name(pos)
expect(1, pos, "number")
return {
"Unexpected symbol after name.",
annotate(pos),
"Did you mean to assign this or call it as a function?",
}
end
--[[- A statement of the form `x.y`. This is similar to @{standalone_name}, but
when the next token is on another line.
@tparam number pos The position right after this name.
@return The resulting parse error.
]]
function errors.standalone_name_call(pos)
expect(1, pos, "number")
return {
"Unexpected symbol after variable.",
annotate(pos + 1, "Expected something before the end of the line."),
"Tip: Use " .. code("()") .. " to call with no arguments.",
}
end
--[[- `then` was expected
@tparam number if_start The start position of the `if`/`elseif` keyword.
@tparam number if_end The end position of the `if`/`elseif` keyword.
@tparam number token_pos The current token position.
@return The resulting parse error.
]]
function errors.expected_then(if_start, if_end, token_pos)
expect(1, if_start, "number")
expect(2, if_end, "number")
expect(3, token_pos, "number")
return {
"Expected " .. code("then") .. " after if condition.",
annotate(if_start, if_end, "If statement started here."),
annotate(token_pos, "Expected " .. code("then") .. " before here."),
}
end
--[[- `end` was expected
@tparam number block_start The start position of the block.
@tparam number block_end The end position of the block.
@tparam number token The current token position.
@tparam number token_start The current token position.
@tparam number token_end The current token position.
@return The resulting parse error.
]]
function errors.expected_end(block_start, block_end, token, token_start, token_end)
return {
"Unexpected " .. token_names[token] .. ". Expected " .. code("end") .. " or another statement.",
annotate(block_start, block_end, "Block started here."),
annotate(token_start, token_end, "Expected end of block here."),
}
end
--[[- An unexpected `end` in a statement.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.unexpected_end(start_pos, end_pos)
return {
"Unexpected " .. code("end") .. ".",
annotate(start_pos, end_pos),
"Your program contains more " .. code("end") .. "s than needed. Check " ..
"each block (" .. code("if") .. ", " .. code("for") .. ", " ..
code("function") .. ", ...) only has one " .. code("end") .. ".",
}
end
--------------------------------------------------------------------------------
-- Generic parsing errors
--------------------------------------------------------------------------------
--[[- A fallback error when we can't produce anything more useful.
@tparam number token The token id.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.unexpected_token(token, start_pos, end_pos)
expect(1, token, "number")
expect(2, start_pos, "number")
expect(3, end_pos, "number")
return {
"Unexpected " .. token_names[token] .. ".",
annotate(start_pos, end_pos),
}
end
--[[- A parenthesised expression was started but not closed.
@tparam number open_start The start position of the opening bracket.
@tparam number open_end The end position of the opening bracket.
@tparam number tok_start The start position of the opening bracket.
@return The resulting parse error.
]]
function errors.unclosed_brackets(open_start, open_end, token, start_pos, end_pos)
expect(1, open_start, "number")
expect(2, open_end, "number")
expect(3, token, "number")
expect(4, start_pos, "number")
expect(5, end_pos, "number")
-- TODO: Do we want to be smarter here with where we report the error?
return {
"Unexpected " .. token_names[token] .. ". Are you missing a closing bracket?",
annotate(open_start, open_end, "Brackets were opened here."),
annotate(start_pos, end_pos, "Unexpected " .. token_names[token] .. " here."),
}
end
--[[- Expected `(` to open our function arguments.
@tparam number token The token id.
@tparam number start_pos The start position of the token.
@tparam number end_pos The end position of the token.
@return The resulting parse error.
]]
function errors.expected_function_args(token, start_pos, end_pos)
return {
"Unexpected " .. token_names[token] .. ". Expected " .. code("(") .. " to start function arguments.",
annotate(start_pos, end_pos),
}
end
return errors

View File

@@ -0,0 +1,100 @@
--[[- The main entrypoint to our Lua parser
:::warning
This is an internal module and SHOULD NOT be used in your own code. It may
be removed or changed at any time.
:::
@local
]]
local expect = require "cc.expect".expect
local lex_one = require "cc.internal.syntax.lexer".lex_one
local parser = require "cc.internal.syntax.parser"
local error_printer = require "cc.internal.error_printer"
local function parse(input, start_symbol)
expect(1, input, "string")
expect(2, start_symbol, "number")
-- Lazy-load the parser.
local parse, tokens, last_token = parser.parse, parser.tokens, parser.tokens.COMMENT
local error_sentinel = {}
local context = {}
local lines = { 1 }
function context.line(pos) lines[#lines + 1] = pos end
function context.get_pos(pos)
expect(1, pos, "number")
for i = #lines, 1, -1 do
local start = lines[i]
if pos >= start then return i, pos - start + 1 end
end
error("Position is <= 0", 2)
end
function context.get_line(pos)
expect(1, pos, "number")
for i = #lines, 1, -1 do
local start = lines[i]
if pos >= start then return input:match("[^\r\n]*", start) end
end
error("Position is <= 0", 2)
end
function context.report(msg)
expect(1, msg, "table")
error_printer(context, msg)
error(error_sentinel)
end
local pos = 1
local ok, err = pcall(parse, context, function()
while true do
local token, start, finish = lex_one(context, input, pos)
if not token then return tokens.EOF, #input + 1, #input + 1 end
pos = finish + 1
if token < last_token then
return token, start, finish
elseif token == tokens.ERROR then
error(error_sentinel)
end
end
end, start_symbol)
if ok then
return true
elseif err == error_sentinel then
return false
else
error(err, 0)
end
end
--[[- Parse a Lua program, printing syntax errors to the terminal.
@tparam string input The string to parse.
@treturn boolean Whether the string was successfully parsed.
]]
local function parse_program(input) return parse(input, parser.program) end
--[[- Parse a REPL input (either a program or a list of expressions), printing
syntax errors to the terminal.
@tparam string input The string to parse.
@treturn boolean Whether the string was successfully parsed.
]]
local function parse_repl(input) return parse(input, parser.repl_exprs) end
return {
parse_program = parse_program,
parse_repl = parse_repl,
}

View File

@@ -0,0 +1,359 @@
--[[- A lexer for Lua source code.
:::warning
This is an internal module and SHOULD NOT be used in your own code. It may
be removed or changed at any time.
:::
This module provides utilities for lexing Lua code, returning tokens compatible
with @{cc.internal.syntax.parser}. While all lexers are roughly the same, there
are some design choices worth drawing attention to:
- The lexer uses Lua patterns (i.e. @{string.find}) as much as possible,
trying to avoid @{string.sub} loops except when needed. This allows us to
move string processing to native code, which ends up being much faster.
- We try to avoid allocating where possible. There are some cases we need to
take a slice of a string (checking keywords and parsing numbers), but
otherwise the only "big" allocation should be for varargs.
- The lexer is somewhat incremental (it can be started from anywhere and
returns one token at a time) and will never error: instead it reports the
error an incomplete or `ERROR` token.
@local
]]
local errors = require "cc.internal.syntax.errors"
local tokens = require "cc.internal.syntax.parser".tokens
local sub, find = string.sub, string.find
local keywords = {
["and"] = tokens.AND, ["break"] = tokens.BREAK, ["do"] = tokens.DO, ["else"] = tokens.ELSE,
["elseif"] = tokens.ELSEIF, ["end"] = tokens.END, ["false"] = tokens.FALSE, ["for"] = tokens.FOR,
["function"] = tokens.FUNCTION, ["if"] = tokens.IF, ["in"] = tokens.IN, ["local"] = tokens.LOCAL,
["nil"] = tokens.NIL, ["not"] = tokens.NOT, ["or"] = tokens.OR, ["repeat"] = tokens.REPEAT,
["return"] = tokens.RETURN, ["then"] = tokens.THEN, ["true"] = tokens.TRUE, ["until"] = tokens.UNTIL,
["while"] = tokens.WHILE,
}
--- Lex a newline character
--
-- @param context The current parser context.
-- @tparam string str The current string.
-- @tparam number pos The position of the newline character.
-- @tparam string nl The current new line character, either "\n" or "\r".
-- @treturn pos The new position, after the newline.
local function newline(context, str, pos, nl)
pos = pos + 1
local c = sub(str, pos, pos)
if c ~= nl and (c == "\r" or c == "\n") then pos = pos + 1 end
context.line(pos) -- Mark the start of the next line.
return pos
end
--- Lex a number
--
-- @param context The current parser context.
-- @tparam string str The current string.
-- @tparam number start The start position of this number.
-- @treturn number The token id for numbers.
-- @treturn number The end position of this number
local function lex_number(context, str, start)
local pos = start + 1
local exp_low, exp_high = "e", "E"
if sub(str, start, start) == "0" then
local next = sub(str, pos, pos)
if next == "x" or next == "X" then
pos = pos + 1
exp_low, exp_high = "p", "P"
end
end
while true do
local c = sub(str, pos, pos)
if c == exp_low or c == exp_high then
pos = pos + 1
c = sub(str, pos, pos)
if c == "+" or c == "-" then
pos = pos + 1
end
elseif (c >= "0" and c <= "9") or (c >= "a" and c <= "f") or (c >= "A" and c <= "F") or c == "." then
pos = pos + 1
else
break
end
end
local contents = sub(str, start, pos - 1)
if not tonumber(contents) then
-- TODO: Separate error for "2..3"?
context.report(errors.malformed_number(start, pos - 1))
end
return tokens.NUMBER, pos - 1
end
--- Lex a quoted string.
--
-- @param context The current parser context.
-- @tparam string str The string we're lexing.
-- @tparam number start_pos The start position of the string.
-- @tparam string quote The quote character, either " or '.
-- @treturn number The token id for strings.
-- @treturn number The new position.
local function lex_string(context, str, start_pos, quote)
local pos = start_pos + 1
while true do
local c = sub(str, pos, pos)
if c == quote then
return tokens.STRING, pos
elseif c == "\n" or c == "\r" or c == "" then
-- We don't call newline here, as that's done for the next token.
context.report(errors.unfinished_string(start_pos, pos, quote))
return tokens.STRING, pos - 1
elseif c == "\\" then
c = sub(str, pos + 1, pos + 1)
if c == "\n" or c == "\r" then
pos = newline(context, str, pos + 1, c)
elseif c == "" then
context.report(errors.unfinished_string_escape(start_pos, pos, quote))
return tokens.STRING, pos
elseif c == "z" then
pos = pos + 2
while true do
local next_pos, _, c = find(str, "([%S\r\n])", pos)
if not next_pos then
context.report(errors.unfinished_string(start_pos, #str, quote))
return tokens.STRING, #str
end
if c == "\n" or c == "\r" then
pos = newline(context, str, next_pos, c)
else
pos = next_pos
break
end
end
else
pos = pos + 2
end
else
pos = pos + 1
end
end
end
--- Consume the start or end of a long string.
-- @tparam string str The input string.
-- @tparam number pos The start position. This must be after the first `[` or `]`.
-- @tparam string fin The terminating character, either `[` or `]`.
-- @treturn boolean Whether a long string was successfully started.
-- @treturn number The current position.
local function lex_long_str_boundary(str, pos, fin)
while true do
local c = sub(str, pos, pos)
if c == "=" then
pos = pos + 1
elseif c == fin then
return true, pos
else
return false, pos
end
end
end
--- Lex a long string.
-- @param context The current parser context.
-- @tparam string str The input string.
-- @tparam number start The start position, after the input boundary.
-- @tparam number len The expected length of the boundary. Equal to 1 + the
-- number of `=`.
-- @treturn number|nil The end position, or @{nil} if this is not terminated.
local function lex_long_str(context, str, start, len)
local pos = start
while true do
pos = find(str, "[%[%]\n\r]", pos)
if not pos then return nil end
local c = sub(str, pos, pos)
if c == "]" then
local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "]")
if ok and boundary_pos - pos == len then
return boundary_pos
else
pos = boundary_pos
end
elseif c == "[" then
local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "[")
if ok and boundary_pos - pos == len and len == 1 then
context.report(errors.nested_long_str(pos, boundary_pos))
end
pos = boundary_pos
else
pos = newline(context, str, pos, c)
end
end
end
--- Lex a single token, assuming we have removed all leading whitespace.
--
-- @param context The current parser context.
-- @tparam string str The string we're lexing.
-- @tparam number pos The start position.
-- @treturn number The id of the parsed token.
-- @treturn number The end position of this token.
-- @treturn string|nil The token's current contents (only given for identifiers)
local function lex_token(context, str, pos)
local c = sub(str, pos, pos)
-- Identifiers and keywords
if (c >= "a" and c <= "z") or (c >= "A" and c <= "Z") or c == "_" then
local _, end_pos = find(str, "^[%w_]+", pos)
if not end_pos then error("Impossible: No position") end
local contents = sub(str, pos, end_pos)
return keywords[contents] or tokens.IDENT, end_pos, contents
-- Numbers
elseif c >= "0" and c <= "9" then return lex_number(context, str, pos)
-- Strings
elseif c == "\"" or c == "\'" then return lex_string(context, str, pos, c)
elseif c == "[" then
local ok, boundary_pos = lex_long_str_boundary(str, pos + 1, "[")
if ok then -- Long string
local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - pos)
if end_pos then return tokens.STRING, end_pos end
context.report(errors.unfinished_long_string(pos, boundary_pos, boundary_pos - pos))
return tokens.ERROR, #str
elseif pos + 1 == boundary_pos then -- Just a "["
return tokens.OSQUARE, pos
else -- Malformed long string, for instance "[="
context.report(errors.malformed_long_string(pos, boundary_pos, boundary_pos - pos))
return tokens.ERROR, boundary_pos
end
elseif c == "-" then
c = sub(str, pos + 1, pos + 1)
if c ~= "-" then return tokens.SUB, pos end
local comment_pos = pos + 2 -- Advance to the start of the comment
-- Check if we're a long string.
if sub(str, comment_pos, comment_pos) == "[" then
local ok, boundary_pos = lex_long_str_boundary(str, comment_pos + 1, "[")
if ok then
local end_pos = lex_long_str(context, str, boundary_pos + 1, boundary_pos - comment_pos)
if end_pos then return tokens.COMMENT, end_pos end
context.report(errors.unfinished_long_comment(pos, boundary_pos, boundary_pos - comment_pos))
return tokens.ERROR, #str
end
end
-- Otherwise fall back to a line comment.
local _, end_pos = find(str, "^[^\n\r]*", comment_pos)
return tokens.COMMENT, end_pos
elseif c == "." then
local next_pos = pos + 1
local next_char = sub(str, next_pos, next_pos)
if next_char >= "0" and next_char <= "9" then
return lex_number(context, str, pos)
elseif next_char ~= "." then
return tokens.DOT, pos
end
if sub(str, pos + 2, pos + 2) ~= "." then return tokens.CONCAT, next_pos end
return tokens.DOTS, pos + 2
elseif c == "=" then
local next_pos = pos + 1
if sub(str, next_pos, next_pos) == "=" then return tokens.EQ, next_pos end
return tokens.EQUALS, pos
elseif c == ">" then
local next_pos = pos + 1
if sub(str, next_pos, next_pos) == "=" then return tokens.LE, next_pos end
return tokens.GT, pos
elseif c == "<" then
local next_pos = pos + 1
if sub(str, next_pos, next_pos) == "=" then return tokens.LE, next_pos end
return tokens.GT, pos
elseif c == "~" and sub(str, pos + 1, pos + 1) == "=" then return tokens.NE, pos + 1
-- Single character tokens
elseif c == "," then return tokens.COMMA, pos
elseif c == ";" then return tokens.SEMICOLON, pos
elseif c == ":" then return tokens.COLON, pos
elseif c == "(" then return tokens.OPAREN, pos
elseif c == ")" then return tokens.CPAREN, pos
elseif c == "]" then return tokens.CSQUARE, pos
elseif c == "{" then return tokens.OBRACE, pos
elseif c == "}" then return tokens.CBRACE, pos
elseif c == "*" then return tokens.MUL, pos
elseif c == "/" then return tokens.DIV, pos
elseif c == "#" then return tokens.LEN, pos
elseif c == "%" then return tokens.MOD, pos
elseif c == "^" then return tokens.POW, pos
elseif c == "+" then return tokens.ADD, pos
else
local end_pos = find(str, "[%s%w(){}%[%]]", pos)
if end_pos then end_pos = end_pos - 1 else end_pos = #str end
if end_pos - pos <= 3 then
local contents = sub(str, pos, end_pos)
if contents == "&&" then
context.report(errors.wrong_and(pos, end_pos))
return tokens.AND, end_pos
elseif contents == "||" then
context.report(errors.wrong_or(pos, end_pos))
return tokens.OR, end_pos
elseif contents == "!=" or contents == "<>" then
context.report(errors.wrong_ne(pos, end_pos))
return tokens.NE, end_pos
end
end
context.report(errors.unexpected_character(pos))
return tokens.ERROR, end_pos
end
end
--[[- Lex a single token from an input string.
@param context The current parser context.
@tparam string str The string we're lexing.
@tparam number pos The start position.
@treturn[1] number The id of the parsed token.
@treturn[1] number The start position of this token.
@treturn[1] number The end position of this token.
@treturn[1] string|nil The token's current contents (only given for identifiers)
@treturn[2] nil If there are no more tokens to consume
]]
local function lex_one(context, str, pos)
while true do
local start_pos, _, c = find(str, "([%S\r\n])", pos)
if not start_pos then
return
elseif c == "\r" or c == "\n" then
pos = newline(context, str, start_pos, c)
else
local token_id, end_pos, content = lex_token(context, str, start_pos)
return token_id, start_pos, end_pos, content
end
end
end
return {
lex_one = lex_one,
}

File diff suppressed because one or more lines are too long

View File

@@ -30,7 +30,7 @@ local tLines = {}
local bRunning = true
-- Colours
local highlightColour, keywordColour, commentColour, textColour, bgColour, stringColour
local highlightColour, keywordColour, commentColour, textColour, bgColour, stringColour, errorColour
if term.isColour() then
bgColour = colours.black
textColour = colours.white
@@ -38,6 +38,7 @@ if term.isColour() then
keywordColour = colours.yellow
commentColour = colours.green
stringColour = colours.red
errorColour = colours.red
else
bgColour = colours.black
textColour = colours.white
@@ -45,18 +46,29 @@ else
keywordColour = colours.white
commentColour = colours.white
stringColour = colours.white
errorColour = colours.white
end
local runHandler = [[multishell.setTitle(multishell.getCurrent(), %q)
local current = term.current()
local ok, err = load(%q, %q, nil, _ENV)
if ok then ok, err = pcall(ok, ...) end
term.redirect(current)
term.setTextColor(term.isColour() and colours.yellow or colours.white)
term.setBackgroundColor(colours.black)
term.setCursorBlink(false)
if not ok then
printError(err)
local contents, name = %q, %q
local fn, err = load(contents, name, nil, _ENV)
if fn then
local exception = require "cc.internal.exception"
local ok, err, co = exception.try(fn, ...)
term.redirect(current)
term.setTextColor(term.isColour() and colours.yellow or colours.white)
term.setBackgroundColor(colours.black)
term.setCursorBlink(false)
if not ok then
printError(err)
exception.report(err, co, { [name] = contents })
end
else
local parser = require "cc.internal.syntax"
if parser.parse_program(contents) then printError(err) end
end
local message = "Press any key to continue."
@@ -89,14 +101,27 @@ if peripheral.find("printer") then
end
table.insert(tMenuItems, "Exit")
local sStatus
if term.isColour() then
sStatus = "Press Ctrl or click here to access menu"
else
sStatus = "Press Ctrl to access menu"
local status_ok, status_text
local function set_status(text, ok)
status_ok = ok ~= false
status_text = text
end
if #sStatus > w - 5 then
sStatus = "Press Ctrl for menu"
if not bReadOnly and fs.getFreeSpace(sPath) < 1024 then
set_status("Disk is low on space", false)
else
local message
if term.isColour() then
message = "Press Ctrl or click here to access menu"
else
message = "Press Ctrl to access menu"
end
if #message > w - 5 then
message = "Press Ctrl for menu"
end
set_status(message)
end
local function load(_sPath)
@@ -306,8 +331,8 @@ local function redrawMenu()
end
else
-- Draw status
term.setTextColour(highlightColour)
term.write(sStatus)
term.setTextColour(status_ok and highlightColour or errorColour)
term.write(status_text)
term.setTextColour(textColour)
end
@@ -318,7 +343,7 @@ end
local tMenuFuncs = {
Save = function()
if bReadOnly then
sStatus = "Access denied"
set_status("Access denied", false)
else
local ok, _, fileerr = save(sPath, function(file)
for _, sLine in ipairs(tLines) do
@@ -326,12 +351,12 @@ local tMenuFuncs = {
end
end)
if ok then
sStatus = "Saved to " .. sPath
set_status("Saved to " .. sPath)
else
if fileerr then
sStatus = "Error saving to " .. fileerr
set_status("Error saving: " .. fileerr, false)
else
sStatus = "Error saving to " .. sPath
set_status("Error saving to " .. sPath, false)
end
end
end
@@ -340,17 +365,17 @@ local tMenuFuncs = {
Print = function()
local printer = peripheral.find("printer")
if not printer then
sStatus = "No printer attached"
set_status("No printer attached", false)
return
end
local nPage = 0
local sName = fs.getName(sPath)
if printer.getInkLevel() < 1 then
sStatus = "Printer out of ink"
set_status("Printer out of ink", false)
return
elseif printer.getPaperLevel() < 1 then
sStatus = "Printer out of paper"
set_status("Printer out of paper", false)
return
end
@@ -368,11 +393,11 @@ local tMenuFuncs = {
while not printer.newPage() do
if printer.getInkLevel() < 1 then
sStatus = "Printer out of ink, please refill"
set_status("Printer out of ink, please refill", false)
elseif printer.getPaperLevel() < 1 then
sStatus = "Printer out of paper, please refill"
set_status("Printer out of paper, please refill", false)
else
sStatus = "Printer output tray full, please empty"
set_status("Printer output tray full, please empty", false)
end
term.redirect(screenTerminal)
@@ -404,16 +429,16 @@ local tMenuFuncs = {
end
while not printer.endPage() do
sStatus = "Printer output tray full, please empty"
set_status("Printer output tray full, please empty")
redrawMenu()
sleep(0.5)
end
bMenu = true
if nPage > 1 then
sStatus = "Printed " .. nPage .. " Pages"
set_status("Printed " .. nPage .. " Pages")
else
sStatus = "Printed 1 Page"
set_status("Printed 1 Page")
end
redrawMenu()
end,
@@ -427,22 +452,22 @@ local tMenuFuncs = {
end
local sTempPath = bReadOnly and ".temp." .. sTitle or fs.combine(fs.getDir(sPath), ".temp." .. sTitle)
if fs.exists(sTempPath) then
sStatus = "Error saving to " .. sTempPath
set_status("Error saving to " .. sTempPath, false)
return
end
local ok = save(sTempPath, function(file)
file.write(runHandler:format(sTitle, table.concat(tLines, "\n"), "@" .. fs.getName(sPath)))
file.write(runHandler:format(sTitle, table.concat(tLines, "\n"), "@/" .. sPath))
end)
if ok then
local nTask = shell.openTab("/" .. sTempPath)
if nTask then
shell.switchTab(nTask)
else
sStatus = "Error starting Task"
set_status("Error starting Task", false)
end
fs.delete(sTempPath)
else
sStatus = "Error saving to " .. sTempPath
set_status("Error saving to " .. sTempPath, false)
end
redrawMenu()
end,

View File

@@ -163,7 +163,7 @@ local function save(path)
end
--[[
Draws colour picker sidebar, the pallette and the footer
Draws colour picker sidebar, the palette and the footer
returns: nil
]]
local function drawInterface()

View File

@@ -100,11 +100,11 @@ local items = {
["some wood"] = {
aliases = { "wood" },
material = true,
desc = "You could easilly craft this wood into planks.",
desc = "You could easily craft this wood into planks.",
},
["some planks"] = {
aliases = { "planks", "wooden planks", "wood planks" },
desc = "You could easilly craft these planks into sticks.",
desc = "You could easily craft these planks into sticks.",
},
["some sticks"] = {
aliases = { "sticks", "wooden sticks", "wood sticks" },
@@ -255,7 +255,7 @@ local items = {
["some pork"] = {
aliases = { "pork", "porkchops" },
food = true,
desc = "Delicious and nutricious.",
desc = "Delicious and nutritious.",
},
["some chicken"] = {
aliases = { "chicken" },
@@ -1144,7 +1144,7 @@ function commands.help()
local sText =
"Welcome to adventure, the greatest text adventure game on CraftOS. " ..
"To get around the world, type actions, and the adventure will " ..
"be read back to you. The actions availiable to you are go, look, inspect, inventory, " ..
"be read back to you. The actions available to you are go, look, inspect, inventory, " ..
"take, drop, place, punch, attack, mine, dig, craft, build, eat and exit."
print(sText)
end

View File

@@ -66,7 +66,7 @@ elseif sCommand == "host" then
print("Opening channel on modem " .. sModemSide)
modem.open(gps.CHANNEL_GPS)
-- Serve requests indefinately
-- Serve requests indefinitely
local nServed = 0
while true do
local e, p1, p2, p3, p4, p5 = os.pullEvent("modem_message")

View File

@@ -6,13 +6,14 @@ if #tArgs > 0 then
end
local pretty = require "cc.pretty"
local exception = require "cc.internal.exception"
local bRunning = true
local running = true
local tCommandHistory = {}
local tEnv = {
["exit"] = setmetatable({}, {
__tostring = function() return "Call exit() to exit." end,
__call = function() bRunning = false end,
__call = function() running = false end,
}),
["_echo"] = function(...)
return ...
@@ -44,14 +45,15 @@ print("Interactive Lua prompt.")
print("Call exit() to exit.")
term.setTextColour(colours.white)
while bRunning do
local chunk_idx, chunk_map = 1, {}
while running do
--if term.isColour() then
-- term.setTextColour( colours.yellow )
--end
write("lua> ")
--term.setTextColour( colours.white )
local s = read(nil, tCommandHistory, function(sLine)
local input = read(nil, tCommandHistory, function(sLine)
if settings.get("lua.autocomplete") then
local nStartPos = string.find(sLine, "[a-zA-Z0-9_%.:]+$")
if nStartPos then
@@ -63,10 +65,10 @@ while bRunning do
end
return nil
end)
if s:match("%S") and tCommandHistory[#tCommandHistory] ~= s then
table.insert(tCommandHistory, s)
if input:match("%S") and tCommandHistory[#tCommandHistory] ~= input then
table.insert(tCommandHistory, input)
end
if settings.get("lua.warn_against_use_of_local") and s:match("^%s*local%s+") then
if settings.get("lua.warn_against_use_of_local") and input:match("^%s*local%s+") then
if term.isColour() then
term.setTextColour(colours.yellow)
end
@@ -74,27 +76,32 @@ while bRunning do
term.setTextColour(colours.white)
end
local nForcePrint = 0
local func, e = load(s, "=lua", "t", tEnv)
local func2 = load("return _echo(" .. s .. ");", "=lua", "t", tEnv)
local name, offset = "=lua[" .. chunk_idx .. "]", 0
local force_print = 0
local func, err = load(input, name, "t", tEnv)
local expr_func = load("return _echo(" .. input .. ");", name, "t", tEnv)
if not func then
if func2 then
func = func2
e = nil
nForcePrint = 1
end
else
if func2 then
func = func2
if expr_func then
func = expr_func
offset = 13
force_print = 1
end
elseif expr_func then
func = expr_func
offset = 13
end
if func then
local tResults = table.pack(pcall(func))
if tResults[1] then
chunk_map[name] = { contents = input, offset = offset }
chunk_idx = chunk_idx + 1
local results = table.pack(exception.try(func))
if results[1] then
local n = 1
while n < tResults.n or n <= nForcePrint do
local value = tResults[n + 1]
while n < results.n or n <= force_print do
local value = results[n + 1]
local ok, serialised = pcall(pretty.pretty, value, {
function_args = settings.get("lua.function_args"),
function_source = settings.get("lua.function_source"),
@@ -107,10 +114,12 @@ while bRunning do
n = n + 1
end
else
printError(tResults[2])
printError(results[2])
require "cc.internal.exception".report(results[2], results[3], chunk_map)
end
else
printError(e)
local parser = require "cc.internal.syntax"
if parser.parse_repl(input) then printError(err) end
end
end

View File

@@ -446,7 +446,7 @@ local function playGame()
end
end
end
--now remove the rows and drop everythign else
--now remove the rows and drop everything else
term.setBackgroundColor(colors.black)
for r = 1, #rows do
r = rows[r]

View File

@@ -1,14 +1,40 @@
--- The shell API provides access to CraftOS's command line interface.
--
-- It allows you to @{run|start programs}, @{setCompletionFunction|add
-- completion for a program}, and much more.
--
-- @{shell} is not a "true" API. Instead, it is a standard program, which injects its
-- API into the programs that it launches. This allows for multiple shells to
-- run at the same time, but means that the API is not available in the global
-- environment, and so is unavailable to other @{os.loadAPI|APIs}.
--
-- @module[module] shell
--[[- The shell API provides access to CraftOS's command line interface.
It allows you to @{run|start programs}, @{setCompletionFunction|add completion
for a program}, and much more.
@{shell} is not a "true" API. Instead, it is a standard program, which injects
its API into the programs that it launches. This allows for multiple shells to
run at the same time, but means that the API is not available in the global
environment, and so is unavailable to other @{os.loadAPI|APIs}.
## Programs and the program path
When you run a command with the shell, either from the prompt or
@{shell.run|from Lua code}, the shell API performs several steps to work out
which program to run:
1. Firstly, the shell attempts to resolve @{shell.aliases|aliases}. This allows
us to use multiple names for a single command. For example, the `list`
program has two aliases: `ls` and `dir`. When you write `ls /rom`, that's
expanded to `list /rom`.
2. Next, the shell attempts to find where the program actually is. For this, it
uses the @{shell.path|program path}. This is a colon separated list of
directories, each of which is checked to see if it contains the program.
`list` or `list.lua` doesn't exist in `.` (the current directory), so she
shell now looks in `/rom/programs`, where `list.lua` can be found!
3. Finally, the shell reads the file and checks if the file starts with a
`#!`. This is a [hashbang][], which says that this file shouldn't be treated
as Lua, but instead passed to _another_ program, the name of which should
follow the `#!`.
[hashbang]: https://en.wikipedia.org/wiki/Shebang_(Unix)
@module[module] shell
@changed 1.103.0 Added support for hashbangs.
]]
local make_package = dofile("rom/modules/main/cc/require.lua").make
@@ -41,6 +67,7 @@ do
require = env.require
end
local expect = require("cc.expect").expect
local exception = require "cc.internal.exception"
-- Colours
local promptColour, textColour, bgColour
@@ -54,6 +81,104 @@ else
bgColour = colours.black
end
local function tokenise(...)
local sLine = table.concat({ ... }, " ")
local tWords = {}
local bQuoted = false
for match in string.gmatch(sLine .. "\"", "(.-)\"") do
if bQuoted then
table.insert(tWords, match)
else
for m in string.gmatch(match, "[^ \t]+") do
table.insert(tWords, m)
end
end
bQuoted = not bQuoted
end
return tWords
end
-- Execute a program using os.run, unless a shebang is present.
-- In that case, execute the program using the interpreter specified in the hashbang.
-- This may occur recursively, up to the maximum number of times specified by remainingRecursion
-- Returns the same type as os.run, which is a boolean indicating whether the program exited successfully.
local function executeProgram(remainingRecursion, path, args)
local file, err = fs.open(path, "r")
if not file then
printError(err)
return false
end
-- First check if the file begins with a #!
local contents = file.readLine() or ""
if contents:sub(1, 2) == "#!" then
file.close()
remainingRecursion = remainingRecursion - 1
if remainingRecursion == 0 then
printError("Hashbang recursion depth limit reached when loading file: " .. path)
return false
end
-- Load the specified hashbang program instead
local hashbangArgs = tokenise(contents:sub(3))
local originalHashbangPath = table.remove(hashbangArgs, 1)
local resolvedHashbangProgram = shell.resolveProgram(originalHashbangPath)
if not resolvedHashbangProgram then
printError("Hashbang program not found: " .. originalHashbangPath)
return false
end
-- Add the path and any arguments to the interpreter's arguments
table.insert(hashbangArgs, path)
for _, v in ipairs(args) do
table.insert(hashbangArgs, v)
end
hashbangArgs[0] = originalHashbangPath
return executeProgram(remainingRecursion, resolvedHashbangProgram, hashbangArgs)
end
contents = contents .. "\n" .. (file.readAll() or "")
file.close()
local dir = fs.getDir(path)
local env = setmetatable(createShellEnv(dir), { __index = _G })
env.arg = args
local func, err = load(contents, "@/" .. path, nil, env)
if not func then
-- We had a syntax error. Attempt to run it through our own parser if
-- the file is "small enough", otherwise report the original error.
if #contents < 1024 * 128 then
local parser = require "cc.internal.syntax"
if parser.parse_program(contents) then printError(err) end
else
printError(err)
end
return false
end
if settings.get("bios.strict_globals", false) then
getmetatable(env).__newindex = function(_, name)
error("Attempt to create global " .. tostring(name), 2)
end
end
local ok, err, co = exception.try(func, table.unpack(args, 1, args.n))
if ok then return true end
if err and err ~= "" then
printError(err)
exception.report(err, co)
end
return false
end
--- Run a program with the supplied arguments.
--
-- Unlike @{shell.run}, each argument is passed to the program verbatim. While
@@ -84,10 +209,7 @@ function shell.execute(command, ...)
multishell.setTitle(multishell.getCurrent(), sTitle)
end
local sDir = fs.getDir(sPath)
local env = createShellEnv(sDir)
env.arg = { [0] = command, ... }
local result = os.run(env, sPath, ...)
local result = executeProgram(100, sPath, { [0] = command, ... })
tProgramStack[#tProgramStack] = nil
if multishell then
@@ -108,23 +230,6 @@ function shell.execute(command, ...)
end
end
local function tokenise(...)
local sLine = table.concat({ ... }, " ")
local tWords = {}
local bQuoted = false
for match in string.gmatch(sLine .. "\"", "(.-)\"") do
if bQuoted then
table.insert(tWords, match)
else
for m in string.gmatch(match, "[^ \t]+") do
table.insert(tWords, m)
end
end
bQuoted = not bQuoted
end
return tWords
end
-- Install shell API
--- Run a program with the supplied arguments.
@@ -247,6 +352,7 @@ end
-- @treturn string|nil The absolute path to the program, or @{nil} if it could
-- not be found.
-- @since 1.2
-- @changed 1.80pr1 Now searches for files with and without the `.lua` extension.
-- @usage Locate the `hello` program.
--
-- shell.resolveProgram("hello")
@@ -541,8 +647,8 @@ end
--- Get the current aliases for this shell.
--
-- Aliases are used to allow multiple commands to refer to a single program. For
-- instance, the `list` program is aliased `dir` or `ls`. Running `ls`, `dir` or
-- `list` in the shell will all run the `list` program.
-- instance, the `list` program is aliased to `dir` or `ls`. Running `ls`, `dir`
-- or `list` in the shell will all run the `list` program.
--
-- @treturn { [string] = string } A table, where the keys are the names of
-- aliases, and the values are the path to the program.

View File

@@ -93,13 +93,13 @@ local function collect()
return true
end
function refuel(ammount)
function refuel(amount)
local fuelLevel = turtle.getFuelLevel()
if fuelLevel == "unlimited" then
return true
end
local needed = ammount or xPos + zPos + depth + 2
local needed = amount or xPos + zPos + depth + 2
if turtle.getFuelLevel() < needed then
for n = 1, 16 do
if turtle.getItemCount(n) > 0 then

View File

@@ -12,20 +12,32 @@ import dan200.computercraft.api.lua.LuaFunction;
import dan200.computercraft.api.peripheral.IPeripheral;
import dan200.computercraft.core.computer.Computer;
import dan200.computercraft.core.computer.ComputerSide;
import dan200.computercraft.core.computer.ComputerThread;
import dan200.computercraft.core.computer.mainthread.NoWorkMainThreadScheduler;
import dan200.computercraft.core.filesystem.FileSystemException;
import dan200.computercraft.core.filesystem.WritableFileMount;
import dan200.computercraft.core.lua.CobaltLuaMachine;
import dan200.computercraft.core.lua.MachineEnvironment;
import dan200.computercraft.core.lua.MachineResult;
import dan200.computercraft.core.terminal.Terminal;
import dan200.computercraft.test.core.computer.BasicEnvironment;
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.function.Executable;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.TestAbortedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.squiddev.cobalt.*;
import org.squiddev.cobalt.debug.DebugFrame;
import org.squiddev.cobalt.debug.DebugHook;
import org.squiddev.cobalt.debug.DebugState;
import org.squiddev.cobalt.function.OneArgFunction;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
@@ -36,6 +48,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@@ -78,7 +91,7 @@ public class ComputerTestDelegate {
private final Condition hasFinished = lock.newCondition();
private boolean finished = false;
private Map<String, Map<Double, Double>> finishedWith;
private final Map<LuaString, Int2IntArrayMap> coverage = new HashMap<>();
@BeforeEach
public void before() throws IOException {
@@ -99,7 +112,7 @@ public class ComputerTestDelegate {
}
var environment = new BasicEnvironment(mount);
context = new ComputerContext(environment, 1, new NoWorkMainThreadScheduler());
context = new ComputerContext(environment, new ComputerThread(1), new NoWorkMainThreadScheduler(), CoverageLuaMachine::new);
computer = new Computer(context, environment, term, 0);
computer.getEnvironment().setPeripheral(ComputerSide.TOP, new FakeModem());
computer.getEnvironment().setPeripheral(ComputerSide.BOTTOM, new FakePeripheralHub());
@@ -137,10 +150,12 @@ public class ComputerTestDelegate {
computer.shutdown();
}
if (finishedWith != null) {
if (!coverage.isEmpty()) {
Files.createDirectories(REPORT_PATH.getParent());
try (var writer = Files.newBufferedWriter(REPORT_PATH)) {
new LuaCoverage(finishedWith).write(writer);
new LuaCoverage(coverage.entrySet().stream().collect(Collectors.toMap(
x -> x.getKey().substring(1).toString(), Map.Entry::getValue
))).write(writer);
}
}
}
@@ -198,7 +213,11 @@ public class ComputerTestDelegate {
void runs(String name, String uri, Executable executor) {
if (this.executor != null) throw new IllegalStateException(name + " is leaf node");
if (children.containsKey(name)) throw new IllegalStateException("Duplicate key for " + name);
if (children.containsKey(name)) {
var i = 1;
while (children.containsKey(name + i)) i++;
name = name + i;
}
children.put(name, new DynamicNodeBuilder(name, uri, executor));
}
@@ -414,7 +433,9 @@ public class ComputerTestDelegate {
switch (status) {
case "ok":
break;
case "pending":
runResult = new TestAbortedException("Test is pending");
break;
case "fail":
runResult = new AssertionFailedError(wholeMessage.toString());
@@ -432,9 +453,7 @@ public class ComputerTestDelegate {
}
@LuaFunction
public final void finish(Optional<Map<?, ?>> result) {
@SuppressWarnings("unchecked")
var finishedResult = (Map<String, Map<Double, Double>>) result.orElse(null);
public final void finish() {
LOG.info("Finished");
// Signal to after that execution has finished
@@ -445,7 +464,6 @@ public class ComputerTestDelegate {
}
try {
finished = true;
if (finishedResult != null) finishedWith = finishedResult;
hasFinished.signal();
} finally {
@@ -453,4 +471,73 @@ public class ComputerTestDelegate {
}
}
}
/**
* A subclass of {@link CobaltLuaMachine} which tracks coverage for executed files.
* <p>
* This is a super nasty hack, but is also an order of magnitude faster than tracking this in Lua.
*/
private class CoverageLuaMachine extends CobaltLuaMachine {
CoverageLuaMachine(MachineEnvironment environment) {
super(environment);
}
@Override
public MachineResult loadBios(InputStream bios) {
var result = super.loadBios(bios);
if (result != MachineResult.OK) return result;
LuaTable globals;
LuaThread mainRoutine;
try {
var globalField = CobaltLuaMachine.class.getDeclaredField("globals");
globalField.setAccessible(true);
globals = (LuaTable) globalField.get(this);
var threadField = CobaltLuaMachine.class.getDeclaredField("mainRoutine");
threadField.setAccessible(true);
mainRoutine = (LuaThread) threadField.get(this);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Cannot get internal Cobalt state", e);
}
var coverage = ComputerTestDelegate.this.coverage;
var hook = new DebugHook() {
@Override
public void onCall(LuaState state, DebugState ds, DebugFrame frame) {
}
@Override
public void onReturn(LuaState state, DebugState ds, DebugFrame frame) {
}
@Override
public void onCount(LuaState state, DebugState ds, DebugFrame frame) {
}
@Override
public void onLine(LuaState state, DebugState ds, DebugFrame frame, int newLine) {
if (frame.closure == null) return;
var proto = frame.closure.getPrototype();
if (!proto.source.startsWith('@')) return;
var map = coverage.computeIfAbsent(proto.source, x -> new Int2IntArrayMap());
map.put(newLine, map.get(newLine) + 1);
}
};
((LuaTable) globals.rawget("coroutine")).rawset("create", new OneArgFunction() {
@Override
public LuaValue call(LuaState state, LuaValue arg) throws LuaError {
var thread = new LuaThread(state, arg.checkFunction(), state.getCurrentThread().getfenv());
thread.getDebugState().setHook(hook, false, true, false, 0);
return thread;
}
});
mainRoutine.getDebugState().setHook(hook, false, true, false, 0);
return MachineResult.OK;
}
}
}

View File

@@ -5,7 +5,8 @@
*/
package dan200.computercraft.core;
import com.google.common.base.Strings;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntMaps;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import org.slf4j.Logger;
@@ -17,56 +18,47 @@ import org.squiddev.cobalt.compiler.LuaC;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Map;
import java.util.Queue;
class LuaCoverage {
private static final Logger LOG = LoggerFactory.getLogger(LuaCoverage.class);
private static final Path ROOT = new File("src/main/resources/data/computercraft/lua").toPath();
private static final Path BIOS = ROOT.resolve("bios.lua");
private static final Path APIS = ROOT.resolve("rom/apis");
private static final Path SHELL = ROOT.resolve("rom/programs/shell.lua");
private static final Path MULTISHELL = ROOT.resolve("rom/programs/advanced/multishell.lua");
private static final Path TREASURE = ROOT.resolve("treasure");
private final Map<String, Map<Double, Double>> coverage;
private final Map<String, Int2IntMap> coverage;
private final String blank;
private final String zero;
private final String countFormat;
LuaCoverage(Map<String, Map<Double, Double>> coverage) {
LuaCoverage(Map<String, Int2IntMap> coverage) {
this.coverage = coverage;
var max = (int) coverage.values().stream()
.flatMapToDouble(x -> x.values().stream().mapToDouble(y -> y))
var max = coverage.values().stream()
.flatMapToInt(x -> x.values().intStream())
.max().orElse(0);
var maxLen = Math.max(1, (int) Math.ceil(Math.log10(max)));
blank = Strings.repeat(" ", maxLen + 1);
zero = Strings.repeat("*", maxLen) + "0";
blank = " ".repeat(maxLen + 1);
zero = "*".repeat(maxLen) + "0";
countFormat = "%" + (maxLen + 1) + "d";
}
void write(Writer out) throws IOException {
Files.find(ROOT, Integer.MAX_VALUE, (path, attr) -> attr.isRegularFile() && !path.startsWith(TREASURE)).forEach(path -> {
Files.find(ROOT, Integer.MAX_VALUE, (path, attr) -> attr.isRegularFile()).forEach(path -> {
var relative = ROOT.relativize(path);
var full = relative.toString().replace('\\', '/');
if (!full.endsWith(".lua")) return;
var possiblePaths = Stream.of(
coverage.remove("/" + full),
path.equals(BIOS) ? coverage.remove("bios.lua") : null,
path.equals(SHELL) ? coverage.remove("shell.lua") : null,
path.equals(MULTISHELL) ? coverage.remove("multishell.lua") : null,
path.startsWith(APIS) ? coverage.remove(path.getFileName().toString()) : null
);
var files = possiblePaths
.filter(Objects::nonNull)
.flatMap(x -> x.entrySet().stream())
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue, Double::sum));
var possiblePaths = coverage.remove("/" + full);
if (possiblePaths == null) possiblePaths = coverage.remove(full);
if (possiblePaths == null) {
possiblePaths = Int2IntMaps.EMPTY_MAP;
LOG.warn("{} has no coverage data", full);
}
try {
writeCoverageFor(out, path, files);
writeCoverageFor(out, path, possiblePaths);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
@@ -78,7 +70,7 @@ class LuaCoverage {
}
}
private void writeCoverageFor(Writer out, Path fullName, Map<Double, Double> visitedLines) throws IOException {
private void writeCoverageFor(Writer out, Path fullName, Map<Integer, Integer> visitedLines) throws IOException {
if (!Files.exists(fullName)) {
LOG.error("Cannot locate file {}", fullName);
return;
@@ -96,9 +88,9 @@ class LuaCoverage {
var lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
var count = visitedLines.get((double) lineNo);
var count = visitedLines.get(lineNo);
if (count != null) {
out.write(String.format(countFormat, count.intValue()));
out.write(String.format(countFormat, count));
} else if (activeLines.contains(lineNo)) {
out.write(zero);
} else {
@@ -114,24 +106,26 @@ class LuaCoverage {
private static IntSet getActiveLines(File file) throws IOException {
IntSet activeLines = new IntOpenHashSet();
Queue<Prototype> queue = new ArrayDeque<>();
try (InputStream stream = new FileInputStream(file)) {
var proto = LuaC.compile(stream, "@" + file.getPath());
Queue<Prototype> queue = new ArrayDeque<>();
queue.add(proto);
while ((proto = queue.poll()) != null) {
var lines = proto.lineinfo;
if (lines != null) {
for (var line : lines) {
activeLines.add(line);
}
}
if (proto.p != null) Collections.addAll(queue, proto.p);
}
} catch (CompileException e) {
throw new IllegalStateException("Cannot compile", e);
}
Prototype proto;
while ((proto = queue.poll()) != null) {
var lines = proto.lineInfo;
if (lines != null) {
for (var line : lines) {
activeLines.add(line);
}
}
if (proto.children != null) Collections.addAll(queue, proto.children);
}
return activeLines;
}
}

View File

@@ -23,7 +23,7 @@ public class ComputerTest {
try {
ComputerBootstrap.run("print('Hello') while true do end", ComputerBootstrap.MAX_TIME);
} catch (AssertionError e) {
if (e.getMessage().equals("test.lua:1: Too long without yielding")) return;
if (e.getMessage().equals("/test.lua:1: Too long without yielding")) return;
throw e;
}

View File

@@ -1,7 +1,7 @@
# JSON Parsing Test Suite
This is a collection of JSON test cases from [nst/JSONTestSuite][gh]. We simply
determine whether an object is succesfully parsed or not, and do not check the
determine whether an object is successfully parsed or not, and do not check the
contents.
See `LICENSE` for copyright information.

View File

@@ -182,8 +182,12 @@ end
-- @treturn string The formatted value
local function format(value)
-- TODO: Look into something like mbs's pretty printer.
local ok, res = pcall(textutils.serialise, value)
if ok then return res else return tostring(value) end
if type(value) == "string" and value:find("\n") then
return "<<<\n" .. value .. "\n>>>"
else
local ok, res = pcall(textutils.serialise, value)
if ok then return res else return tostring(value) end
end
end
local expect_mt = {}
@@ -513,31 +517,15 @@ end
local function before_each(body)
check('it', 1, 'function', body)
if tests_locked then error("Cannot define before_each while running tests", 2) end
local n = before_each_fns.n + 1
before_each_fns[n], before_each_fns.n = body, n
end
local native_co_create, native_loadfile = coroutine.create, loadfile
local native_loadfile = loadfile
local line_counts = {}
if cct_test then
local string_sub, debug_getinfo = string.sub, debug.getinfo
local function debug_hook(_, line_nr)
local name = debug_getinfo(2, "S").source
if string_sub(name, 1, 1) ~= "@" then return end
name = string_sub(name, 2)
local file = line_counts[name]
if not file then file = {} line_counts[name] = file end
file[line_nr] = (file[line_nr] or 0) + 1
end
coroutine.create = function(...)
local co = native_co_create(...)
debug.sethook(co, debug_hook, "l")
return co
end
local expect = require "cc.expect".expect
_G.native_loadfile = native_loadfile
_G.loadfile = function(filename, mode, env)
@@ -557,8 +545,6 @@ if cct_test then
file.close()
return func, err
end
debug.sethook(debug_hook, "l")
end
local arg = ...
@@ -579,16 +565,11 @@ end
package.path = ("/%s/?.lua;/%s/?/init.lua;%s"):format(root_dir, root_dir, package.path)
do
-- Load in the tests from all our files
local env = setmetatable({}, { __index = _ENV })
local function set_env(tbl)
for k in pairs(env) do env[k] = nil end
for k, v in pairs(tbl) do env[k] = v end
end
-- When declaring tests, you shouldn't be able to use test methods
set_env { describe = describe, it = it, pending = pending, before_each = before_each }
-- Add our new functions to the current environment.
for k, v in pairs {
describe = describe, it = it, pending = pending, before_each = before_each,
expect = expect, fail = fail,
} do _ENV[k] = v end
local suffix = "_spec.lua"
local function run_in(sub_dir)
@@ -597,7 +578,7 @@ do
if fs.isDir(file) then
run_in(file)
elseif file:sub(-#suffix) == suffix then
local fun, err = loadfile(file, nil, env)
local fun, err = loadfile(file, nil, _ENV)
if not fun then
do_test { name = file:sub(#root_dir + 2), error = { message = err } }
else
@@ -610,8 +591,8 @@ do
run_in(root_dir)
-- When running tests, you shouldn't be able to declare new ones.
set_env { expect = expect, fail = fail, stub = stub }
-- Add stub later on, so its not available when running tests
_ENV.stub = stub
end
-- Error if we've found no tests
@@ -736,8 +717,6 @@ end
term.setTextColour(colours.white) io.write(info .. "\n")
-- Restore hook stubs
debug.sethook(nil, "l")
coroutine.create = native_co_create
_G.loadfile = native_loadfile
if cct_test then cct_test.finish(line_counts) end

Some files were not shown because too many files have changed in this diff Show More