195
\$\begingroup\$

Try to write some code in your language and make it not satisfying our criteria of being a programming language any more.

A language satisfies our criteria (simplified version for this challenge) of being a programming language if:

  • It can read user input representing tuples of positive integers in some way.
  • It can output at least two different possible results depending on the input.
  • It can take two positive integers and add them (and the result can affect the output).
  • It can take a positive integer and decide whether it is a prime (and the result can affect the output).
  • For the purpose of this challenge, any kind of output that isn't an allowed output method for a normal challenge is ignored. So it doesn't matter whether the program can also play a piece of music, or posting via HTTP, etc.
  • Update: You can also choose one or some of the allowed output methods, and ignore all the others. But you must use the same definition everywhere in the following criteria. And if your program can disable more than one output methods — that worths more upvotes.

Examples like making it not able to output, or disabling all the loop constructs so it won't be able to do primality test and making sure the user cannot re-enable them.

You should leave a place for inserting new code. By default, it is at the end of your code. If we consider putting the source code in that place in your answer and running the full code as a complete program the interpreter of a new language, that language should not satisfy the criteria.

But the inserted code must be executed in such a way like a language satisfying the criteria:

  • The inserted code must be grammatically the same as something (say it's a code block in the following criteria) that generally do satisfy the criteria, from the perspective of whoever wants to write a syntax highlighter. So it cannot be in a string, comment, etc.
  • The inserted code must be actually executed, in a way it is supposed to satisfy the criteria. So it cannot be in an unused function or sizeof in C, you cannot just execute only a non-functional part in the code, and you cannot put it after an infinite loop, etc.
  • You can't limit the number of possible grammatically correct programs generated this way. If there is already something like a length limit in the language you are using, it shouldn't satisfy the criteria even if this limit is removed.
  • You can't modify or "use up" the content of input / output, but you can prevent them from being accessed.
  • These criteria usually only applies to languages without explicit I/O:
    • Your code should redirect the user input (that contains informations of arbitrary length) to the inserted code, if a code block isn't usually able to get the user input directly / explicitly in the language you are using.
    • Your code should print the returned value of the inserted code, if a code block isn't usually able to output things directly / explicitly in the language you are using.
    • In case you print the returned value, and it is typed in the language you are using, the returned type should be able to have 2 different practically possible values. For example, you cannot use the type struct {} or struct {private:int x;} in C++.

This is popularity-contest. The highest voted valid answer (so nobody spotted an error or all errors are fixed) wins.

Clarifications

  • You shouldn't modify the code in the text form, but can change the syntax before the code is interpreted or compiled.
  • You can do other things while the code is running. But the reason that it doesn't satisfy the criteria should be within the inserted code itself. It can error because of the interference of another thread, but not just be killed by another thread.
  • All the specs basically means it should be grammatically likely satisfying the criteria if all the built-ins were not changed but not actually do. It's fine if you find any non-grammatical workarounds, such as passing the parameters to the code block correctly, but make them not able to be used in some way.
  • Again, the inserted code must be actually executed. Code after an infinite loop or crashing is considered "not actually executed", thus not valid. Those answers might be interesting, but there are already some other infinite loop or crashing questions on this site, and you may find a more appropriate one to answer. If not, consider asking a new question. Examples of those questions are:

Leaderboard

var QUESTION_ID=61115/*,OVERRIDE_USER=8478*/;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,/*getComments()*/(more_answers?getAnswers():process())}})}/*function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}*/function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),score:s.score,language:a[1],lang:jQuery('<div>').html(a[1]).text(),link:s.share_link})}),e.sort(function(e,s){var r=e.score,a=s.score;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.score!=a&&(n=r),a=e.score,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",e.n=n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.score).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text())/*,s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}*/});var t=e/*[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o])*/;t.sort(function(e,s){return (e.lang.toUpperCase()>s.lang.toUpperCase())-(e.lang.toUpperCase()<s.lang.toUpperCase())||(e.lang>s.lang)-(e.lang<s.lang)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{PLACE}}",o.n).replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.score).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<(?:h\d|(?!.*<h\d>)p)>\s*((?:[^,;(\s]| +[^-,;(\s])+)(?=(?: *(?:[,;(]| -).*?)?\s*<\/(h\d|p)>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;float:left}table{width:250px}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Sorted by Language</h2> <table class="language-list"> <thead> <tr><td></td><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{PLACE}}</td><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
  • \$\begingroup\$ Am I allowed to change the code before executing it? Also, can I run other code whilst I am running the code given? \$\endgroup\$ – Blue Oct 18 '15 at 12:30
  • 21
    \$\begingroup\$ This could have made a really great cops and robbers challenge I think. \$\endgroup\$ – DankMemes Oct 18 '15 at 23:07
  • 6
    \$\begingroup\$ @DankMemes Agreed. As it stands, it's much too vague, and most answers would be invalidated by finding a workaround. CnR with this premise would be delightful. \$\endgroup\$ – Mego Oct 18 '15 at 23:54
  • 3
    \$\begingroup\$ So then it seems to be saying that in languages with explicit IO it's permissible to do completely boring things like reading and discarding the contents of stdin. It sets up a completely unfair playing field where some languages require you to carefully handle the IO for the inserted code, and other languages allow you to trash it and deny IO to the inserted code. \$\endgroup\$ – Peter Taylor Oct 19 '15 at 12:28
  • 2
    \$\begingroup\$ Are we allowed to use a language that's already unusable to begin with? (JavaScript for example) \$\endgroup\$ – 12Me21 Oct 17 '17 at 14:23

80 Answers 80

5
\$\begingroup\$

GolfScript

"#{def eval(s) end}":+:%:/:,:*:do:while:until

The series of :foo replaces all of the looping operators and addition and concatenation, but that's not sufficient. It's also necessary to prevent deferring the computation to Ruby's string interpolation, which I accomplish by replacing Ruby's eval operator using a string interpolation. String literals which occur later in the source code will be passed through my no-op eval rather than the built-in one.

The reason it's necessary to replace all of the looping operators, even such innocuous ones as ,, is that primality testing doesn't require unbounded looping. E.g. the following uses only , in its three forms (range, filter, len) to do primality testing:

~.,2>{1$\%!},,\;

The reason for replacing + is that jimmy23013 proposed using quining to get a looping construct. The specific implementation he provided doesn't work because by clobbering foo I've also clobbered the (standard) interpreter's way of parsing strings, but I expect it could be reworked using blocks instead of strings so I'm playing it safe.

\$\endgroup\$
  • \$\begingroup\$ Primality test is still possible: ~.1>2\'3$3$\'@2$-@@2$0>!.+.+.+.+.+.+>.~\'.~;;!!@&@)\@3$3$>.+.+.+.+.+.+.+>.~'.~;\;\;. Without eval strings and numbers can't be specified directly, but there are workarounds like n[n!!.+.+.+.+.+.+]+. \$\endgroup\$ – jimmy23013 Oct 22 '15 at 12:01
  • \$\begingroup\$ Seems to give an error in the online tester; I'll try it at home later. Is the idea basically to use a quine technique to get a loop? \$\endgroup\$ – Peter Taylor Oct 22 '15 at 12:37
  • \$\begingroup\$ Yes. It doesn't work with "#{def eval(s) end}" directly and need some more complex workaround, which I'm not bothered to implement yet. \$\endgroup\$ – jimmy23013 Oct 22 '15 at 14:51
  • \$\begingroup\$ Why not just block ~? Those .+.+... can be replaced with 1000 0 if. \$\endgroup\$ – jimmy23013 Oct 25 '15 at 14:37
  • 1
    \$\begingroup\$ Why not just block everything...? \$\endgroup\$ – Lynn Dec 29 '15 at 2:11
5
\$\begingroup\$

Forth

0 set-order

Basically, tell the interpreter/compiler that there are no dictionaries of known instructions. It can still read numbers (because they're not instructions) and they'll go on the stack if interpreting, but you can not issue any instructions about what to do with them, nor can you restore the search order because that would require issuing an instruction.

\$\endgroup\$
5
\$\begingroup\$

Z80 assembler

Two bytes are enough to completely hang any Z80 based system:

di 
halt

aka "Disable interrupts, then halt until an interrupt arrives". Yeah, sure!

EDIT: I had missed the "code that crashes doesn't count" part in the question, so I guess that this does not qualify.

\$\endgroup\$
5
\$\begingroup\$

Java

I decided to do something little bit nasty and break java, by using little bit less code than here

       public class a {

            static {
                final SecurityManager securityManager = new SecurityManager() {
                    @Override
                    public void checkPackageAccess(String pkg) {
                        throw new RuntimeException("broken");
                    }
                };
                java.lang.System.setSecurityManager(securityManager);

            }

            public static void main(String[] args) throws Exception {
             //and here goes your code...

            }
        }
\$\endgroup\$
  • \$\begingroup\$ You know, I can just do this. Not sure if that counts though. \$\endgroup\$ – Benjamin Urquhart Jun 2 at 0:29
  • \$\begingroup\$ I don't think that counts as a crack. \$\endgroup\$ – pppery Sep 4 at 22:10
  • \$\begingroup\$ @BenjaminUrquhart fair point, fixed \$\endgroup\$ – user902383 Sep 5 at 6:55
  • 1
    \$\begingroup\$ If you wish to subject your answer to "cracks" that consist of adding code to the end (which I don't think are valid), then your fix can still be worked around. \$\endgroup\$ – pppery Sep 11 at 1:46
  • \$\begingroup\$ Found a "crack" that is contained within the main function. Takes 2 ints as arguments and outputs to stderr via an exception with a message set to the sum of those values. Will link once I can find a way to make it fit in a comment. \$\endgroup\$ – Benjamin Urquhart Sep 15 at 21:06
4
\$\begingroup\$

Javascript

Tested in Chrome.

Object.defineProperty(document,"body",{get:function(){return null}});
Object.defineProperty(document,"innerHTML",{set:function(){}});
Object.defineProperty(HTMLElement.prototype,"innerHTML",{set:function(){}});
Object.defineProperty(HTMLElement.prototype,"innerText",{set:function(){}});
HTMLElement.prototype.appendChild=document.createElement=document.getElementsByName=document.getElementsByClassName=document.getElementsByTagName=document.getElementsByTagNameNS=document.getElementById=document.write=document.writeln=console=document.querySelector=document.querySelectorAll=alert=setTimeout=prompt=confirm=open=Array=Array.prototype.constructor=Object=Object.prototype.constructor=Object.prototype.toString=null;
try{var window = {}; with(window){/*code*/} }catch(e){}

Browser javascript is really hard to break.

\$\endgroup\$
  • \$\begingroup\$ document.body.innerHTML="<iframe src=\"javascript:'<script>alert(prompt(\\\'Hello!\\\',\\\'\\\'));</script>'\">" \$\endgroup\$ – user2428118 Oct 20 '15 at 23:22
  • \$\begingroup\$ @user2428118: Fixed! \$\endgroup\$ – SuperJedi224 Oct 21 '15 at 1:36
  • \$\begingroup\$ Is it intentional that this immeadetly redirects the browser's location to 'null'? \$\endgroup\$ – pppery Oct 21 '15 at 20:28
  • \$\begingroup\$ No, it isn't. Let me fix that. \$\endgroup\$ – SuperJedi224 Oct 21 '15 at 20:30
  • \$\begingroup\$ setTimeout('throw "Test"',10) works for output too. Also window.open('data:text/html,a%20div'). \$\endgroup\$ – Ismael Miguel Dec 6 '15 at 22:06
4
\$\begingroup\$

Javascript

You can stop any output destroying (most of) the window object.

Also, you can't get rid of document, but you can crush it's content every millisecond.

Here's what I came up with:

(function(window){
    var html = document.getElementsByTagName('html')[0];

    setInterval(function(){html.innerHTML='';}, 1);
    window.addEventListener('error', function(){});

    for(var k in window)
    {
        if(k!='location')
        {
            window[k]=window;
        }
    }
})(Function('return this')());

This sets every single object inside window (except location, it will reload the page) to be ... the window object!!!

This will mess directly with the real window: Running Function('return this')() will return the this object for that context. Since that is eval'ed code, it will be the ... window object!

This also catches all exceptions by setting an handler on window, before deleting everything.

Also, we go grab the <html> element and set it's innerHTML to an empty string. This means that your output will work for less than a millisecond.

Your code is still executed. It just won't be able to show any output. Maybe you can create a file! If only the API wasn't destroyed...


Warning: This causes huge strain on your CPU and RAM. Run this at your own risk! It may cause overheating on your CPU and abnormal behaviour on your browser. It forces the code to run as many times as the browser can handle, in a second. This may cause a huge queue of functions to be executed, if it takes longer than the minimum time interval (which is 4ms for Firefox and Google Chrome (source provided by @somebody))

To stop the process, either run document.location=document.location or press F5.

I am NOT responsible for ANY hardware or software damage or data loss caused by running this code.

\$\endgroup\$
  • \$\begingroup\$ Most browsers don't support intervals less than about 10ms. \$\endgroup\$ – SuperJedi224 Dec 6 '15 at 12:48
  • \$\begingroup\$ @SuperJedi224 What browsers? It works everywhere where I try it \$\endgroup\$ – Ismael Miguel Dec 6 '15 at 14:24
  • \$\begingroup\$ I heard somewhere that there was a minimum of 10ms in chrome and 15ms in FF and safari. Apparently, this is no longer the case. However, there is still a minimum of 4ms with nested timeouts and 1s in tabs that are not currently focused. \$\endgroup\$ – SuperJedi224 Dec 6 '15 at 18:43
  • \$\begingroup\$ @SuperJedi224 But there aren't nested timeout. They seem to work fine on any browser I throw this at. If this worked only on a single version of a very specific browser, it was acceptable. Watch the most voted answer: it only works on a specific engine, in a specific version. \$\endgroup\$ – Ismael Miguel Dec 6 '15 at 19:11
  • \$\begingroup\$ What I meant is that the information on which I had based my first comment was apparently outdated. \$\endgroup\$ – SuperJedi224 Dec 6 '15 at 19:15
4
\$\begingroup\$

Go

I did it! I really finally did it! I've been stewing on this problem for months but I finally have a definitive solution that I challenge anyone to crack!

package main

import (
    . "runtime"
    . "os"
)

func main() {
    const (
        Chmod = iota
        Chtimes
        Create
        Exit
        File
        FindProcess
        Lchown
        Link
        Mkdir
        MkdirAll
        NewFile
        Open
        OpenFile
        Process
        Remove
        RemoveAll
        Rename
        Setenv
        StartProcess
        Symlink
        TempDir
        Truncate
        Unsetenv
    )
    Stdout.Close()
    Stdin.Close()
    Stderr.Close()
    defer func() {
        go func() {
            // User code here
        }()
    }()
    Goexit()
}

My definitive reddit post on this problem for Go.

But now, I have a solution. By forcing the user's code to execute in a goroutine, and then terminating the main goroutine with runtime.Goexit, the user can no longer set the exit code. If they panic the program crashes, yes, but if they don't then it also crashes, per the documentation of Goexit:

Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.

\$\endgroup\$
  • \$\begingroup\$ I give up, omfg \$\endgroup\$ – cat Oct 1 '16 at 10:46
  • \$\begingroup\$ @cat Nonverbal communication can be hard to understand at times. Are you impressed, or annoyed that I have continued to notify you about my progress on this challenge? \$\endgroup\$ – EMBLEM Oct 19 '16 at 20:26
  • 1
    \$\begingroup\$ I'm genuinely sorry, I guess I should have appended a :D -- I'm impressed, and only cheerfully annoyed at your awesome answer c: I don't mind you keeping me updated. \$\endgroup\$ – cat Oct 19 '16 at 21:47
4
\$\begingroup\$

IBM Mainframe Assembler - 6

la 15,0

On entry to any program, Register 15 contains your base address. Overwrite that value, and expect an 0C4 abend (addressing exception) almost immediately.

\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to the site! \$\endgroup\$ – DJMcMayhem May 5 '17 at 20:58
  • 3
    \$\begingroup\$ That appears to be 7 bytes. \$\endgroup\$ – CalculatorFeline Jul 10 '17 at 22:00
4
\$\begingroup\$

Operation Flashpoint scripting language

A feature I once discovered accidentally: You can create a variable with a name that's already taken by a command, thus making the command inaccessible. It can be recovered from by deleting the variable, but the command that is used to remove a variable can also be overwritten.

Save the following as init.sqs in the mission folder:

; Overwrite commands that can be used to execute code with variables with the same name.
call = 0
exec = 0
drop = 0
addEventHandler = 0
createDialog = 0

; There are other commands that could do the task, but not without input from the player.
; Any command in the game can be overwritten (except operators whose name doesn't begin
; with a letter, those are not valid variable names), so to be completely sure one could
; overwrite every single command, but these should suffice.

; Even if somehow ("onFlare.sqs", "onPlayerKilled.sqs" or some other scripts that are called
; automatically under specific circumstances) one gets a script running, make it impossible
; to create loops. Recursion is only possible with 'exec' or 'call' (and technically with 'drop').
goto = 0
while = 0
forEach = 0

; Overwrite the 'nil' command so that it cannot be used to recover from the above.
; Without this, "call = nil" would make 'call' work again (or any other overwritten command).
nil = 0

; Your code can be added here at the end of this script or anywhere else in the mission.

Now there is no way to use any kinds of loops or recursion.

Trying to call a piece of code outputting "Hello, World!":

enter image description here

\$\endgroup\$
4
\$\begingroup\$

Python 2

import sys
sys.setrecursionlimit(1)

Sets the maximum recursion depth to 1.
After entering these 2 lines, any subsequent line will yield:

RuntimeError: <exception str() failed>

enter image description here

Edit: They fixed this bug in Python 3.

Python 3

import sys,os,_thread

def poll(id):
    while True:
        sys.stdout = None
        sys.__stdout__ = None
        sys.stderr = None
        sys.__stderr__ = None
        open = None
        os.system = None
        builtins = None

_thread.start_new_thread(poll, (1,))

Print will now output nothing. Any other command that creates output gives:

RuntimeError: lost sys.stdout

enter image description here

Edit: The sys.__stdout__ = None serves to prevent the user from recovering sys.stdout using sys.stdout = sys.__stdout__. Credit to @someone.

Edit: sys.stdout could also be redirected to a file using sys.stdout = open("output.txt","w"). The open = None prevents this. Credit to @someone.

Edit: Added os.system = None because it could also be used to print. Credit to @Jonathan Frech

def print(x):
    os.system("echo {0}".format(x))

Edit: open can be recovered by:

import builtins
open = builtins.open

To prevent this, I made the whole script into a thread.

Edit: Added builtins = None to disable builtins.open. Credit to @Jonathan Frech

\$\endgroup\$
  • \$\begingroup\$ Can sys.stdout = sys.__stdout__ recover python 3 version? \$\endgroup\$ – my pronoun is monicareinstate Oct 22 '17 at 6:10
  • \$\begingroup\$ @someone Indeed. Setting it to None as well seems to do the trick :) \$\endgroup\$ – Zachary Cotton Oct 22 '17 at 6:17
  • \$\begingroup\$ Can we output to a file with sys.stdout = open("abc.txt","w")? \$\endgroup\$ – my pronoun is monicareinstate Oct 22 '17 at 6:24
  • \$\begingroup\$ Outputting text is most likely still possible using os.system. \$\endgroup\$ – Jonathan Frech Oct 22 '17 at 19:44
  • \$\begingroup\$ I think your last edit should say sys.stdout instead of sys.stdin. \$\endgroup\$ – Jonathan Frech Oct 23 '17 at 0:29
4
\$\begingroup\$

Mascarpone

0^

Mascarpone is a language that is quite similar in concept to Emmental, but taken to the extreme. Interpreters are first class objects, so you can push interpreters to the stack, modify them, and then use them on program strings.

In this case, the initial interpreter assigns 0 the meaning of "push to the stack an interpreter in which every character is defined to cause an error." ^ is assigned the meaning of "pop an interpreter off the stack and assign it as the new interpreter for subsequent characters in the program." This means that any characters added after this will error.

Alternatively, if this violates the "code must actually execute" rule, there are many other ways to break the language.

v'_>1^

This is similar, but instead of defining every character to be an error, it defines every character to be a no-op. That way, every character of your code is technically executed, but it just has no effect.

Here's another way:

v'_v>'x<^

x should be replaced with a command here. This essentially creates a new version of the current interpreter with x redefined to be a no-op, and then assigns that as the new interpreter.

While disabling commands might seem devastating, Mascarpone actually seems fairly flexible to the removal of individual commands.

  • It only really needs [v*:! to simulate the Turing-complete ():^ subset of Underload.
  • ' can be used instead of [, so disabling it doesn't kill the language.
  • Disabling . (the output instruction) doesn't work, as you can still output via exit code (erroring/not erroring).
  • Instead of ! (execute operation), you can have v'_<^_ (assign the operation to a command in a new interpreter, then switch to that interpreter and run that command).

I believe disabling v, *, or : might kill the language, but this is only 3 commands out of 18.

\$\endgroup\$
4
\$\begingroup\$

Ruby 2.2.3

protected_methods = [:instance_methods,:__send__,:remove_method,:include?,:==,:to_s,:call,:pop]
protected_constants = [ObjectSpace, NameError, Exception, Module]
END{exit(0)}
ObjectSpace.each_object(Module) do |mod|
  next if protected_constants.include?(mod)
  im = mod.instance_methods
  while (meth = im.pop)
    next if protected_methods.include? meth
    mod.__send__(:remove_method,meth) rescue NameError
  end
  singleton = (class << mod;self;end)
  singleton_im = singleton.instance_methods
  while (meth = singleton_im.pop) 
    next if protected_methods.include? meth
    singleton.__send__(:remove_method,meth) rescue NameError
  end
end
s = (class << self;self;end)
ms = s.instance_methods
while (m = ms.pop)
  next if protected_methods.include? m
  s.__send__(:remove_method,m)
end

# Your code goes here

Ah, I love ruby. This code iterates through every Model (including classes) and un-defines all the methods, except for the ones in protected_methods. Anything you try to call is undefined, including Object#method_missing which means, due to a ruby quirk, a stackoverflow (technically stack level too deep) error is thrown.

Fun fact: if Exception is not in protected_constants then ruby 2.2.3 segfaults (maybe I should submit a bug report about that /s).

This was surprisingly bigger than I was first expecting, particularly because many things can't be DRY, because that would involve using methods that I need to be undefined.

I am pretty sure this works. I've taken a multi-layered approach in that even if you manage to get something in, you probably won't be able to do anything to it; 5+4 results in undefined method '+' for 5:Fixnum, and good luck getting anything out.


In case anyone needs to debug this, or if I forget, you can output after undefining IO#write if you grab a reference to it beforehand:

debug = STDOUT.method(:write)
class IO;remove_method :write;end
debug.call('foo bar')
\$\endgroup\$
3
\$\begingroup\$

StackStream

{ new-stream }     'stdinout def
{ drop exec }      'if def
{ drop drop exec } 'elseif def

Basically, this redefines the default symbol 'stdinout' to return an empty stream, which points nowhere. It then defines 'if' and 'elseif' to always run the first branch, so output is always the same.

\$\endgroup\$
3
\$\begingroup\$

TeX (LaTeX)

\output{\setbox1\vbox{\unvbox255}}}
\let\output\relax

You can still do a lot in a code that starts with this. However, no pages will be ever produced. The output routine that takes care of building up the pages is destroyed, and also its "handle" is destroyed so that you cannot rebuild it. Needless to say, you can still compute a lot of stuff and output them in a file or in the log; you just can't use this crippled TeX to produce any document.

To disable writes, you can simply add:

\let\write\relax

You can't disable the log though.

\$\endgroup\$
3
\$\begingroup\$

Enema

:OQ::!Q:

Code can come any place after this.

This language is similar to Emmental in that it is capable of redefining itself. Essentially, what we're doing here is redefining O (which normally is for output) to do nothing (thus making the language no longer have a transformational model) and then redefine ! (which can be used to reset a word to its default behavior) to do nothing as well.

\$\endgroup\$
3
\$\begingroup\$

Perl

Not only will this make perl unusable, but your entire machine will seize up in seconds... Also works well for bash.

while(fork){fork}

Because fork returns the PID of the child process, or zero for the parent, evaluation the first-fork will create two processes. One of those will exit the loop, and continue evaluation. The other will enter the while body, and create one additional new process with the second-fork. These two processes will again hit the first-fork and create and additional two processes, for a total of four. Two of those will exit the while loop, and execute following code a second and third time. The other two will again enter the loop body. Then four processes will be tested in the first-fork, creating 8 processes, four of which execute the following code for a 4th, 5th, 6th and 7th time. And so on.

On any unix system, you run out of PID numbers and the fork begins to fail when you have 32k processes, but at this point, the scheduler is so busy that any interaction with a windowing system or shell is unusably slow.

\$\endgroup\$
  • 1
    \$\begingroup\$ Is the code after that actually executed? \$\endgroup\$ – jimmy23013 Dec 1 '15 at 8:10
  • \$\begingroup\$ @jimmy23013 good question. The answer is yes; I updated my response to reflect this. \$\endgroup\$ – Dale Johnson Dec 1 '15 at 21:10
  • 12
    \$\begingroup\$ In all fairness, Perl is unusable out of the box. \$\endgroup\$ – Mego Dec 1 '15 at 21:14
  • 2
    \$\begingroup\$ What if your code includes kill(getppid())? \$\endgroup\$ – pppery Jun 18 '16 at 12:03
3
\$\begingroup\$

INTERCAL-72

DO ABSTAIN FROM NEXTING+REINSTATING

INTERCAL has a command for globally disabling the ability of other types of commands to run. (Using it in this form is generally considered a bad idea, because it's a global action-at-a-distance which has no way to exactly reverse it; more recent versions of INTERCAL also have ABSTAIN #1 FROM which is exactly reversed by REINSTATE, but that wasn't around in the time of INTERCAL-72, the oldest version of the language.)

ABSTAINING from REINSTATING is an even worse idea, because it then becomes impossible to even approximately reverse the effect of the ABSTAIN; you can't do a global REINSTATE (the crudest way to get the commands working again) if you can't do any sort of REINSTATE. All we have to do, therefore, is to disable enough other commands at the same time that the language becomes impossible to program in. INTERCAL-72 only has one useful control structure (NEXT/RESUME/FORGET), and disabling NEXT by itself is enough to make it impossible to do any sort of loop.

In more modern versions of INTERCAL, there are a ton of other ways to do control flow (COME FROM, WHILE (not the same as C's while!), TRY AGAIN, GO AHEAD, etc.), and even other ways to reinstate lines of code (e.g. AGAIN), so an answer in modern INTERCAL, while it could use the same general idea, would be a lot longer.

\$\endgroup\$
3
\$\begingroup\$

Common Lisp

(setq *debugger-hook* (lambda (a b) (abort)))

(set-macro-character #\( (lambda (stream char)
                           (read-delimited-list #\) stream)
                           (values)))

Step one is to disable the debugger. I do this by binding the *debugger-hook* (which is called immediately before entering the debugger) to a function which cancels whatever tried to enter the debugger in the first place. Then, I turned ( into a comment character- everything up to its matching close paren is completely ignored.

The result, tested on sbcl at the repl (both line-by-line and #'load ing it from a file), is a repl which completely ignores any meaningful code. Literal values (number, strings, symbols, etc.) work just fine, but anything else is just ignored.

\$\endgroup\$
  • \$\begingroup\$ What old-paren? \$\endgroup\$ – CalculatorFeline Jul 10 '17 at 21:41
3
\$\begingroup\$

TXR Lisp

(set *package* (make-package "X")*package-alist*())

The TXR Lisp dialect has a package system that is inspired by the one in ANSI Common Lisp. TXR Lisp not only has the variable *package*, but also exposes the list of packages themselves as the special variable *package-alist*, which can be assigned, or subject to a dynamic binding.

If we change *package* to a new, empty package, we can still reach functions in the usr package:

1> (set *package* (make-package "empty"))
#<package: empty>
2> (+ 2 2)
** warning: (expr-2:1) unbound function +
** (expr-2:1) + does not name a function or operator
3> (usr:+ 2 2)
4

However, if we also clear the *package-alist*, we will prevent the usr: prefix from being usable:

4> (usr:set usr:*package-alist* usr:nil)
nil
5> (usr:+ 2 2)
expr-5:1: usr:+: package usr not found
** syntax error

Of course, we should do this manipulation first, then clobber *package*, or do it all in one set form:

After this is evaluated, the rest of the code is in an inescapable, empty sandbox.

\$\endgroup\$
3
\$\begingroup\$

ForceLang

def io nil
def gui nil
def require nil
def goto nil
def gotoex nil
def if nil
def undef nil
def def nil
<your code here>

Uses def to mask a bunch of key stuff, including all of the language's IO and most of the language's control flow. Then uses def to mask undef so you can't undo any of it. Finally, uses def to mask itself just because it can.

\$\endgroup\$
2
\$\begingroup\$

C

#define main \
    hide(); \
    int main() \
    { \
        fclose(stdin); \
        fclose(stdout); \
        fclose(stderr); \
        return hide(); \
    } \
    int hide
\$\endgroup\$
  • 2
    \$\begingroup\$ Isn't "a function that is never called" against the rules? \$\endgroup\$ – Fabian Schmengler Oct 18 '15 at 19:53
  • \$\begingroup\$ I see how I misunderstood "the inserted code", I have changed my answer to something that is hopefully valid. \$\endgroup\$ – user46060 Oct 18 '15 at 20:08
  • 2
    \$\begingroup\$ That's recoverable. On Linux, freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout) should put you back on track. \$\endgroup\$ – PSkocik Oct 19 '15 at 23:16
  • 38
    \$\begingroup\$ #undef main.. \$\endgroup\$ – R.. Oct 20 '15 at 2:52
  • 1
    \$\begingroup\$ Why not just do void fclose(_) {...} and write your code in there? \$\endgroup\$ – Esolanging Fruit May 12 '17 at 4:48
2
\$\begingroup\$

Simplex v.0.5

h]$g$o$s$`$$u1{vbR4Rl<?[{;L}#]{p}u}
h]                                   ~~ define macro 0 as nothing
  $ $ $ $ $                          ~~ grab next character and redefine its function to
                                     ~~ evaluate the current macro number (0)
   g o s ` $                         ~~ redefine output as a string (g), output as number 
                                     ~~ (o), as a character (s), or as a result of
                                     ~~ suppression (`) and also prevents the user from
                                     ~~ redefining them back, if possible
            u1                       ~~ goes up a strip and sets the byte to 1
              {                   }  ~~ repeat inside until a zero byte is met
               v                     ~~ goes down a strip
                b                    ~~ takes input as a string and puts to strip
                 R4Rl<               ~~ right, 4, right, length => length < 4
                      ?[     ]       ~~ perform inside iff byte is not zero
                        {  }         ~~ loop inside until zero byte is met
                         ;L          ~~ pushes the character to the outer program, left
                            #        ~~ stops evaluation (goes to outer program)
                              { }    ~~ loop inside until zero byte is met
                               p     ~~ removes current byte
                                 u   ~~ goes up a strip to meet the 1 byte; essentially
                                     ~~ a while(true){...} loop.

Essentially, destroys the output commands, then takes input from the user as strings, pushing them to the outer program, until a null-length string is encountered, at which point evaluation ceases and the user's input (the outer program) is evaluated. The user cannot output anything nor can they redefine anything. This thus eliminates the criteria of being able to output anything. If you want to eliminate input, simply put a $ in front of each of G, b, and i before the octothorpe (#) 6 characters before the end.

\$\endgroup\$
2
\$\begingroup\$

O

N:+:-:/:*:@:\:[:]:1:2:3:4:5:6:7:8:9:0:{:}:<:>:=:#:%:^:?:d:w:o:p::;

This reassigns mostly everything to a null codeblock, making any code that contains these characters do nothing.

You could add every ASCII character to make sure they can't do anything, but this kills all arithmetic, stack manipulation, codeblock creation, array creation, pushing numbers to the stack, comparing numbers, control flow, outputting, and assigning variables.

\$\endgroup\$
2
\$\begingroup\$

Mouse-2002

$ ~your code here

In Mouse, $ denotes the end of the program, thus, anything after it will be evaluated and "run" but won't actually do anything. No online interpreter available, unfortunately, but here is a fixed-so-it-compiles-in-gcc version of the interpreter written in C.

\$\endgroup\$
  • \$\begingroup\$ Too bad it ain't ): \$\endgroup\$ – cat Dec 9 '15 at 1:22
  • \$\begingroup\$ Invalid because the code after it wasn't actually executed. \$\endgroup\$ – pppery Feb 22 '16 at 21:19
  • \$\begingroup\$ @ppperry did you read past the first clause of the first sentence? \$\endgroup\$ – cat Feb 22 '16 at 21:22
2
\$\begingroup\$

J, online interpreter

f =: f
f 3

This calls f with f with f with... etc. Here's what the page looks like:

crash 1

Successive attempts at entering things in yields, well, nothing:

this

Tested on Firefox.

\$\endgroup\$
  • \$\begingroup\$ Hmm this only seem to break for me on the online interpreter using Firefox. The interpreter seems to be usable afterwards in Chrome, and jconsole handles the error completely differently locally. Might be worth noting. \$\endgroup\$ – Sp3000 May 23 '16 at 8:05
  • \$\begingroup\$ @Sp3000 Huh, interesting. Consider it noted. \$\endgroup\$ – Conor O'Brien May 23 '16 at 15:51
2
\$\begingroup\$

Lua

local write = io.write
local type = type
local pairs = pairs
local setmetatable = setmetatable
local function destroy(g,t)
    t = t or {}
    setmetatable(g, {__index = function() return write end,__newindex = function() return false end})
    for k,v in pairs(g) do
        if(type(v)=="table")then
            local has = false
            for k2, v2 in pairs(t) do
                if v2 == v then
                    has = true
                    break
                end
            end
            if not has then
                t[#t+1]=v
                destroy(v,t)
            end
        elseif(type(v)=="function")then
            g[k] = write
        end
    end
end
destroy(_G)
type = write
pairs = write
setmetatable = nil

A fun one, makes all functions, including string and table constructors, into the io.write function. It doesn't necessarily prevent the language from doing things it was already doing, but it does cripple it from this point onwards. I chose io.write because I thought it interesting to see if I could make trying to run literally anything print. It didn't work so well.

\$\endgroup\$
2
\$\begingroup\$

Bash

exec &> /dev/null

Any code that comes after can execute whatever it wants, but its output is cast into the void of /dev/null.

\$\endgroup\$
  • \$\begingroup\$ File I/O still works though. \$\endgroup\$ – eush77 May 14 '17 at 18:02
  • \$\begingroup\$ @eush77 True! However, the challenge stated that we could cover only a subset of the allowed output methods. \$\endgroup\$ – Chris May 15 '17 at 8:51
  • \$\begingroup\$ Right, I missed that. \$\endgroup\$ – eush77 May 15 '17 at 9:16
  • \$\begingroup\$ Too bad exec &> /dev/tty easily reverses that :) \$\endgroup\$ – eush77 May 15 '17 at 9:23
  • \$\begingroup\$ @eush77 True... If you really wanted to break it, you would do exec &> /dev/null < /dev/zero. But I'm pretty sure that breaks the rules. \$\endgroup\$ – Chris May 15 '17 at 20:03
2
\$\begingroup\$

S.I.L.O.S, 1 byte

0

Try it online!

Yes, in SILOS, your code can be made completely useless by editing the first line. With this, you can not store any variavbles (or take any input). Essentially it allocates 0 bytes of memory for the first line.

\$\endgroup\$
2
\$\begingroup\$

PowerShell

(gv ex* -v|% S*).LanguageMode=2

This doesn't work on TIO (which uses PowerShell core) but it does work on Windows PowerShell. Additional code can (attempt to) be executed directly after this (via ; or newline).

Putting PowerShell into NoLanguage mode makes it effectively useless unless you pre-defined allowable commands to execute.

\$\endgroup\$
  • \$\begingroup\$ No need to count bytes. \$\endgroup\$ – user75200 Oct 29 '17 at 16:49
  • \$\begingroup\$ @user75200 true, fixed \$\endgroup\$ – briantist Oct 29 '17 at 21:13
2
\$\begingroup\$

QBasic, 29 bytes

FOR i=0TO65535:POKE i,0:NEXT

Overwrites current segment (containing code and important data structures of the interpreter) with zeros.

Similar code may have similar effects on most interpreted BASIC implementations running on bare metal.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.