task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PARI.2FGP
PARI/GP
point.x=1; point.y=2;
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pascal
Pascal
type point = record x, y: integer; end;
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBA
VBA
Sub copystring() a = "Hello World!" b = a a = "I'm gone" Debug.Print b Debug.Print a End Sub
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vim_Script
Vim Script
let str1 = "original string" let str2 = str1 let str1 = "new string"   echo "String 1:" str1 echo "String 2:" str2
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#Scala
Scala
import java.awt.{ Color, geom,Graphics2D ,Rectangle} import scala.math.hypot import scala.swing.{MainFrame,Panel,SimpleSwingApplication} import scala.swing.Swing.pair2Dimension import scala.util.Random   object CirculairConstrainedRandomPoints extends SimpleSwingApplication { //min/max of display-x resp. y val dx0, dy0 = 30; val dxm, dym = 430 val prefSizeX, prefSizeY = 480   val palet = Map("b" -> Color.blue, "g" -> Color.green, "r" -> Color.red, "s" -> Color.black) val cs = List((0, 0, 10, "b"), (0, 0, 15, "g")) //circle position and color val xmax, ymax = 20; val xmin, ymin = -xmax   class Coord(x: Double, y: Double) { def dx = (((dxm - dx0) / 2 + x.toDouble / xmax * (dxm - dx0) / 2) + dx0).toInt def dy = (((dym - dy0) / 2 - y.toDouble / ymax * (dym - dy0) / 2) + dy0).toInt }   object Coord { def apply(x: Double, y: Double) = new Coord(x, y) }   //points: val points = new Iterator[Int] { val r = new Random;def next = r.nextInt(31) - 15; def hasNext = true }.toStream. zip(new Iterator[Int] { val r = new Random; def next = r.nextInt(31) - 15; def hasNext = true }.toStream). map { case (x, y) => (x, y, hypot(x, y)) }.filter { case (x, y, r) => r >= 10 && r <= 15 }.take(100).toSeq. map { case (x, y, r) => new Rectangle(Coord(x, y).dx - 2, Coord(x, y).dy - 2, 4, 4) }   private def ui = new Panel { background = Color.white preferredSize = (prefSizeX, prefSizeY)   class Circle(center: Coord, r: Double, val color: Color) { val dr = (Coord(r, 0).dx - pcentre.dx) * 2 val dx = center.dx - dr / 2 val dy = center.dy - dr / 2 }   object Circle { def apply(x: Double, y: Double, r: Double, color: Color) = new Circle(Coord(x, y), r, color) }   val pcentre = Coord(0, 0) val pxmax = Coord(xmax, 0); val pxmin = Coord(xmin, 0) val pymax = Coord(0, ymax); val pymin = Coord(0, ymin)   //axes: val a_path = new geom.GeneralPath a_path.moveTo(pxmin.dx, pxmin.dy); a_path.lineTo(pxmax.dx, pxmax.dy) //x-axis a_path.moveTo(pymin.dx, pymin.dy); a_path.lineTo(pymax.dx, pymax.dy) //y-axis   //labeling: val labels = List(-20, -15, -10, -5, 5, 10, 15, 20) labels.foreach { x => { val p = Coord(x, 0); a_path.moveTo(p.dx, p.dy - 3); a_path.lineTo(p.dx, p.dy + 3) } } labels.foreach { y => { val p = Coord(0, y); a_path.moveTo(p.dx - 3, p.dy); a_path.lineTo(p.dx + 3, p.dy) } } val xlabels = labels.map(x => { val p = Coord(x, 0); Triple(x.toString, p.dx - 3, p.dy + 20) }) val ylabels = labels.map(y => { val p = Coord(0, y); Triple(y.toString, p.dx - 20, p.dy + 5) })   //circles: val circles = cs.map { case (x, y, r, c) => Circle(x, y, r, palet(c)) }   override def paintComponent(g: Graphics2D) = { super.paintComponent(g) circles.foreach { c => { g.setColor(c.color); g.drawOval(c.dx, c.dy, c.dr, c.dr) } } g.setColor(palet("r")); points.foreach(g.draw(_)) g.setColor(palet("s")); g.draw(a_path) xlabels.foreach { case (text, px, py) => g.drawString(text, px, py) } ylabels.foreach { case (text, px, py) => g.drawString(text, px, py) } } } // def ui   def top = new MainFrame { title = "Rosetta Code >>> Task: Constrained random points on a circle | Language: Scala" contents = ui } }
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program condstr.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessTest1: .asciz "The test 1 is equal.\n" szMessTest1N: .asciz "The test 1 is not equal.\n" szMessTest2: .asciz "The test 2 is equal.\n" szMessTest2N: .asciz "The test 2 is not equal.\n" szMessTest3: .asciz "The test 3 is <.\n" szMessTest3N: .asciz "The test 3 is >.\n" szMessTest4: .asciz "The test 4 is <=.\n" szMessTest4N: .asciz "The test 4 is >.\n" szMessTest5: .asciz "The test 5 is negative.\n" szMessTest5N: .asciz "The test 5 is positive ou equal 0.\n" szMessTest6: .asciz "Test 6 : carry is off.\n" szMessTest6N: .asciz "Test 6 : carry is set.\n" szMessTest7: .asciz "Test 7 : no overflow.\n" szMessTest7N: .asciz "Test 7 : overflow.\n" szMessTest8: .asciz "Test 8 : then.\n" szMessTest8N: .asciz "Test 8 : else.\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */   @ test equal zero, not equal zero @movs r1,#0 @ comments movs r1,#1 @ @ s --> flags and uncomments ldreq r0,iAdrszMessTest1 ldrne r0,iAdrszMessTest1N bl affichageMess   @ test equal 5, not equal 5 @mov r1,#5 mov r1,#10 cmp r1,#5 ldreq r0,iAdrszMessTest2 ldrne r0,iAdrszMessTest2N bl affichageMess   @ test < 5, > 5 SIGNED mov r1,#-10 @mov r1,#10 cmp r1,#5 ldrlt r0,iAdrszMessTest3 ldrgt r0,iAdrszMessTest3N bl affichageMess   @ test < 5, > 5 UNSIGNED @mov r1,#-10 mov r1,#2 cmp r1,#5 ldrls r0,iAdrszMessTest4 ldrhi r0,iAdrszMessTest4N bl affichageMess   @ test < 0, > 0 @movs r1,#-10 movs r1,#2 @ s --> flags ldrmi r0,iAdrszMessTest5 ldrpl r0,iAdrszMessTest5N bl affichageMess   @ carry off carry on @mov r1,#-10 @ for carry set @mov r1,#10 @ for carry off mov r1,#(2<<30) - 1 @ for carry off adds r1,#20 @ s --> flags ldrcc r0,iAdrszMessTest6 @ carry clear ldrcs r0,iAdrszMessTest6N @ carry set bl affichageMess   @ overflow off overflow on @mov r1,#-10 @ for not overflow @mov r1,#10 @ for not overflow mov r1,#(2<<30) - 1 @ for overflow adds r1,#20 @ s --> flags ldrvc r0,iAdrszMessTest7 @ overflow off ldrvs r0,iAdrszMessTest7N @ overflow on bl affichageMess   @ other if then else mov r1,#5 @ for then @mov r1,#20 @ for else cmp r1,#10 ble 1f @ less or equal @bge 1f @ greather or equal @else ldr r0,iAdrszMessTest8N @ overflow off bl affichageMess b 2f 1: @ then ldr r0,iAdrszMessTest8 @ overflow off bl affichageMess 2:   100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrszMessTest1: .int szMessTest1 iAdrszMessTest1N: .int szMessTest1N iAdrszMessTest2: .int szMessTest2 iAdrszMessTest2N: .int szMessTest2N iAdrszMessTest3: .int szMessTest3 iAdrszMessTest3N: .int szMessTest3N iAdrszMessTest4: .int szMessTest4 iAdrszMessTest4N: .int szMessTest4N iAdrszMessTest5: .int szMessTest5 iAdrszMessTest5N: .int szMessTest5N iAdrszMessTest6: .int szMessTest6 iAdrszMessTest6N: .int szMessTest6N iAdrszMessTest7: .int szMessTest7 iAdrszMessTest7N: .int szMessTest7N iAdrszMessTest8: .int szMessTest8 iAdrszMessTest8N: .int szMessTest8N /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */    
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#ALGOL_68
ALGOL 68
# returns text commatized according to the rules of the task and the # # period, location and separator paramters # PROC commatize = ( STRING text, INT location, INT period, STRING separator )STRING: IF STRING str := text[ AT 1 ]; # handle the options # INT start position := IF location = 0 THEN 1 ELSE location FI; INT period length := IF period = 0 THEN 3 ELSE period FI; STRING separator string := IF separator = "" THEN "," ELSE separator FI; period length < 1 OR start position < 1 OR start position > UPB str THEN # invalid parameters - return the text unchanged # text ELIF # attempt to find a non-zero digit # INT number pos := start position; WHILE IF number pos > UPB str THEN FALSE ELSE str[ number pos ] < "1" OR str[ number pos ] > "9" FI DO number pos +:= 1 OD; number pos > UPB str THEN # no digits in the string - return the text unchanged # text ELSE # have at least one digit # STRING result := str[ 1 : number pos - 1 ]; # find the final digit # INT number end := number pos; WHILE IF number end >= UPB str THEN FALSE ELSE str[ number end + 1 ] >= "0" AND str[ number end + 1 ] <= "9" FI DO number end +:= 1 OD; # copy the digits commatizing as required # INT digit count := ( number end - number pos ) + 1; WHILE digit count > 1 DO result +:= str[ number pos ]; number pos +:= 1; digit count -:= 1; IF digit count MOD period length = 0 THEN # need a comma after this digit # result +:= separator string FI OD; # final digit and the rest of the string # result +:= str[ number pos : ]; result FI # commatize # ;   # modes and operators to allow us to specify optional parameters to the # # commatizing procedure # MODE COMMATIZINGOPTIONS = STRUCT( STRING text, INT location, INT period, STRING separator ); PRIO LOCATION = 9; OP LOCATION = ( STRING text, INT location )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, location, 0, "" ); PRIO PERIOD = 9; OP PERIOD = ( STRING text, INT period )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, period, "" ); PRIO SEPARATOR = 9; OP SEPARATOR = ( STRING text, CHAR separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator ); OP SEPARATOR = ( STRING text, STRING separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator ); OP LOCATION = ( COMMATIZINGOPTIONS opts, INT location )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text OF opts, location, period OF opts, separator OF opts ); OP PERIOD = ( COMMATIZINGOPTIONS opts, INT period )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text OF opts, location OF opts, period, separator OF opts ); OP SEPARATOR = ( COMMATIZINGOPTIONS opts, CHAR separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); OP SEPARATOR = ( COMMATIZINGOPTIONS opts, STRING separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); OP COMMATIZE = ( STRING text )STRING: commatize( text, 0, 0, "" ); OP COMMATIZE = ( COMMATIZINGOPTIONS opts )STRING: commatize( text OF opts, location OF opts, period OF opts, separator OF opts );   # test the commatization procedure and operators # print( ( COMMATIZE( "pi=3.14159265358979323846264338327950288419716939937510582097494459231" PERIOD 5 SEPARATOR " " LOCATION 6 ), newline ) ); print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." SEPARATOR "." ), newline ) ); print( ( COMMATIZE """-in Aus$+1411.8millions""", newline ) ); print( ( COMMATIZE "===US$0017440 millions=== (in 2000 dollars)", newline ) ); print( ( COMMATIZE "123.e8000 is pretty big.", newline ) ); print( ( COMMATIZE "The land area of the earth is 57268900(29% of the surface) square miles.", newline ) ); print( ( COMMATIZE "Ain't no numbers in this here words, nohow, no way, Jose.", newline ) ); print( ( COMMATIZE "James was never known as 0000000007", newline ) ); print( ( COMMATIZE "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", newline ) ); print( ( COMMATIZE " $-140000±100 millions.", newline ) ); print( ( COMMATIZE "6/9/1946 was a good year for some.", newline ) )
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#D
D
// // The Rosetta Code Virtual Machine in D. // // This code was migrated from an implementation in ATS. I have tried // to keep it possible to compare the two languages easily, although // in some cases the demonstration of "low level" techniques in ATS // (such as avoiding memory leaks that might require garbage // collection), or the use of linked lists as intermediate storage, or // other such matters, seemed inappropriate to duplicate in D // programming. // // (For example: in ATS, using a fully built linked list to initialize // an array solves typechecking issues that simply do not exist in D's // type system.) //   import std.ascii; import std.conv; import std.stdint; import std.stdio; import std.string; import std.typecons;   enum Op { HALT = 0x0000, // 00000 ADD = 0x0001, // 00001 SUB = 0x0002, // 00010 MUL = 0x0003, // 00011 DIV = 0x0004, // 00100 MOD = 0x0005, // 00101 LT = 0x0006, // 00110 GT = 0x0007, // 00111 LE = 0x0008, // 01000 GE = 0x0009, // 01001 EQ = 0x000A, // 01010 NE = 0x000B, // 01011 AND = 0x000C, // 01100 OR = 0x000D, // 01101 NEG = 0x000E, // 01110 NOT = 0x000F, // 01111 PRTC = 0x0010, // 10000 PRTI = 0x0011, // 10001 PRTS = 0x0012, // 10010 FETCH = 0x0013, // 10011 STORE = 0x0014, // 10100 PUSH = 0x0015, // 10101 JMP = 0x0016, // 10110 JZ = 0x0017 // 10111 }   const string[] opcodeOrder = ["halt", // 00000 bit pattern "add", // 00001 "sub", // 00010 "mul", // 00011 "div", // 00100 "mod", // 00101 "lt", // 00110 "gt", // 00111 "le", // 01000 "ge", // 01001 "eq", // 01010 "ne", // 01011 "and", // 01100 "or", // 01101 "neg", // 01110 "not", // 01111 "prtc", // 10000 "prti", // 10001 "prts", // 10010 "fetch", // 10011 "store", // 10100 "push", // 10101 "jmp", // 10110 "jz"]; // 10111   enum Register { PC = 0, SP = 1, MAX = SP }   alias vmint = uint32_t;   class VM { string[] strings; ubyte[] code; vmint[] data; vmint[] stack; vmint[Register.MAX + 1] registers; }   class BadVMException : Exception { this(string msg, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line); } }   class VMRuntimeException : Exception { this(string msg, string file = __FILE__, size_t line = __LINE__) { super(msg, file, line); } }   vmint twosComplement (vmint x) { // This computes the negative of x, if x is regarded as signed. pragma(inline); return (~x) + vmint(1U); }   vmint add (vmint x, vmint y) { // This works whether x or y is regarded as unsigned or signed. pragma(inline); return x + y; }   vmint sub (vmint x, vmint y) { // This works whether x or y is regarded as unsigned or signed. pragma(inline); return x - y; }   vmint equality (vmint x, vmint y) { pragma(inline); return vmint(x == y); }   vmint inequality (vmint x, vmint y) { pragma(inline); return vmint(x != y); }   vmint signedLt (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) < int32_t(y)); }   vmint signedGt (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) > int32_t(y)); }   vmint signedLte (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) <= int32_t(y)); }   vmint signedGte (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) >= int32_t(y)); }   vmint signedMul (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) * int32_t(y)); }   vmint signedDiv (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) / int32_t(y)); }   vmint signedMod (vmint x, vmint y) { pragma(inline); return vmint(int32_t(x) % int32_t(y)); }   vmint logicalNot (vmint x) { pragma(inline); return vmint(!x); }   vmint logicalAnd (vmint x, vmint y) { pragma(inline); return vmint((!!x) * (!!y)); }   vmint logicalOr (vmint x, vmint y) { pragma(inline); return (vmint(1) - vmint((!x) * (!y))); }   vmint parseDigits (string s, size_t i, size_t j) { const badInteger = "bad integer";   if (j == i) throw new BadVMException (badInteger); auto x = vmint(0); for (size_t k = i; k < j; k += 1) if (!isDigit (s[k])) throw new BadVMException (badInteger); else // The result is allowed to overflow freely. x = (vmint(10) * x) + vmint(s[k] - '0'); return x; }   vmint parseInteger (string s, size_t i, size_t j) { const badInteger = "bad integer";   vmint retval; if (j == i) throw new BadVMException (badInteger); else if (j == i + vmint(1) && !isDigit (s[i])) throw new BadVMException (badInteger); else if (s[i] != '-') retval = parseDigits (s, i, j); else if (j == i + vmint(1)) throw new BadVMException (badInteger); else retval = twosComplement (parseDigits (s, i + vmint(1), j)); return retval; }   size_t skipWhitespace (string s, size_t n, size_t i) { while (i < n && isWhite (s[i])) i += 1; return i; }   size_t skipNonwhitespace (string s, size_t n, size_t i) { while (i < n && !isWhite (s[i])) i += 1; return i; }   bool substrEqual (string s, size_t i, size_t j, string t) { // Is s[i .. j-1] equal to t?   auto retval = false; auto m = t.length; if (m == j - i) { auto k = size_t(0); while (k < m && s[i + k] == t[k]) k += 1; retval = (k == m); } return retval; }   string dequoteString (string s, size_t n) { const badQuotedString = "bad quoted string";   string t = ""; s = strip(s); if (s.length < 2 || s[0] != '"' || s[$ - 1] != '"') throw new BadVMException (badQuotedString); auto i = 1; while (i < s.length - 1) if (s[i] != '\\') { t ~= s[i]; i += 1; } else if (i + 1 == s.length - 1) throw new BadVMException (badQuotedString); else if (s[i + 1] == 'n') { t ~= '\n'; i += 2; } else if (s[i + 1] == '\\') { t ~= '\\'; i += 2; } else throw new BadVMException (badQuotedString); return t; }   string[] readStrings (File f, size_t stringsSize) { const badQuotedString = "Bad quoted string.";   string[] strings; strings.length = stringsSize; for (size_t k = 0; k < stringsSize; k += 1) { auto line = f.readln(); strings[k] = dequoteString (line, line.length); } return strings; }   ubyte opcodeNameTo_ubyte (string str, size_t i, size_t j) { size_t k = 0; while (k < opcodeOrder.length && !substrEqual (str, i, j, opcodeOrder[k])) k += 1; if (k == opcodeOrder.length) throw new BadVMException ("unrecognized opcode name"); return to!ubyte(k); }   ubyte vmintByte0 (vmint i) { return (i & 0xFF); }   ubyte vmintByte1 (vmint i) { return ((i >> 8) & 0xFF); }   ubyte vmintByte2 (vmint i) { return ((i >> 16) & 0xFF); }   ubyte vmintByte3 (vmint i) { return (i >> 24); }   ubyte[] parseInstruction (string line) { const bad_instruction = "bad VM instruction";   const n = line.length; auto i = skipWhitespace (line, n, 0);   // Skip the address field. i = skipNonwhitespace (line, n, i);   i = skipWhitespace (line, n, i); auto j = skipNonwhitespace (line, n, i); auto opcode = opcodeNameTo_ubyte (line, i, j);   auto startOfArgument = j;   ubyte[] finishPush () { const i1 = skipWhitespace (line, n, startOfArgument); const j1 = skipNonwhitespace (line, n, i1); const arg = parseInteger (line, i1, j1); // Little-endian storage. return [opcode, vmintByte0 (arg), vmintByte1 (arg), vmintByte2 (arg), vmintByte3 (arg)]; }   ubyte[] finishFetchOrStore () { const i1 = skipWhitespace (line, n, startOfArgument); const j1 = skipNonwhitespace (line, n, i1); if (j1 - i1 < 3 || line[i1] != '[' || line[j1 - 1] != ']') throw new BadVMException (bad_instruction); const arg = parseInteger (line, i1 + 1, j1 - 1); // Little-endian storage. return [opcode, vmintByte0 (arg), vmintByte1 (arg), vmintByte2 (arg), vmintByte3 (arg)]; }   ubyte[] finishJmpOrJz () { const i1 = skipWhitespace (line, n, startOfArgument); const j1 = skipNonwhitespace (line, n, i1); if (j1 - i1 < 3 || line[i1] != '(' || line[j1 - 1] != ')') throw new BadVMException (bad_instruction); const arg = parseInteger (line, i1 + 1, j1 - 1); // Little-endian storage. return [opcode, vmintByte0 (arg), vmintByte1 (arg), vmintByte2 (arg), vmintByte3 (arg)]; }   ubyte[] retval; switch (opcode) { case Op.PUSH: retval = finishPush (); break; case Op.FETCH: case Op.STORE: retval = finishFetchOrStore (); break; case Op.JMP: case Op.JZ: retval = finishJmpOrJz (); break; default: retval = [opcode]; break; }   return retval; }   ubyte[] readCode (File f) { // Read the instructions from the input, producing an array of // array of instruction bytes. ubyte[] code = []; auto line = f.readln(); while (line !is null) { code ~= parseInstruction (line); line = f.readln(); } return code; }   void parseHeaderLine (string line, ref size_t dataSize, ref size_t stringsSize) { const bad_vm_header_line = "bad VM header line";   const n = line.length; auto i = skipWhitespace (line, n, 0); auto j = skipNonwhitespace (line, n, i); if (!substrEqual (line, i, j, "Datasize:")) throw new BadVMException (bad_vm_header_line); i = skipWhitespace (line, n, j); j = skipNonwhitespace (line, n, i); dataSize = parseInteger (line, i, j); i = skipWhitespace (line, n, j); j = skipNonwhitespace (line, n, i); if (!substrEqual (line, i, j, "Strings:")) throw new BadVMException (bad_vm_header_line); i = skipWhitespace (line, n, j); j = skipNonwhitespace (line, n, i); stringsSize = parseInteger (line, i, j); }   VM readVM (File f) { const line = f.readln();   size_t dataSize; size_t stringsSize; parseHeaderLine (line, dataSize, stringsSize);   VM vm = new VM(); vm.strings = readStrings (f, stringsSize); vm.code = readCode (f); vm.data.length = dataSize; vm.stack.length = 65536; // A VERY big stack, MUCH bigger than is // "reasonable" for this VM. The same size // as in the ATS, however. vm.registers[Register.PC] = vmint(0); vm.registers[Register.SP] = vmint(0);   return vm; }   vmint pop (VM vm) { pragma(inline); const spBefore = vm.registers[Register.SP]; if (spBefore == 0) throw new VMRuntimeException ("stack underflow"); const spAfter = spBefore - vmint(1); vm.registers[Register.SP] = spAfter; return vm.stack[spAfter]; }   void push (VM vm, vmint x) { pragma(inline); const spBefore = vm.registers[Register.SP]; if (vm.stack.length <= spBefore) throw new VMRuntimeException ("stack overflow"); vm.stack[spBefore] = x; const spAfter = spBefore + vmint(1); vm.registers[Register.SP] = spAfter; }   vmint fetchData (VM vm, vmint index) { pragma(inline); if (vm.data.length <= index) throw new VMRuntimeException ("fetch from outside the data section"); return vm.data[index]; }   void storeData (VM vm, vmint index, vmint x) { pragma(inline); if (vm.data.length <= index) throw new VMRuntimeException ("store to outside the data section"); vm.data[index] = x; }   vmint getArgument (VM vm) { pragma(inline); auto pc = vm.registers[Register.PC]; if (vm.code.length <= pc + vmint(4)) throw new VMRuntimeException ("the program counter is out of bounds"); // The data is stored little-endian. const byte0 = vmint (vm.code[pc]); const byte1 = vmint (vm.code[pc + vmint(1)]); const byte2 = vmint (vm.code[pc + vmint(2)]); const byte3 = vmint (vm.code[pc + vmint(3)]); return (byte0) | (byte1 << 8) | (byte2 << 16) | (byte3 << 24); }   void skipArgument (VM vm) { pragma(inline); vm.registers[Register.PC] += vmint(4); }   // // The string mixins below are going to do for us *some* of what the // ATS template system did for us. The two methods hardly resemble // each other, but both can be used to construct function definitions // at compile time. //   template UnaryOperation (alias name, alias func) { const char[] UnaryOperation = "void " ~ name ~ " (VM vm) { pragma(inline); const sp = vm.registers[Register.SP]; if (sp == vmint(0)) throw new VMRuntimeException (\"stack underflow\"); const x = vm.stack[sp - vmint(1)]; const z = " ~ func ~ " (x); vm.stack[sp - vmint(1)] = z; }"; }   template BinaryOperation (alias name, alias func) { const char[] BinaryOperation = "void " ~ name ~ " (VM vm) { pragma(inline); const spBefore = vm.registers[Register.SP]; if (spBefore <= vmint(1)) throw new VMRuntimeException (\"stack underflow\"); const spAfter = spBefore - vmint(1); vm.registers[Register.SP] = spAfter; const x = vm.stack[spAfter - vmint(1)]; const y = vm.stack[spAfter]; const z = " ~ func ~ "(x, y); vm.stack[spAfter - vmint(1)] = z; }"; }   mixin (UnaryOperation!("uopNeg", "twosComplement")); mixin (UnaryOperation!("uopNot", "logicalNot"));   mixin (BinaryOperation!("binopAdd", "add")); mixin (BinaryOperation!("binopSub", "sub")); mixin (BinaryOperation!("binopMul", "signedMul")); mixin (BinaryOperation!("binopDiv", "signedDiv")); mixin (BinaryOperation!("binopMod", "signedMod")); mixin (BinaryOperation!("binopEq", "equality")); mixin (BinaryOperation!("binopNe", "inequality")); mixin (BinaryOperation!("binopLt", "signedLt")); mixin (BinaryOperation!("binopGt", "signedGt")); mixin (BinaryOperation!("binopLe", "signedLte")); mixin (BinaryOperation!("binopGe", "signedGte")); mixin (BinaryOperation!("binopAnd", "logicalAnd")); mixin (BinaryOperation!("binopOr", "logicalOr"));   void doPush (VM vm) { pragma(inline); const arg = getArgument (vm); push (vm, arg); skipArgument (vm); }   void doFetch (VM vm) { pragma(inline); const i = getArgument (vm); const x = fetchData (vm, i); push (vm, x); skipArgument (vm); }   void doStore (VM vm) { pragma(inline); const i = getArgument (vm); const x = pop (vm); storeData (vm, i, x); skipArgument (vm); }   void doJmp (VM vm) { pragma(inline); const arg = getArgument (vm); vm.registers[Register.PC] += arg; }   void doJz (VM vm) { pragma(inline); const x = pop (vm); if (x == vmint(0)) doJmp (vm); else skipArgument (vm); }   void doPrtc (File fOut, VM vm) { const x = pop (vm); fOut.write (to!char(x)); }   void doPrti (File fOut, VM vm) { const x = pop (vm); fOut.write (int32_t(x)); }   void doPrts (File fOut, VM vm) { const i = pop (vm); if (vm.strings.length <= i) throw new VMRuntimeException ("string index out of bounds"); fOut.write (vm.strings[i]); }   void vmStep (File fOut, VM vm, ref bool machineHalt, ref bool badOpcode) { const pc = vm.registers[Register.PC]; if (vm.code.length <= pc) throw new VMRuntimeException ("the program counter is out of bounds"); vm.registers[Register.PC] = pc + vmint(1); const opcode = vm.code[pc]; const uOpcode = uint(opcode);   // Dispatch by bifurcation on the bit pattern of the opcode. This // method is logarithmic in the number of opcode values.   machineHalt = false; badOpcode = false; if ((uOpcode & (~0x1FU)) == 0U) { if ((uOpcode & 0x10U) == 0U) { if ((uOpcode & 0x08U) == 0U) { if ((uOpcode & 0x04U) == 0U) { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) machineHalt = true; else binopAdd (vm); } else { if ((uOpcode & 0x01U) == 0U) binopSub (vm); else binopMul (vm); } } else { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) binopDiv (vm); else binopMod (vm); } else { if ((uOpcode & 0x01U) == 0U) binopLt (vm); else binopGt (vm); } } } else { if ((uOpcode & 0x04U) == 0U) { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) binopLe (vm); else binopGe (vm); } else { if ((uOpcode & 0x01U) == 0U) binopEq (vm); else binopNe (vm); } } else { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) binopAnd (vm); else binopOr (vm); } else { if ((uOpcode & 0x01U) == 0U) uopNeg (vm); else uopNot (vm); } } } } else { if ((uOpcode & 0x08U) == 0U) { if ((uOpcode & 0x04U) == 0U) { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) doPrtc (fOut, vm); else doPrti (fOut, vm); } else { if ((uOpcode & 0x01U) == 0U) doPrts (fOut, vm); else doFetch (vm); } } else { if ((uOpcode & 0x02U) == 0U) { if ((uOpcode & 0x01U) == 0U) doStore (vm); else doPush (vm); } else { if ((uOpcode & 0x01U) == 0U) doJmp (vm); else doJz (vm); } } } else badOpcode = true; } } else badOpcode = true; }   void vmContinue (File fOut, VM vm) { auto machineHalt = false; auto badOpcode = false; while (!machineHalt && !badOpcode) vmStep (fOut, vm, machineHalt, badOpcode); if (badOpcode) throw new VMRuntimeException ("unrecognized opcode at runtime"); }   void vmInitialize (VM vm) { foreach (ref x; vm.data) x = vmint(0); vm.registers[Register.PC] = vmint(0); vm.registers[Register.SP] = vmint(0); }   void vmRun (File fOut, VM vm) { vmInitialize (vm); vmContinue (fOut, vm); }   void ensure_that_vmint_is_suitable () { // Try to guarantee that vmint is exactly 32 bits, and that it // allows overflow in either direction. assert (vmint(0xFFFFFFFFU) + vmint(1U) == vmint(0U)); assert (vmint(0U) - vmint(1U) == vmint(0xFFFFFFFFU)); assert (vmint(-1234) == twosComplement (vmint(1234))); }   int main (char[][] args) { auto inpFilename = "-"; auto outFilename = "-"; if (2 <= args.length) inpFilename = to!string (args[1]); if (3 <= args.length) outFilename = to!string (args[2]);   auto inpF = stdin; if (inpFilename != "-") inpF = File (inpFilename, "r"); auto vm = readVM (inpF); if (inpFilename != "-") inpF.close();   auto outF = stdout; if (outFilename != "-") outF = File (outFilename, "w"); ensure_that_vmint_is_suitable (); vmRun (outF, vm); if (outFilename != "-") outF.close();   return 0; }
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#AWK
AWK
  function error(msg) { printf("%s\n", msg) exit(1) }   function bytes_to_int(bstr, i, sum) { sum = 0 for (i=word_size-1; i>=0; i--) { sum *= 256 sum += code[bstr+i] } return sum }   function make_node(oper, left, right, value) { node_type [next_free_node_index] = oper node_left [next_free_node_index] = left node_right[next_free_node_index] = right node_value[next_free_node_index] = value return next_free_node_index ++ }   function make_leaf(oper, n) { return make_node(oper, 0, 0, n) }   function emit_byte(x) { code[next_free_code_index++] = x }   function emit_word(x, i) { for (i=0; i<word_size; i++) { emit_byte(int(x)%256); x = int(x/256) } }   function emit_word_at(at, n, i) { for (i=0; i<word_size; i++) { code[at+i] = int(n)%256 n = int(n/256) } }   function hole( t) { t = next_free_code_index emit_word(0) return t }   function fetch_var_offset(name, n) { if (name in globals) { n = globals[name] } else { globals[name] = globals_n n = globals_n globals_n += 1 } return n }   function fetch_string_offset(the_string, n) { n = string_pool[the_string] if (n == "") { string_pool[the_string] = string_n n = string_n string_n += 1 } return n }   function code_gen(x, n, p1, p2) { if (x == 0) { return } else if (node_type[x] == "nd_Ident") { emit_byte(FETCH) n = fetch_var_offset(node_value[x]) emit_word(n) } else if (node_type[x] == "nd_Integer") { emit_byte(PUSH) emit_word(node_value[x]) } else if (node_type[x] == "nd_String") { emit_byte(PUSH) n = fetch_string_offset(node_value[x]) emit_word(n) } else if (node_type[x] == "nd_Assign") { n = fetch_var_offset(node_value[node_left[x]]) code_gen(node_right[x]) emit_byte(STORE) emit_word(n) } else if (node_type[x] == "nd_If") { code_gen(node_left[x]) # expr emit_byte(JZ) # if false, jump p1 = hole() # make room for jump dest code_gen(node_left[node_right[x]]) # if true statements if (node_right[node_right[x]] != 0) { emit_byte(JMP) # jump over else statements p2 = hole() } emit_word_at(p1, next_free_code_index - p1) if (node_right[node_right[x]] != 0) { code_gen(node_right[node_right[x]]) # else statements emit_word_at(p2, next_free_code_index - p2) } } else if (node_type[x] == "nd_While") { p1 =next_free_code_index code_gen(node_left[x]) emit_byte(JZ) p2 = hole() code_gen(node_right[x]) emit_byte(JMP) # jump back to the top emit_word(p1 - next_free_code_index) emit_word_at(p2, next_free_code_index - p2) } else if (node_type[x] == "nd_Sequence") { code_gen(node_left[x]) code_gen(node_right[x]) } else if (node_type[x] == "nd_Prtc") { code_gen(node_left[x]) emit_byte(PRTC) } else if (node_type[x] == "nd_Prti") { code_gen(node_left[x]) emit_byte(PRTI) } else if (node_type[x] == "nd_Prts") { code_gen(node_left[x]) emit_byte(PRTS) } else if (node_type[x] in operators) { code_gen(node_left[x]) code_gen(node_right[x]) emit_byte(operators[node_type[x]]) } else if (node_type[x] in unary_operators) { code_gen(node_left[x]) emit_byte(unary_operators[node_type[x]]) } else { error("error in code generator - found '" node_type[x] "', expecting operator") } }   function code_finish() { emit_byte(HALT) }   function list_code() { printf("Datasize: %d Strings: %d\n", globals_n, string_n) # Make sure that arrays are sorted by value in ascending order. PROCINFO["sorted_in"] = "@val_str_asc" # This is a dependency on GAWK. for (k in string_pool) print(k) pc = 0 while (pc < next_free_code_index) { printf("%4d ", pc) op = code[pc] pc += 1 if (op == FETCH) { x = bytes_to_int(pc) printf("fetch [%d]\n", x); pc += word_size } else if (op == STORE) { x = bytes_to_int(pc) printf("store [%d]\n", x); pc += word_size } else if (op == PUSH) { x = bytes_to_int(pc) printf("push  %d\n", x); pc += word_size } else if (op == ADD) { print("add") } else if (op == SUB) { print("sub") } else if (op == MUL) { print("mul") } else if (op == DIV) { print("div") } else if (op == MOD) { print("mod") } else if (op == LT) { print("lt") } else if (op == GT) { print("gt") } else if (op == LE) { print("le") } else if (op == GE) { print("ge") } else if (op == EQ) { print("eq") } else if (op == NE) { print("ne") } else if (op == AND) { print("and") } else if (op == OR) { print("or") } else if (op == NEG) { print("neg") } else if (op == NOT) { print("not") } else if (op == JMP) { x = bytes_to_int(pc) printf("jmp (%d) %d\n", x, pc + x); pc += word_size } else if (op == JZ) { x = bytes_to_int(pc) printf("jz (%d) %d\n", x, pc + x); pc += word_size } else if (op == PRTC) { print("prtc") } else if (op == PRTI) { print("prti") } else if (op == PRTS) { print("prts") } else if (op == HALT) { print("halt") } else { error("list_code: Unknown opcode '" op "'") } } # while pc }   function load_ast( line, line_list, text, n, node_type, value, left, right) { getline line n=split(line, line_list) text = line_list[1] if (text == ";") return 0 node_type = all_syms[text] if (n > 1) { value = line_list[2] for (i=3;i<=n;i++) value = value " " line_list[i] if (value ~ /^[0-9]+$/) value = int(value) return make_leaf(node_type, value) } left = load_ast() right = load_ast() return make_node(node_type, left, right) }   BEGIN { all_syms["Identifier" ] = "nd_Ident" all_syms["String" ] = "nd_String" all_syms["Integer" ] = "nd_Integer" all_syms["Sequence" ] = "nd_Sequence" all_syms["If" ] = "nd_If" all_syms["Prtc" ] = "nd_Prtc" all_syms["Prts" ] = "nd_Prts" all_syms["Prti" ] = "nd_Prti" all_syms["While" ] = "nd_While" all_syms["Assign" ] = "nd_Assign" all_syms["Negate" ] = "nd_Negate" all_syms["Not" ] = "nd_Not" all_syms["Multiply" ] = "nd_Mul" all_syms["Divide" ] = "nd_Div" all_syms["Mod" ] = "nd_Mod" all_syms["Add" ] = "nd_Add" all_syms["Subtract" ] = "nd_Sub" all_syms["Less" ] = "nd_Lss" all_syms["LessEqual" ] = "nd_Leq" all_syms["Greater" ] = "nd_Gtr" all_syms["GreaterEqual"] = "nd_Geq" all_syms["Equal" ] = "nd_Eql" all_syms["NotEqual" ] = "nd_Neq" all_syms["And" ] = "nd_And" all_syms["Or" ] = "nd_Or"   FETCH=1; STORE=2; PUSH=3; ADD=4; SUB=5; MUL=6; DIV=7; MOD=8; LT=9; GT=10; LE=11; GE=12; EQ=13; NE=14; AND=15; OR=16; NEG=17; NOT=18; JMP=19; JZ=20; PRTC=21; PRTS=22; PRTI=23; HALT=24;   operators["nd_Lss"] = LT operators["nd_Gtr"] = GT operators["nd_Leq"] = LE operators["nd_Geq"] = GE operators["nd_Eql"] = EQ operators["nd_Neq"] = NE operators["nd_And"] = AND operators["nd_Or" ] = OR operators["nd_Sub"] = SUB operators["nd_Add"] = ADD operators["nd_Div"] = DIV operators["nd_Mul"] = MUL operators["nd_Mod"] = MOD   unary_operators["nd_Negate"] = NEG unary_operators["nd_Not" ] = NOT   next_free_node_index = 1 next_free_code_index = 0 globals_n = 0 string_n = 0 word_size = 4 input_file = "-"   if (ARGC > 1) input_file = ARGV[1] n = load_ast() code_gen(n) code_finish() list_code() }  
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#D
D
import std.stdio, std.algorithm, std.container, std.datetime, std.random, std.typetuple;   immutable int[] allOnes, sortedData, randomData;   static this() { // Initialize global Arrays. immutable size_t arraySize = 10_000;   allOnes = new int[arraySize]; //allOnes[] = 1; foreach (ref d; allOnes) d = 1;   sortedData = new int[arraySize]; foreach (immutable i, ref d; sortedData) d = i;   randomData = new int[arraySize]; foreach (ref d; randomData) d = uniform(0, int.max); }   // BubbleSort:   void bubbleSort(T)(T[] list) { for (int i = list.length - 1; i > 0; i--) for (int j = i -1; j >= 0; j--) if (list[i] < list[j]) swap(list[i], list[j]); }   void allOnesBubble() { auto data = allOnes.dup; data.bubbleSort; assert(data.isSorted); }   void sortedBubble() { auto data = sortedData.dup; data.bubbleSort; assert(data.isSorted); }   void randomBubble() { auto data = randomData.dup; data.bubbleSort; assert(data.isSorted); }   // InsertionSort:   void insertionSort(T)(T[] list) { foreach (immutable i, currElem; list) { size_t j = i; for (; j > 0 && currElem < list[j - 1]; j--) list[j] = list[j - 1]; list[j] = currElem; } }   void allOnesInsertion() { auto data = allOnes.dup; data.insertionSort; assert(data.isSorted); }   void sortedInsertion() { auto data = sortedData.dup; data.insertionSort; assert(data.isSorted); }   void randomInsertion() { auto data = randomData.dup; data.insertionSort; assert(data.isSorted); }   // HeapSort:   void heapSort(T)(T[] data) { auto h = data.heapify; while (!h.empty) h.removeFront; }   void allOnesHeap() { auto data = allOnes.dup; data.heapSort; assert(data.isSorted); }   void sortedHeap() { auto data = sortedData.dup; data.heapSort; assert(data.isSorted); }   void randomHeap() { auto data = randomData.dup; data.heapSort; assert(data.isSorted); }   // Built-in sort:   void allOnesBuiltIn() { auto data = allOnes.dup; data.sort!q{a < b}; assert(data.isSorted); }   void sortedBuiltIn() { auto data = sortedData.dup; data.sort!q{a < b}; assert(data.isSorted); }   void randomBuiltIn() { auto data = randomData.dup; data.sort!q{a < b}; assert(data.isSorted); }   static void show(in TickDuration[4u] r) { alias args = TypeTuple!("usecs", int); writefln(" Bubble Sort:  %10d", r[0].to!args); writefln(" Insertion Sort: %10d", r[1].to!args); writefln(" Heap Sort:  %10d", r[3].to!args); writefln(" Built-in Sort:  %10d", r[2].to!args); }   void main() { enum nRuns = 100; writeln("Timings in microseconds:");   writeln(" Testing against all ones:"); nRuns.benchmark!(allOnesBubble, allOnesInsertion, allOnesHeap, allOnesBuiltIn).show;   writeln("\n Testing against sorted data."); nRuns.benchmark!(sortedBubble, sortedInsertion, sortedHeap, sortedBuiltIn).show;   writeln("\n Testing against random data."); nRuns.benchmark!(randomBubble, randomInsertion, randomHeap, randomBuiltIn).show; }
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) The interpreter algorithm is relatively simple interp(x) if x == NULL return NULL elif x.node_type == Integer return x.value converted to an integer elif x.node_type == Ident return the current value of variable x.value elif x.node_type == String return x.value elif x.node_type == Assign globals[x.left.value] = interp(x.right) return NULL elif x.node_type is a binary operator return interp(x.left) operator interp(x.right) elif x.node_type is a unary operator, return return operator interp(x.left) elif x.node_type == If if (interp(x.left)) then interp(x.right.left) else interp(x.right.right) return NULL elif x.node_type == While while (interp(x.left)) do interp(x.right) return NULL elif x.node_type == Prtc print interp(x.left) as a character, no newline return NULL elif x.node_type == Prti print interp(x.left) as an integer, no newline return NULL elif x.node_type == Prts print interp(x.left) as a string, respecting newlines ("\n") return NULL elif x.node_type == Sequence interp(x.left) interp(x.right) return NULL else error("unknown node type") Notes: Because of the simple nature of our tiny language, Semantic analysis is not needed. Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0. This means, for instance, that 3 / 2 should result in 1. For division when one of the operands is negative, the result should be truncated towards 0. This means, for instance, that 3 / -2 should result in -1. Test program prime.t lex <prime.t | parse | interp /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 101 is prime Total primes found: 26 Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task Virtual Machine Interpreter task
#Perl
Perl
#!/usr/bin/perl   use strict; # interpreter.pl - execute a flatAST use warnings; # http://www.rosettacode.org/wiki/Compiler/AST_interpreter use integer;   my %variables;   tree()->run;   sub tree { my $line = <> // die "incomplete tree\n"; (local $_, my $arg) = $line =~ /^(\w+|;)\s+(.*)/ or die "bad input $line"; /String/ ? bless [$arg =~ tr/""//dr =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ger], $_ : /Identifier|Integer/ ? bless [ $arg ], $_ : /;/ ? bless [], 'Null' : bless [ tree(), tree() ], $_; }   sub Add::run { $_[0][0]->run + $_[0][1]->run } sub And::run { $_[0][0]->run && $_[0][1]->run } sub Assign::run { $variables{$_[0][0][0]} = $_[0][1]->run } sub Divide::run { $_[0][0]->run / $_[0][1]->run } sub Equal::run { $_[0][0]->run == $_[0][1]->run ? 1 : 0 } sub Greater::run { $_[0][0]->run > $_[0][1]->run ? 1 : 0 } sub GreaterEqual::run { $_[0][0]->run >= $_[0][1]->run ? 1 : 0 } sub Identifier::run { $variables{$_[0][0]} // 0 } sub If::run { $_[0][0]->run ? $_[0][1][0]->run : $_[0][1][1]->run } sub Integer::run { $_[0][0] } sub Less::run { $_[0][0]->run < $_[0][1]->run ? 1 : 0 } sub LessEqual::run { $_[0][0]->run <= $_[0][1]->run ? 1 : 0 } sub Mod::run { $_[0][0]->run % $_[0][1]->run } sub Multiply::run { $_[0][0]->run * $_[0][1]->run } sub Negate::run { - $_[0][0]->run } sub Not::run { $_[0][0]->run ? 0 : 1 } sub NotEqual::run { $_[0][0]->run != $_[0][1]->run ? 1 : 0 } sub Null::run {} sub Or::run { $_[0][0]->run || $_[0][1]->run } sub Prtc::run { print chr $_[0][0]->run } sub Prti::run { print $_[0][0]->run } sub Prts::run { print $_[0][0][0] } sub Sequence::run { $_->run for $_[0]->@* } sub Subtract::run { $_[0][0]->run - $_[0][1]->run } sub While::run { $_[0][1]->run while $_[0][0]->run }
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.2B.2B
C++
#include <iostream> #include <algorithm> #include <string> #include <list>   using namespace std;   bool cmp(const string& a, const string& b) { return b.length() < a.length(); // reverse sort! }   void compareAndReportStringsLength(list<string> listOfStrings) { if (!listOfStrings.empty()) { char Q = '"'; string has_length(" has length "); string predicate_max(" and is the longest string"); string predicate_min(" and is the shortest string"); string predicate_ave(" and is neither the longest nor the shortest string");   list<string> ls(listOfStrings); // clone to avoid side-effects ls.sort(cmp); int max = ls.front().length(); int min = ls.back().length();   for (list<string>::iterator s = ls.begin(); s != ls.end(); s++) { int length = s->length(); string* predicate; if (length == max) predicate = &predicate_max; else if (length == min) predicate = &predicate_min; else predicate = &predicate_ave;   cout << Q << *s << Q << has_length << length << *predicate << endl; } } }   int main(int argc, char* argv[]) { list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(listOfStrings);   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Icon
Icon
# # The Rosetta Code Tiny-Language Parser, in Icon. # # This implementation is based closely on the pseudocode and the C # reference implementation. #   # ximage from the IPL is useful for debugging. Use "xdump(x)" to # pretty-print x. #link ximage   record token_record (line_no, column_no, tok, tokval) record token_getter (nxt, curr)   procedure main (args) local inpf_name, outf_name local inpf, outf local nexttok, currtok, current_token, gettok local ast   inpf_name := "-" outf_name := "-" if 1 <= *args then inpf_name := args[1] if 2 <= *args then outf_name := args[2]   inpf := if inpf_name == "-" then &input else (open(inpf_name, "r") | stop("failed to open \"" || inpf_name || "\" for input")) outf := if outf_name == "-" then &output else (open(outf_name, "w") | stop("failed to open \"" || outf_name || "\" for output"))   current_token := [&null] nexttok := create generate_tokens(inpf, current_token) currtok := create get_current_token (current_token) gettok := token_getter(nexttok, currtok) ast := parse(gettok) prt_ast(outf, ast)   close(inpf) close(outf) end   procedure prt_ast (outf, ast) if *ast = 0 then { write(outf, ";") } else { writes(outf, ast[1]) if ast[1] == ("Identifier" | "Integer" | "String") then { write(outf, " ", ast[2]) } else { write(outf) prt_ast(outf, ast[2]) prt_ast(outf, ast[3]) } } end   procedure generate_tokens (inpf, current_token) local s   while s := read(inpf) do { if trim(s) ~== "" then { current_token[1] := string_to_token_record(s) suspend current_token[1] } } end   procedure get_current_token (current_token) repeat (suspend current_token[1]) end   procedure string_to_token_record (s) local line_no, column_no, tok, tokval   static spaces   initial { spaces := ' \t\f\v\r\n' }   trim(s) ? { tab(many(spaces)) line_no := integer(tab(many(&digits))) tab(many(spaces)) column_no := integer(tab(many(&digits))) tab(many(spaces)) tok := tab(many(&letters ++ '_')) tab(many(spaces)) tokval := tab(0) } return token_record(line_no, column_no, tok, tokval) end   procedure parse (gettok) local tok local t   t := [] @gettok.nxt tok := "Not End_of_input" while tok ~== "End_of_input" do { t := ["Sequence", t, stmt(gettok)] tok := (@gettok.curr).tok } return t end   procedure stmt (gettok) local e, s, t, v local tok local done   t := [] if accept(gettok, "Keyword_if") then { e := paren_expr(gettok) s := stmt(gettok) t := ["If", e, ["If", s, if accept(gettok, "Keyword_else") then stmt(gettok) else []]] } else if accept(gettok, "Keyword_putc") then { t := ["Prtc", paren_expr(gettok), []] expect(gettok, "Putc", "Semicolon") } else if accept(gettok, "Keyword_print") then { expect(gettok, "Print", "LeftParen") done := 0 while done = 0 do { tok := @gettok.curr if tok.tok == "String" then { e := ["Prts", ["String", tok.tokval], []] @gettok.nxt } else { e := ["Prti", expr(gettok, 0), []] } t := ["Sequence", t, e] accept(gettok, "Comma") | (done := 1) } expect(gettok, "Print", "RightParen") expect(gettok, "Print", "Semicolon") } else if (@gettok.curr).tok == "Semicolon" then { @gettok.nxt } else if (@gettok.curr).tok == "Identifier" then { v := ["Identifier", (@gettok.curr).tokval] @gettok.nxt expect(gettok, "assign", "Op_assign") t := ["Assign", v, expr(gettok, 0)] expect(gettok, "assign", "Semicolon") } else if accept(gettok, "Keyword_while") then { e := paren_expr(gettok) t := ["While", e, stmt(gettok)] } else if accept(gettok, "LeftBrace") then { until (@gettok.curr).tok == ("RightBrace" | "End_of_input") do { t := ["Sequence", t, stmt(gettok)] } expect(gettok, "Lbrace", "RightBrace") } else if (@gettok.curr).tok ~== "End_of_input" then { tok := @gettok.curr error(tok, ("expecting start of statement, found '" || text(tok.tok) || "'")) } return t end   procedure paren_expr (gettok) local x   expect(gettok, "paren_expr", "LeftParen"); x := expr(gettok, 0); expect(gettok, "paren_expr", "RightParen"); return x end   procedure expr (gettok, p) local tok, save_tok local x, y local q   tok := @gettok.curr case tok.tok of { "LeftParen" : { x := paren_expr(gettok) } "Op_subtract" : { @gettok.nxt y := expr(gettok, precedence("Op_negate")) x := ["Negate", y, []] } "Op_add" : { @gettok.nxt x := expr(gettok, precedence("Op_negate")) } "Op_not" : { @gettok.nxt y := expr(gettok, precedence("Op_not")) x := ["Not", y, []] } "Identifier" : { x := ["Identifier", tok.tokval] @gettok.nxt } "Integer" : { x := ["Integer", tok.tokval] @gettok.nxt } default : { error(tok, "Expecting a primary, found: " || text(tok.tok)) } }   while (tok := @gettok.curr & is_binary(tok.tok) & p <= precedence(tok.tok)) do { save_tok := tok @gettok.nxt q := precedence(save_tok.tok) if not is_right_associative(save_tok.tok) then q +:= 1 x := [operator(save_tok.tok), x, expr(gettok, q)] }   return x end   procedure accept (gettok, tok) local nxt   if (@gettok.curr).tok == tok then nxt := @gettok.nxt else fail return nxt end   procedure expect (gettok, msg, tok) if (@gettok.curr).tok ~== tok then { error(@gettok.curr, msg || ": Expecting '" || text(tok) || "', found '" || text((@gettok.curr).tok) || "'") } return @gettok.nxt end   procedure error (token, msg) write("(", token.line_no, ", ", token.column_no, ") error: ", msg) exit(1) end   procedure precedence (tok) local p   case tok of { "Op_multiply" : p := 13 "Op_divide" : p := 13 "Op_mod" : p := 13 "Op_add" : p := 12 "Op_subtract" : p := 12 "Op_negate" : p := 14 "Op_not" : p := 14 "Op_less" : p := 10 "Op_lessequal" : p := 10 "Op_greater" : p := 10 "Op_greaterequal" : p := 10 "Op_equal" : p := 9 "Op_notequal" : p := 9 "Op_and" : p := 5 "Op_or" : p := 4 default : p := -1 } return p end   procedure is_binary (tok) return ("Op_add" | "Op_subtract" | "Op_multiply" | "Op_divide" | "Op_mod" | "Op_less" | "Op_lessequal" | "Op_greater" | "Op_greaterequal" | "Op_equal" | "Op_notequal" | "Op_and" | "Op_or") == tok fail end   procedure is_right_associative (tok) # None of the current operators is right associative. fail end   procedure operator (tok) local s   case tok of { "Op_multiply" : s := "Multiply" "Op_divide" : s := "Divide" "Op_mod" : s := "Mod" "Op_add" : s := "Add" "Op_subtract" : s := "Subtract" "Op_negate" : s := "Negate" "Op_not" : s := "Not" "Op_less" : s := "Less" "Op_lessequal" : s := "LessEqual" "Op_greater" : s := "Greater" "Op_greaterequal" : s := "GreaterEqual" "Op_equal" : s := "Equal" "Op_notequal" : s := "NotEqual" "Op_and" : s := "And" "Op_or" : s := "Or" } return s end   procedure text (tok) local s   case tok of { "Keyword_else" : s := "else" "Keyword_if" : s := "if" "Keyword_print" : s := "print" "Keyword_putc" : s := "putc" "Keyword_while" : s := "while" "Op_multiply" : s := "*" "Op_divide" : s := "/" "Op_mod" : s := "%" "Op_add" : s := "+" "Op_subtract" : s := "-" "Op_negate" : s := "-" "Op_less" : s := "<" "Op_lessequal" : s := "<=" "Op_greater" : s := ">" "Op_greaterequal" : s := ">=" "Op_equal" : s := "==" "Op_notequal" : s := "!=" "Op_not" : s := "!" "Op_assign" : s := "=" "Op_and" : s := "&&" "Op_or" : s := "||" "LeftParen" : s := "(" "RightParen" : s := ")" "LeftBrace" : s := "{" "RightBrace" : s := "}" "Semicolon" : s := ";" "Comma" : s := "," "Identifier" : s := "Ident" "Integer" : s := "Integer literal" "String" : s := "String literal" "End_of_input" : s := "EOI" } return s end
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h>   #define for_x for (int x = 0; x < w; x++) #define for_y for (int y = 0; y < h; y++) #define for_xy for_x for_y void show(void *u, int w, int h) { int (*univ)[w] = u; printf("\033[H"); for_y { for_x printf(univ[y][x] ? "\033[07m \033[m" : " "); printf("\033[E"); } fflush(stdout); }   void evolve(void *u, int w, int h) { unsigned (*univ)[w] = u; unsigned new[h][w];   for_y for_x { int n = 0; for (int y1 = y - 1; y1 <= y + 1; y1++) for (int x1 = x - 1; x1 <= x + 1; x1++) if (univ[(y1 + h) % h][(x1 + w) % w]) n++;   if (univ[y][x]) n--; new[y][x] = (n == 3 || (n == 2 && univ[y][x])); } for_y for_x univ[y][x] = new[y][x]; }   void game(int w, int h) { unsigned univ[h][w]; for_xy univ[y][x] = rand() < RAND_MAX / 10 ? 1 : 0; while (1) { show(univ, w, h); evolve(univ, w, h); usleep(200000); } }   int main(int c, char **v) { int w = 0, h = 0; if (c > 1) w = atoi(v[1]); if (c > 2) h = atoi(v[2]); if (w <= 0) w = 30; if (h <= 0) h = 30; game(w, h); }
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Perl
Perl
my @point = (3, 8);
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Phix
Phix
with javascript_semantics enum x,y type point(object p) return sequence(p) and length(p)=y and atom(p[x]) and atom(p[y]) end type point p = {175,3.375} p[x] -= p[y]*20 puts(1,"point p is ") ?p printf(1,"p[x]:%g, p[y]:%g\n",{p[x],p[y]}) p[x] = 0 -- fine p[y] = "string" -- run-time error (not pwa/p2js)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Visual_Basic_.NET
Visual Basic .NET
'Immutable Strings Dim a = "Test string" Dim b = a 'reference to same string Dim c = New String(a.ToCharArray) 'new string, normally not used   'Mutable Strings Dim x As New Text.StringBuilder("Test string") Dim y = x 'reference Dim z = New Text.StringBuilder(x.ToString) 'new string
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
var s = "wren" var t = s System.print("Are 's' and 't' equal? %(s == t)")
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#Sidef
Sidef
var points = []; while (points.len < 100) { var (x, y) = 2.of{31.rand.int - 15}...; var r2 = (x**2 + y**2); if ((r2 >= 100) && (r2 <= 225)) { points.append([x, y]); } }   print <<'HEAD'; %!PS-Adobe-3.0 EPSF-3.0 %%BoundingBox 0 0 400 400 200 200 translate 10 10 scale 0 setlinewidth 1 0 0 setrgbcolor 0 0 10 0 360 arc stroke 0 0 15 360 0 arcn stroke 0 setgray /pt { .1 0 360 arc fill } def HEAD   points.each { |pt| say "#{pt.join(' ')} pt" }; print '%%EOF';
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Arturo
Arturo
num: 2   if? num=2 [ print "yep, num is 2" ] else [ print "something went wrong..." ]
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#C.23
C#
  static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" };   void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) .ToList() .ForEach(Console.WriteLine); }   string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); }     string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1));   return string.Join(separator, match.Value.Split(interval)); }   public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); }   static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue;   yield return source.Substring(i - interval, interval); } } }  
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
L(strings_s) [‘AA AA AA AA’, ‘AA ACB BB CC’] V strings = strings_s.split(‘ ’) print(strings) print(all(zip(strings, strings[1..]).map(a -> a[0] == a[1]))) print(all(zip(strings, strings[1..]).map(a -> a[0] < a[1]))) print()
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#11l
11l
:start: print(‘Program name: ’:argv[0]) print("Arguments:\n":argv[1..].join("\n"))
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Forth
Forth
CREATE BUF 0 , \ single-character look-ahead buffer : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : >INT ( -- n) >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ; CREATE A 0 , : C@A ( -- c) A @ C@ ; : C@A+ ( -- c) C@A 1 CHARS A +! ; : C!A+ ( c --) A @ C! 1 CHARS A +! ; : WORD ( -- c-addr) >SPACE PAD 1+ A ! BEGIN PEEK SPACE? INVERT WHILE GETC C!A+ REPEAT >SPACE PAD A @ OVER - 1- PAD C! ; : >STRING ( -- c-addr) >SPACE GETC DROP PAD 1+ A ! BEGIN PEEK [CHAR] " <> WHILE GETC C!A+ REPEAT GETC DROP PAD A @ OVER - 1- PAD C! ; : \INTERN ( c-addr -- c-addr) HERE >R A ! C@A+ DUP C, BEGIN DUP WHILE C@A+ DUP [CHAR] \ = IF DROP -1 R@ +! C@A+ [CHAR] n = IF 10 ELSE [CHAR] \ THEN THEN C, 1- REPEAT DROP R> ; : . 0 .R ;   CREATE DATA 0 , CREATE STRINGS 0 , : >DATA HERE DATA ! WORD DROP >INT 4 * BEGIN DUP WHILE 0 C, 1- REPEAT DROP ; : >STRINGS HERE STRINGS ! WORD DROP >INT DUP >R CELLS ALLOT 0 BEGIN DUP R@ < WHILE DUP CELLS >STRING \INTERN STRINGS @ ROT + ! 1+ REPEAT R> DROP DROP ; : >HEADER >DATA >STRINGS ; : i32! ( n addr --) OVER $FF AND OVER C! 1+ OVER 8 RSHIFT $FF AND OVER C! 1+ OVER 16 RSHIFT $FF AND OVER C! 1+ SWAP 24 RSHIFT $FF AND SWAP C! ; : i32@ ( addr -- n) >R \ This is kinda slow... hmm R@ C@ R@ 1 + C@ 8 LSHIFT OR R@ 2 + C@ 16 LSHIFT OR R> 3 + C@ 24 LSHIFT OR DUP $7FFFFFFF AND SWAP $80000000 AND - ; \ sign extend : i32, ( n --) HERE 4 ALLOT i32! ; : i32@+ ( -- n) A @ i32@ A @ 4 + A ! ; CREATE BYTECODE 0 , : @fetch i32@+ 4 * DATA @ + i32@ ; : @store i32@+ 4 * DATA @ + i32! ; : @jmp i32@+ BYTECODE @ + A ! ; : @jz IF 4 A +! ELSE @jmp THEN ; : @prts CELLS STRINGS @ + @ COUNT TYPE ; : @div >R S>D R> SM/REM SWAP DROP ; CREATE OPS ' @fetch , ' @store , ' i32@+ , ' @jmp , ' @jz , ' EMIT , ' . , ' @prts , ' NEGATE , ' 0= , ' + , ' - , ' * , ' @div , ' MOD , ' < , ' > , ' <= , ' >= , ' = , ' <> , ' AND , ' OR , ' BYE , CREATE #OPS 0 , : OP: CREATE #OPS @ , 1 #OPS +! DOES> @ ; OP: fetch OP: store OP: push OP: jmp OP: jz OP: prtc OP: prti OP: prts OP: neg OP: not OP: add OP: sub OP: mul OP: div OP: mod OP: lt OP: gt OP: le OP: ge OP: eq OP: ne OP: and OP: or OP: halt : >OP WORD FIND 0= IF ." Unrecognized opcode" ABORT THEN EXECUTE ; : >i32 >INT i32, ; : >[i32] GETC DROP >i32 GETC DROP ; : >OFFSET WORD DROP ( drop relative offset) >i32 ; CREATE >PARAM ' >[i32] DUP , , ' >i32 , ' >OFFSET DUP , , : >BYTECODE HERE >R BEGIN >INT DROP >OP >R R@ C, R@ 5 < IF R@ CELLS >PARAM + @ EXECUTE THEN R> halt = UNTIL R> BYTECODE ! ; : RUN BYTECODE @ A ! BEGIN C@A+ CELLS OPS + @ EXECUTE AGAIN ; >HEADER >BYTECODE RUN
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdint.h> #include <ctype.h>   typedef unsigned char uchar;   typedef enum { nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or } NodeType;   typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t;   typedef uchar code;   typedef struct Tree { NodeType node_type; struct Tree *left; struct Tree *right; char *value; } Tree;   #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _p = 0; \ int _qy_ ## name ## _max = 0   #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0)   #define da_rewind(name) _qy_ ## name ## _p = 0   #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) #define da_len(name) _qy_ ## name ## _p #define da_add(name) do {da_redim(name); _qy_ ## name ## _p++;} while (0)   FILE *source_fp, *dest_fp; static int here; da_dim(object, code); da_dim(globals, const char *); da_dim(string_pool, const char *);   // dependency: Ordered by NodeType, must remain in same order as NodeType enum struct { char *enum_text; NodeType node_type; Code_t opcode; } atr[] = { {"Identifier" , nd_Ident, -1 }, {"String" , nd_String, -1 }, {"Integer" , nd_Integer, -1 }, {"Sequence" , nd_Sequence, -1 }, {"If" , nd_If, -1 }, {"Prtc" , nd_Prtc, -1 }, {"Prts" , nd_Prts, -1 }, {"Prti" , nd_Prti, -1 }, {"While" , nd_While, -1 }, {"Assign" , nd_Assign, -1 }, {"Negate" , nd_Negate, NEG}, {"Not" , nd_Not, NOT}, {"Multiply" , nd_Mul, MUL}, {"Divide" , nd_Div, DIV}, {"Mod" , nd_Mod, MOD}, {"Add" , nd_Add, ADD}, {"Subtract" , nd_Sub, SUB}, {"Less" , nd_Lss, LT }, {"LessEqual" , nd_Leq, LE }, {"Greater" , nd_Gtr, GT }, {"GreaterEqual", nd_Geq, GE }, {"Equal" , nd_Eql, EQ }, {"NotEqual" , nd_Neq, NE }, {"And" , nd_And, AND}, {"Or" , nd_Or, OR }, };   void error(const char *fmt, ... ) { va_list ap; char buf[1000];   va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); }   Code_t type_to_op(NodeType type) { return atr[type].opcode; }   Tree *make_node(NodeType node_type, Tree *left, Tree *right) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->left = left; t->right = right; return t; }   Tree *make_leaf(NodeType node_type, char *value) { Tree *t = calloc(sizeof(Tree), 1); t->node_type = node_type; t->value = strdup(value); return t; }   /*** Code generator ***/   void emit_byte(int c) { da_append(object, (uchar)c); ++here; }   void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x;   x.n = n;   for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } }   int hole() { int t = here; emit_int(0); return t; }   void fix(int src, int dst) { *(int32_t *)(object + src) = dst-src; }   int fetch_var_offset(const char *id) { for (int i = 0; i < da_len(globals); ++i) { if (strcmp(id, globals[i]) == 0) return i; } da_add(globals); int n = da_len(globals) - 1; globals[n] = strdup(id); return n; }   int fetch_string_offset(const char *st) { for (int i = 0; i < da_len(string_pool); ++i) { if (strcmp(st, string_pool[i]) == 0) return i; } da_add(string_pool); int n = da_len(string_pool) - 1; string_pool[n] = strdup(st); return n; }   void code_gen(Tree *x) { int p1, p2, n;   if (x == NULL) return; switch (x->node_type) { case nd_Ident: emit_byte(FETCH); n = fetch_var_offset(x->value); emit_int(n); break; case nd_Integer: emit_byte(PUSH); emit_int(atoi(x->value)); break; case nd_String: emit_byte(PUSH); n = fetch_string_offset(x->value); emit_int(n); break; case nd_Assign: n = fetch_var_offset(x->left->value); code_gen(x->right); emit_byte(STORE); emit_int(n); break; case nd_If: code_gen(x->left); // if expr emit_byte(JZ); // if false, jump p1 = hole(); // make room for jump dest code_gen(x->right->left); // if true statements if (x->right->right != NULL) { emit_byte(JMP); p2 = hole(); } fix(p1, here); if (x->right->right != NULL) { code_gen(x->right->right); fix(p2, here); } break; case nd_While: p1 = here; code_gen(x->left); // while expr emit_byte(JZ); // if false, jump p2 = hole(); // make room for jump dest code_gen(x->right); // statements emit_byte(JMP); // back to the top fix(hole(), p1); // plug the top fix(p2, here); // plug the 'if false, jump' break; case nd_Sequence: code_gen(x->left); code_gen(x->right); break; case nd_Prtc: code_gen(x->left); emit_byte(PRTC); break; case nd_Prti: code_gen(x->left); emit_byte(PRTI); break; case nd_Prts: code_gen(x->left); emit_byte(PRTS); break; case nd_Lss: case nd_Gtr: case nd_Leq: case nd_Geq: case nd_Eql: case nd_Neq: case nd_And: case nd_Or: case nd_Sub: case nd_Add: case nd_Div: case nd_Mul: case nd_Mod: code_gen(x->left); code_gen(x->right); emit_byte(type_to_op(x->node_type)); break; case nd_Negate: case nd_Not: code_gen(x->left); emit_byte(type_to_op(x->node_type)); break; default: error("error in code generator - found %d, expecting operator\n", x->node_type); } }   void code_finish() { emit_byte(HALT); }   void list_code() { fprintf(dest_fp, "Datasize: %d Strings: %d\n", da_len(globals), da_len(string_pool)); for (int i = 0; i < da_len(string_pool); ++i) fprintf(dest_fp, "%s\n", string_pool[i]);   code *pc = object;   again: fprintf(dest_fp, "%5d ", (int)(pc - object)); switch (*pc++) { case FETCH: fprintf(dest_fp, "fetch [%d]\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case STORE: fprintf(dest_fp, "store [%d]\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case PUSH : fprintf(dest_fp, "push  %d\n", *(int32_t *)pc); pc += sizeof(int32_t); goto again; case ADD : fprintf(dest_fp, "add\n"); goto again; case SUB : fprintf(dest_fp, "sub\n"); goto again; case MUL : fprintf(dest_fp, "mul\n"); goto again; case DIV : fprintf(dest_fp, "div\n"); goto again; case MOD : fprintf(dest_fp, "mod\n"); goto again; case LT : fprintf(dest_fp, "lt\n"); goto again; case GT : fprintf(dest_fp, "gt\n"); goto again; case LE : fprintf(dest_fp, "le\n"); goto again; case GE : fprintf(dest_fp, "ge\n"); goto again; case EQ : fprintf(dest_fp, "eq\n"); goto again; case NE : fprintf(dest_fp, "ne\n"); goto again; case AND : fprintf(dest_fp, "and\n"); goto again; case OR : fprintf(dest_fp, "or\n"); goto again; case NOT : fprintf(dest_fp, "not\n"); goto again; case NEG : fprintf(dest_fp, "neg\n"); goto again; case JMP : fprintf(dest_fp, "jmp (%d) %d\n", *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object)); pc += sizeof(int32_t); goto again; case JZ : fprintf(dest_fp, "jz (%d) %d\n", *(int32_t *)pc, (int32_t)(pc + *(int32_t *)pc - object)); pc += sizeof(int32_t); goto again; case PRTC : fprintf(dest_fp, "prtc\n"); goto again; case PRTI : fprintf(dest_fp, "prti\n"); goto again; case PRTS : fprintf(dest_fp, "prts\n"); goto again; case HALT : fprintf(dest_fp, "halt\n"); break; default:error("listcode:Unknown opcode %d\n", *(pc - 1)); } }   void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); }   NodeType get_enum_value(const char name[]) { for (size_t i = 0; i < sizeof(atr) / sizeof(atr[0]); i++) { if (strcmp(atr[i].enum_text, name) == 0) { return atr[i].node_type; } } error("Unknown token %s\n", name); return -1; }   char *read_line(int *len) { static char *text = NULL; static int textmax = 0;   for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; }   char *rtrim(char *text, int *len) { // remove trailing spaces for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ;   text[*len] = '\0'; return text; }   Tree *load_ast() { int len; char *yytext = read_line(&len); yytext = rtrim(yytext, &len);   // get first token char *tok = strtok(yytext, " ");   if (tok[0] == ';') { return NULL; } NodeType node_type = get_enum_value(tok);   // if there is extra data, get it char *p = tok + strlen(tok); if (p != &yytext[len]) { for (++p; isspace(*p); ++p) ; return make_leaf(node_type, p); }   Tree *left = load_ast(); Tree *right = load_ast(); return make_node(node_type, left, right); }   int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); init_io(&dest_fp, stdout, "wb", argc > 2 ? argv[2] : "");   code_gen(load_ast()); code_finish(); list_code();   return 0; }
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#Erlang
Erlang
  -module( compare_sorting_algorithms ).   -export( [task/0] ).   task() -> Ns = [100, 1000, 10000], Lists = [{"ones", fun list_of_ones/1, Ns}, {"ranges", fun list_of_ranges/1, Ns}, {"reversed_ranges", fun list_of_reversed_ranges/1, Ns}, {"shuffleds", fun list_of_shuffleds/1, Ns}], Sorts = [{bubble_sort, fun bubble_sort:list/1}, {insertion_sort, fun sort:insertion/1}, {iquick_sort, fun quicksort:qsort/1}], Results = [time_list(X, Sorts) || X <- Lists], [file:write_file(X++".png", egd_chart:graph(Y, [{x_label, "log N"}, {y_label, "log ms"}])) || {X, Y} <- Results].     list_of_ones( N ) -> [1 || _X <- lists:seq(1, N)]. list_of_ranges( N ) -> [X || X <- lists:seq(1, N)]. list_of_reversed_ranges( N ) -> lists:reverse( list_of_ranges(N) ). list_of_shuffleds( N ) -> [random:uniform(N) || _X <- lists:seq(1, N)].   time_list( {List, List_fun, Values}, Sorts ) -> Results = [{Sort, time_sort(Sort_fun, List_fun, Values)} || {Sort, Sort_fun} <- Sorts], {List, Results}.   time_sort( Sort_fun, List_fun, Values ) -> [time(Sort_fun, List_fun, X) || X <- Values].   time( Fun, List_fun, N ) -> {Time, _Result} = timer:tc( fun() -> Fun( List_fun(N) ) end ), {math:log10(N), math:log10(Time)}.  
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) The interpreter algorithm is relatively simple interp(x) if x == NULL return NULL elif x.node_type == Integer return x.value converted to an integer elif x.node_type == Ident return the current value of variable x.value elif x.node_type == String return x.value elif x.node_type == Assign globals[x.left.value] = interp(x.right) return NULL elif x.node_type is a binary operator return interp(x.left) operator interp(x.right) elif x.node_type is a unary operator, return return operator interp(x.left) elif x.node_type == If if (interp(x.left)) then interp(x.right.left) else interp(x.right.right) return NULL elif x.node_type == While while (interp(x.left)) do interp(x.right) return NULL elif x.node_type == Prtc print interp(x.left) as a character, no newline return NULL elif x.node_type == Prti print interp(x.left) as an integer, no newline return NULL elif x.node_type == Prts print interp(x.left) as a string, respecting newlines ("\n") return NULL elif x.node_type == Sequence interp(x.left) interp(x.right) return NULL else error("unknown node type") Notes: Because of the simple nature of our tiny language, Semantic analysis is not needed. Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0. This means, for instance, that 3 / 2 should result in 1. For division when one of the operands is negative, the result should be truncated towards 0. This means, for instance, that 3 / -2 should result in -1. Test program prime.t lex <prime.t | parse | interp /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 101 is prime Total primes found: 26 Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task Virtual Machine Interpreter task
#Phix
Phix
-- -- demo\rosetta\Compiler\interp.exw -- ================================ -- with javascript_semantics include parse.e sequence vars = {}, vals = {} function var_idx(sequence inode) if inode[1]!=tk_Identifier then ?9/0 end if string ident = inode[2] integer n = find(ident,vars) if n=0 then vars = append(vars,ident) vals = append(vals,0) n = length(vars) end if return n end function function interp(object t) if t!=NULL then integer ntype = t[1] object t2 = t[2], t3 = iff(length(t)=3?t[3]:0) switch ntype do case tk_Sequence: {} = interp(t2) {} = interp(t3) case tk_assign: vals[var_idx(t2)] = interp(t3) case tk_Identifier: return vals[var_idx(t)] case tk_Integer: return t2 case tk_String: return t2 case tk_lt: return interp(t2) < interp(t3) case tk_add: return interp(t2) + interp(t3) case tk_sub: return interp(t2) - interp(t3) case tk_while: while interp(t2) do {} = interp(t3) end while case tk_Prints: puts(1,interp(t2)) case tk_Printi: printf(1,"%d",interp(t2)) case tk_putc: printf(1,"%c",interp(t2)) case tk_and: return interp(t2) and interp(t3) case tk_or: return interp(t2) or interp(t3) case tk_le: return interp(t2) <= interp(t3) case tk_ge: return interp(t2) >= interp(t3) case tk_ne: return interp(t2) != interp(t3) case tk_gt: return interp(t2) > interp(t3) case tk_mul: return interp(t2) * interp(t3) case tk_div: return trunc(interp(t2)/interp(t3)) case tk_mod: return remainder(interp(t2),interp(t3)) case tk_if: {} = interp(t3[iff(interp(t2)?2:3)]) case tk_not: return not interp(t2) case tk_neg: return - interp(t2) else error("unknown node type") end switch end if return NULL end function procedure main(sequence cl) open_files(cl) toks = lex() object t = parse() {} = interp(t) close_files() end procedure --main(command_line()) main({0,0,"primes.c"})
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
using System; using System.Collections.Generic;   namespace example { class Program { static void Main(string[] args) { var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(strings); }   private static void compareAndReportStringsLength(string[] strings) { if (strings.Length > 0) { char Q = '"'; string hasLength = " has length "; string predicateMax = " and is the longest string"; string predicateMin = " and is the shortest string"; string predicateAve = " and is neither the longest nor the shortest string"; string predicate;   (int, int)[] li = new (int, int)[strings.Length]; for (int i = 0; i < strings.Length; i++) li[i] = (strings[i].Length, i); Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1); int maxLength = li[0].Item1; int minLength = li[strings.Length - 1].Item1;   for (int i = 0; i < strings.Length; i++) { int length = li[i].Item1; string str = strings[li[i].Item2]; if (length == maxLength) predicate = predicateMax; else if (length == minLength) predicate = predicateMin; else predicate = predicateAve; Console.WriteLine(Q + str + Q + hasLength + length + predicate); } } }   } }  
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#J
J
require'format/printf'   tkref=: tokenize 'End_of_input*/%+--<<=>>===!=!&&||print=print(if{else}while;,putc)a""0' tkref,. (tknames)=: tknames=:;: {{)n End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_not Op_and Op_or Keyword_print Op_assign Keyword_print LeftParen Keyword_if LeftBrace Keyword_else RightBrace Keyword_while Semicolon Comma Keyword_putc RightParen Identifier String Integer }}-.LF   tkV=: 2 (tkref i.tokenize '*/%+-<<=>>===!=&&||')} (#tktyp)#0 tkV=: 1 (1 0+tkref i.tokenize '-!')} tkV tkPrec=: 13 13 13 12 12 10 10 10 10 9 9 5 4 (tkref i.tokenize'*/%+-<<=>>==!=&&||')} tkV<._1 tkPrec=: 14 (1 0+tkref i.tokenize'-!')} tkPrec NB. proofread |:(<"1 tkV,.tkPrec),tkref,:tknames   tkref,.(ndDisp)=: ndDisp=:;:{{)n Sequence Multiply Divide Mod Add Subtract Negate Less LessEqual Greater GreaterEqual Equal NotEqual Not And Or Prts Assign Prti x If x x x While x x Prtc x Identifier String Integer }}-.LF NB. proofread |:tkref,:ndDisp   gettoken=: {{ 'tok_ln tok_col'=: (0;ndx){::x 'tok_name tok_value'=: (1;ndx){::x if. 'Error'-:tok_name do. error 'invalid word ',":tok_value end. ind=. tknames i.<tok_name tok_text=: ind{::tkref tok_valence=: ind{::tkV tok_precedence=: ind{::tkPrec ndx=:ndx+1 node_display=: ind{::ndDisp }}   parse=: {{ ndx=: tok_ln=: tok_col=: 0 gettok=: y&gettoken gettok'' t=.a: whilst.-.(a:-:t)+.tok_name-:End_of_input do. t=. Sequence make_node t stmt'' end. }}   stmt=:{{)v t=. a: select.tok_name case.Keyword_if do. s=. stmt e=. paren_expr gettok'' if.Keyword_else-:tok_name do. S=. stmt gettok'' else. S=. a: end. t=. If make_node e If make_node s S case.Keyword_putc do. e=. paren_expr gettok'' t=. Prtc make_node e a: Prtc expect Semicolon case.Keyword_print do.gettok'' 'Print' expect LeftParen while.do. if.String-:tok_name do. gettok e=. Prts make_node (String make_leaf tok_value) a: else. e=. Prti make_node (expr 0) a: end. t=. Sequence make_node t e if.Comma-:tok_name do.Comma expect Comma else.break.end. end. 'Print' expect RightParen 'Print' expect Semicolon case.Semicolon do.gettok'' case.Identifier do. gettok v=. Identifier make_leaf tok_value Assign expect Op_assign t=. Assign make_node v e=. expr 0 Assign expect Semicolon case.Keyword_while do. t=. While make_node e s=. stmt e=. paren_expr gettok'' case.LeftBrace do. 'LeftBrace' expect LeftBrace while.-.(<tok_name) e. RightBrace;End_of_input do. t=. Sequence make_node t stmt'' end. 'LeftBrace' expect RightBrace case.End_of_input do. case.do. error 'Expecting start of statement, found %s'sprintf<tok_text end. t }}   paren_expr=: {{ 'paren_expr' expect LeftParen t=. expr 0 'paren_expr' expect RightParen t }}   not_prec=: tkPrec{~tknames i.<Op_not expr=: {{ select.tok_name case.LeftParen do.e=. paren_expr'' case.Op_add do.gettok'' e=. expr not_prec case.Op_subtract do.gettok'' e=. Negate make_node (expr not_prec) a: case.Op_not do.gettok'' e=. Not make_node (expr not_prec) a: case.Identifier do. gettok e=. Identifier make_leaf tok_value case.Integer do. gettok e=. Integer make_leaf tok_value case.do. error 'Expecting a primary, found %s'sprintf<tok_text end. while.(2=tok_valence)*tok_precedence>:y do. q=. 1+tok_precedence [ op=. node_display NB. no right associative operators gettok'' node=. expr q e=. op make_node e node end. e }}   expect=: {{ if.y-:tok_name do. gettok'' return.end. error '%s: Expecting "%s", found "%s"'sprintf x;(tkref{::~tknames i.<y);tok_text }}   make_leaf=: {{ x;y }}   make_node=: {{ m;n;<y }}   error=: {{ echo 'Error: line %d, column %d: %s\n'sprintf tok_ln;tok_col;y throw. }}     syntax=: {{  ;(flatAST parse y),each LF }}   flatAST=: {{ assert.*L.y select.#y case.1 do.<';' assert.y-:a: case.2 do.<;:inv ":each y case.3 do.({.y),(flatAST 1{::y),flatAST 2{::y case.do.assert.0 end. }}  
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#C.23
C#
  using System; using System.Text; using System.Threading;   namespace ConwaysGameOfLife { // Plays Conway's Game of Life on the console with a random initial state. class Program { // The delay in milliseconds between board updates. private const int DELAY = 50;   // The cell colors. private const ConsoleColor DEAD_COLOR = ConsoleColor.White; private const ConsoleColor LIVE_COLOR = ConsoleColor.Black;   // The color of the cells that are off of the board. private const ConsoleColor EXTRA_COLOR = ConsoleColor.Gray;   private const char EMPTY_BLOCK_CHAR = ' '; private const char FULL_BLOCK_CHAR = '\u2588';   // Holds the current state of the board. private static bool[,] board;   // The dimensions of the board in cells. private static int width = 32; private static int height = 32;   // True if cell rules can loop around edges. private static bool loopEdges = true;     static void Main(string[] args) { // Use initializeRandomBoard for a larger, random board. initializeDemoBoard();   initializeConsole();   // Run the game until the Escape key is pressed. while (!Console.KeyAvailable || Console.ReadKey(true).Key != ConsoleKey.Escape) { Program.drawBoard(); Program.updateBoard();   // Wait for a bit between updates. Thread.Sleep(DELAY); } }   // Sets up the Console. private static void initializeConsole() { Console.BackgroundColor = EXTRA_COLOR; Console.Clear();   Console.CursorVisible = false;   // Each cell is two characters wide. // Using an extra row on the bottom to prevent scrolling when drawing the board. int width = Math.Max(Program.width, 8) * 2 + 1; int height = Math.Max(Program.height, 8) + 1; Console.SetWindowSize(width, height); Console.SetBufferSize(width, height);   Console.BackgroundColor = DEAD_COLOR; Console.ForegroundColor = LIVE_COLOR; }   // Creates the initial board with a random state. private static void initializeRandomBoard() { var random = new Random();   Program.board = new bool[Program.width, Program.height]; for (var y = 0; y < Program.height; y++) { for (var x = 0; x < Program.width; x++) { // Equal probability of being true or false. Program.board[x, y] = random.Next(2) == 0; } } }   // Creates a 3x3 board with a blinker. private static void initializeDemoBoard() { Program.width = 3; Program.height = 3;   Program.loopEdges = false;   Program.board = new bool[3, 3]; Program.board[1, 0] = true; Program.board[1, 1] = true; Program.board[1, 2] = true; }   // Draws the board to the console. private static void drawBoard() { // One Console.Write call is much faster than writing each cell individually. var builder = new StringBuilder();   for (var y = 0; y < Program.height; y++) { for (var x = 0; x < Program.width; x++) { char c = Program.board[x, y] ? FULL_BLOCK_CHAR : EMPTY_BLOCK_CHAR;   // Each cell is two characters wide. builder.Append(c); builder.Append(c); } builder.Append('\n'); }   // Write the string to the console. Console.SetCursorPosition(0, 0); Console.Write (builder.ToString()); }   // Moves the board to the next state based on Conway's rules. private static void updateBoard() { // A temp variable to hold the next state while it's being calculated. bool[,] newBoard = new bool[Program.width, Program.height];   for (var y = 0; y < Program.height; y++) { for (var x = 0; x < Program.width; x++) { var n = countLiveNeighbors(x, y); var c = Program.board[x, y];   // A live cell dies unless it has exactly 2 or 3 live neighbors. // A dead cell remains dead unless it has exactly 3 live neighbors. newBoard[x, y] = c && (n == 2 || n == 3) || !c && n == 3; } }   // Set the board to its new state. Program.board = newBoard; }   // Returns the number of live neighbors around the cell at position (x,y). private static int countLiveNeighbors(int x, int y) { // The number of live neighbors. int value = 0;   // This nested loop enumerates the 9 cells in the specified cells neighborhood. for (var j = -1; j <= 1; j++) { // If loopEdges is set to false and y+j is off the board, continue. if (!Program.loopEdges && y + j < 0 || y + j >= Program.height) { continue; }   // Loop around the edges if y+j is off the board. int k = (y + j + Program.height) % Program.height;   for (var i = -1; i <= 1; i++) { // If loopEdges is set to false and x+i is off the board, continue. if (!Program.loopEdges && x + i < 0 || x + i >= Program.width) { continue; }   // Loop around the edges if x+i is off the board. int h = (x + i + Program.width) % Program.width;   // Count the neighbor cell at (h,k) if it is alive. value += Program.board[h, k] ? 1 : 0; } }   // Subtract 1 if (x,y) is alive since we counted it as a neighbor. return value - (Program.board[x, y] ? 1 : 0); } } }    
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PHP
PHP
# Using pack/unpack $point = pack("ii", 1, 2);   $u = unpack("ix/iy", $point); echo $x; echo $y;   list($x,$y) = unpack("ii", $point); echo $x; echo $y;
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PicoLisp
PicoLisp
(class +Point)   (dm T (X Y) (=: x X) (=: y Y) )   (setq P (new '(+Point) 3 4))   (show P)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#X86_Assembly
X86 Assembly
  section .data string db "Hello World", 0   section .bss string2 resb 12   section .text global _main _main: mov ecx, 0 looping: mov al, [string + ecx] mov [string2 + ecx], al inc ecx cmp al, 0 ;copy until we find the terminating 0 je end jmp looping end: xor eax, eax ret  
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#X86-64_Assembly
X86-64 Assembly
  option casemap:none option literals:on   printf proto :dword, :VARARG exit proto :dword   .data s db "Goodbye, World!",0   .data? d db 20 dup (?) dp dq ? tb dd ?   .code main proc lea rsi, s ;; Put the address of var S into the source index(RSI) xor rcx, rcx ;; Zero out RCX _getsize: inc rcx ;; Advanced the index by 1 cmp byte ptr [rsi+rcx],0 ;; check the current byte for terminating 0 jne _getsize ;; nope, jump back and check again   mov tb, ecx ;; tb = Total bytes, Keep a copy of the size of the string lea rsi, s ;; Copy the address of s into the source index(rsi) lea rdi, d ;; Copy the address of d into the destination index(rdi) rep movsb ;; Copy bytes from ESI to EDI until RCX is 0   lea rax, s ;; Get the address of S mov dp, rax ;; Copy it from RAX to dp   mov rbx,rdi ;; Make a copy of RDI, cause over writes due to ABI call args T_T invoke printf, CSTR("-> s (0x%x) = %s",10), rsi, addr s invoke printf, CSTR("-> d (0x%x) = %s",10), rbx, addr d invoke printf, CSTR("-> dp (0x%x) = %s",10), addr dp, dp invoke printf, CSTR("-> bytes copied: %i",10), tb xor rsi, rsi call exit ret main endp   end  
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val plotWindow = fn coords => (* input list of int*int within 'dim' *) let val dim = {tw=325,th=325} ; val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; (* single call only *) val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ]  ; val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth (#tw dim), XmNheight (#th dim) ] ; val usegc = DefaultGC (XtDisplay canvas) ; val put = fn (w,s,t)=> ( XSetForeground usegc 0xfffffff ; XFillRectangle (XtWindow canvas) usegc (Area{x=0,y=0,w = #tw dim, h= #th dim})  ; XSetForeground usegc 0  ; XDrawPoints (XtWindow canvas) usegc ( List.map (fn (x,y)=>XPoint {x=x,y=y}) coords ) CoordModeOrigin ; t ) in   ( XtSetCallbacks canvas [ (XmNexposeCallback , put) ] XmNarmCallback ; XtManageChild canvas ; XtManageChild main ; XtRealizeWidget shell )   end;   val urandomlist = fn seed => fn n => (* put code from (www.rosettacode.org) wiki/Random_numbers#Standard_ML 'urandomlist' here input : seed and number of drawings *) end;   val normalizedPts = fn () => (* select ([0,1]*[0,1]) points in normalized bandwidth *) let val realseeds = ( 972.1 , 10009.3 ) ; val usum = fn (u,v) => u*(u-1.0) + v*(v-1.0) ; val lim = ( ~350.0/900.0, ~225.0/900.0 ) ; (* limits to usum *) val select = fn i => usum i <= #2 lim andalso usum i >= #1 lim  ; (* select according to inequalities *) val uv = ListPair.zip ( urandomlist (#1 realseeds) 2500 , urandomlist (#2 realseeds) 2500 ) (* take 2500 couples *) in List.take ( List.filter select uv , 1000 ) end ;
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Astro
Astro
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: qux()   match x: 0 => foo() 1 => bar() 2 => baz() _ => qux()   (a) ? b : c
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#D
D
import std.stdio, std.regex, std.range;   auto commatize(in char[] txt, in uint start=0, in uint step=3, in string ins=",") @safe in { assert(step > 0); } body { if (start > txt.length || step > txt.length) return txt;   // First number may begin with digit or decimal point. Exponents ignored. enum decFloField = ctRegex!("[0-9]*\\.[0-9]+|[0-9]+");   auto matchDec = matchFirst(txt[start .. $], decFloField); if (!matchDec) return txt;   // Within a decimal float field: // A decimal integer field to commatize is positive and not after a point. enum decIntField = ctRegex!("(?<=\\.)|[1-9][0-9]*"); // A decimal fractional field is preceded by a point, and is only digits. enum decFracField = ctRegex!("(?<=\\.)[0-9]+");   return txt[0 .. start] ~ matchDec.pre ~ matchDec.hit .replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField) .replace!(m => m.hit.chunks(step).join(ins))(decFracField) ~ matchDec.post; }   unittest { // An attempted solution may have one or more of the following errors: // ignoring a number that has only zero before its decimal point assert("0.0123456".commatize == "0.012,345,6"); // commatizing numbers other than the first assert("1000 2.3000".commatize == "1,000 2.3000"); // only commatizing in one direction from the decimal point assert("0001123.456789".commatize == "0001,123.456,789"); // detecting prefixes such as "Z$" requires detecting other prefixes assert(" NZ$300000".commatize == " NZ$300,000"); // detecting a decimal field that isn't attached to the first number assert(" 2600 and .0125".commatize == " 2,600 and .0125"); // ignoring the start value, or confusing base 0 (used here) with base 1 assert("1 77000".commatize(1) == "1 77,000"); // ignoring a number that begins with a point, or treating it as integer assert(" .0104004".commatize == " .010,400,4"); }   void main() { "pi=3.14159265358979323846264338327950288419716939937510582097494459231" .commatize(0, 5, " ").writeln; "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." .commatize(0, 3, ".").writeln; foreach (const line; "commatizing_numbers_using_defaults.txt".File.byLine) line.commatize.writeln; }
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#360_Assembly
360 Assembly
* Compare a list of strings 31/01/2017 COMPLIST CSECT USING COMPLIST,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) " -> LR R13,R15 " addressability MVC SNAME,=C'ABC' LA R1,SNAME LA R2,ABC BAL R14,TEST call test('ABC',abc) MVC SNAME,=C'AAA' LA R1,SNAME LA R2,AAA BAL R14,TEST call test('AAA',aaa) MVC SNAME,=C'ACB' LA R1,SNAME LA R2,ACB BAL R14,TEST call test('ACB',acb) L R13,4(0,R13) epilog LM R14,R12,12(R13) " restore XR R15,R15 " rc=0 BR R14 exit *------- ---- test(name,xlist) ----------------------- TEST MVC NAME,0(R1) store argument #1 MVC XLIST(6),0(R2) store argument #2 MVI ALLEQ,X'01' alleq=true MVI INCRE,X'01' incre=true LA R6,1 i=1 LOOPI LA R2,NXLIST hbound(xlist) BCTR R2,0 -1 CR R6,R2 do i to hbound(xlist)-1 BH ELOOPI MVC XBOOL,ALLEQ OC XBOOL,INCRE or CLI XBOOL,X'01' and while alleq or incre BNE ELOOPI LA R2,1(R6) i+1 SLA R2,1 *2 LA R3,XLIST-2(R2) @xlist(i+1) LR R1,R6 i SLA R1,1 *2 LA R4,XLIST-2(R1) @xlist(i) CLC 0(2,R3),0(R4) if xlist(i+1)=xlist(i) BNE SEL1B MVI INCRE,X'00' incre=false B SEL1END SEL1B CLC 0(2,R3),0(R4) if xlist(i+1)<xlist(i) BNL SEL1OTH MVI INCRE,X'00' incre=false MVI ALLEQ,X'00' alleq=false B SEL1END SEL1OTH MVI ALLEQ,X'00' alleq=false SEL1END LA R6,1(R6) i=i+1 B LOOPI ELOOPI CLI ALLEQ,X'01' if alleq BNE SEL2B MVC TXT,=CL40'all elements are equal' B SEL2END SEL2B CLI INCRE,X'01' if incre BNE SEL2OTH MVC TXT,=CL40'elements are in increasing order' B SEL2END SEL2OTH MVC TXT,=CL40'neither equal nor in increasing order' SEL2END MVI PG,C' ' MVC PG+1(79),PG clear buffer MVC PG(3),NAME MVC PG+3(3),=C' : ' MVC PG+6(40),TXT XPRNT PG,L'PG BR R14 return to caller * ---- ---------------------------------------- SNAME DS CL3 ABC DC CL2'AA',CL2'BB',CL2'CC' AAA DC CL2'AA',CL2'AA',CL2'AA' ACB DC CL2'AA',CL2'CC',CL2'BB' NAME DS CL3 XLIST DS 3CL2 NXLIST EQU (*-XLIST)/L'XLIST ALLEQ DS X INCRE DS X TXT DS CL40 XBOOL DS X PG DS CL80 YREGS END COMPLIST
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Action.21
Action!
DEFINE PTR="CARD"   BYTE FUNC AreEqual(PTR ARRAY a BYTE len) INT i   FOR i=1 TO len-1 DO IF SCompare(a(0),a(i))#0 THEN RETURN (0) FI OD RETURN (1)   BYTE FUNC IsAscendingOrder(PTR ARRAY a BYTE len) INT i   FOR i=1 TO len-1 DO IF SCompare(a(i-1),a(i))>=0 THEN RETURN (0) FI OD RETURN (1)   PROC Test(PTR ARRAY a BYTE len) INT i   Print("Input array: [") FOR i=0 TO len-1 DO Print(a(i)) IF i<len-1 THEN Put(32) FI OD PrintE("]")   IF AreEqual(a,len) THEN PrintE("All strings are lexically equal.") ELSE PrintE("Not all strings are lexically equal.") FI   IF IsAscendingOrder(a,len) THEN PrintE("The list is in strict ascending order.") ELSE PrintE("The list is not in strict ascending order.") FI PutE() RETURN   PROC Main() PTR ARRAY a1(4),a2(4),a3(4),a4(1)   a1(0)="aaa" a1(1)="aaa" a1(2)="aaa" a1(3)="aaa" Test(a1,4)   a2(0)="aaa" a2(1)="aab" a2(2)="aba" a2(3)="baa" Test(a2,4)   a3(0)="aaa" a3(1)="aab" a3(2)="aba" a3(3)="aba" Test(a3,4)   a4(0)="aaa" Test(a4,1) RETURN
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#8080_Assembly
8080 Assembly
putch: equ 2 ; CP/M syscall to print character puts: equ 9 ; CP/M syscall to print $-terminated string arglen: equ 80h ; Length of argument argmt: equ 81h ; Argument string fcb1: equ 5Ch ; FCBs fcb2: equ 6Ch org 100h ;;; Print all argument(s) as given lxi d,cmdln ; Print 'Command line: ' mvi c,puts call 5 lda arglen ; Retrieve the length of the argument lxi h,argmt ; Pointer to argument string call plstr ;;; CP/M also assumes that the first two words on the command ;;; line are filenames, and prepares two FCBs with the filenames ;;; in them. If there are no filenames, they will be blank. lxi d,file1 ; Print the first one mvi c,puts call 5 mvi a,11 ; Filenames are 8+3 characters long and padded with lxi h,fcb1+1 ; spaces call plstr lxi d,file2 ; Print the second one mvi c,puts call 5 mvi a,11 lxi h,fcb2+1 ; ... fall through - on small systems saving bytes is a virtue ;;; This subroutine prints a length-A string in HL. plstr: ana a ; If A=0, print nothing. rz push psw ; Save A and HL registers on the stack push h ; (CP/M syscalls clobber all registers) mov e,m ; Print character under HL mvi c,putch call 5 pop h ; Restore A and HL registers pop psw inx h ; Increment string pointer dcr a ; Decrement character counter jnz plstr ; Print next character if not zero ret cmdln: db 'Command line: $' file1: db 13,10,'File 1: $' file2: db 13,10,'File 2: $'
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#8086_Assembly
8086 Assembly
with Ada.Command_line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO;   procedure Print_Commands is begin -- The number of command line arguments is retrieved from the function Argument_Count -- The actual arguments are retrieved from the function Argument -- The program name is retrieved from the function Command_Name Put(Command_Name & " "); for Arg in 1..Argument_Count loop Put(Argument(Arg) & " "); end loop; New_Line; end Print_Commands;
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#11l
11l
// Single line comment \\ Also single line comment (continuation of the comment in previous line)   \[ This is a multi line comment ]   \{ And this }   \( And this )   \‘ And this ’
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Fortran
Fortran
module compiler_type_kinds use, intrinsic :: iso_fortran_env, only: int32 use, intrinsic :: iso_fortran_env, only: int64   implicit none private   ! Synonyms. integer, parameter, public :: size_kind = int64 integer, parameter, public :: length_kind = size_kind integer, parameter, public :: nk = size_kind   ! Synonyms for character capable of storing a Unicode code point. integer, parameter, public :: unicode_char_kind = selected_char_kind ('ISO_10646') integer, parameter, public :: ck = unicode_char_kind   ! Synonyms for integers capable of storing a Unicode code point. integer, parameter, public :: unicode_ichar_kind = int32 integer, parameter, public :: ick = unicode_ichar_kind   ! Synonyms for integers in the virtual machine or the interpreter’s ! runtime. (The Rosetta Code task says integers in the virtual ! machine are 32-bit, but there is nothing in the task that prevents ! us using 64-bit integers in the compiler and interpreter.) integer, parameter, public :: runtime_int_kind = int64 integer, parameter, public :: rik = runtime_int_kind end module compiler_type_kinds   module helpers use, non_intrinsic :: compiler_type_kinds, only: nk, rik, ck   implicit none private   public :: new_storage_size public :: next_power_of_two   public :: isspace public :: quoted_string   public :: int32_to_vm_bytes public :: uint32_to_vm_bytes public :: int32_from_vm_bytes public :: uint32_from_vm_bytes   public :: bool2int   character(1, kind = ck), parameter, public :: horizontal_tab_char = char (9, kind = ck) character(1, kind = ck), parameter, public :: linefeed_char = char (10, kind = ck) character(1, kind = ck), parameter, public :: vertical_tab_char = char (11, kind = ck) character(1, kind = ck), parameter, public :: formfeed_char = char (12, kind = ck) character(1, kind = ck), parameter, public :: carriage_return_char = char (13, kind = ck) character(1, kind = ck), parameter, public :: space_char = ck_' '   ! The following is correct for Unix and its relatives. character(1, kind = ck), parameter, public :: newline_char = linefeed_char   character(1, kind = ck), parameter, public :: backslash_char = char (92, kind = ck)   contains   elemental function new_storage_size (length_needed) result (size) integer(kind = nk), intent(in) :: length_needed integer(kind = nk) :: size   ! Increase storage by orders of magnitude.   if (2_nk**32 < length_needed) then size = huge (1_nk) else size = next_power_of_two (length_needed) end if end function new_storage_size   elemental function next_power_of_two (x) result (y) integer(kind = nk), intent(in) :: x integer(kind = nk) :: y   ! ! It is assumed that no more than 64 bits are used. ! ! The branch-free algorithm is that of ! https://archive.is/nKxAc#RoundUpPowerOf2 ! ! Fill in bits until one less than the desired power of two is ! reached, and then add one. !   y = x - 1 y = ior (y, ishft (y, -1)) y = ior (y, ishft (y, -2)) y = ior (y, ishft (y, -4)) y = ior (y, ishft (y, -8)) y = ior (y, ishft (y, -16)) y = ior (y, ishft (y, -32)) y = y + 1 end function next_power_of_two   elemental function isspace (ch) result (bool) character(1, kind = ck), intent(in) :: ch logical :: bool   bool = (ch == horizontal_tab_char) .or. & & (ch == linefeed_char) .or. & & (ch == vertical_tab_char) .or. & & (ch == formfeed_char) .or. & & (ch == carriage_return_char) .or. & & (ch == space_char) end function isspace   function quoted_string (str) result (qstr) character(*, kind = ck), intent(in) :: str character(:, kind = ck), allocatable :: qstr   integer(kind = nk) :: n, i, j   ! Compute n = the size of qstr. n = 2_nk do i = 1_nk, len (str, kind = nk) select case (str(i:i)) case (newline_char, backslash_char) n = n + 2 case default n = n + 1 end select end do   allocate (character(n, kind = ck) :: qstr)   ! Quote the string. qstr(1:1) = ck_'"' j = 2_nk do i = 1_nk, len (str, kind = nk) select case (str(i:i)) case (newline_char) qstr(j:j) = backslash_char qstr((j + 1):(j + 1)) = ck_'n' j = j + 2 case (backslash_char) qstr(j:j) = backslash_char qstr((j + 1):(j + 1)) = backslash_char j = j + 2 case default qstr(j:j) = str(i:i) j = j + 1 end select end do if (j /= n) error stop ! Check code correctness. qstr(n:n) = ck_'"' end function quoted_string   subroutine int32_to_vm_bytes (n, bytes, i) integer(kind = rik), intent(in) :: n character(1), intent(inout) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   bytes(i) = achar (ibits (n, 0, 8)) bytes(i + 1) = achar (ibits (n, 8, 8)) bytes(i + 2) = achar (ibits (n, 16, 8)) bytes(i + 3) = achar (ibits (n, 24, 8)) end subroutine int32_to_vm_bytes   subroutine uint32_to_vm_bytes (n, bytes, i) integer(kind = rik), intent(in) :: n character(1), intent(inout) :: bytes(0:*) integer(kind = rik), intent(in) :: i   call int32_to_vm_bytes (n, bytes, i) end subroutine uint32_to_vm_bytes   subroutine int32_from_vm_bytes (n, bytes, i) integer(kind = rik), intent(out) :: n character(1), intent(in) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   call uint32_from_vm_bytes (n, bytes, i) if (ibits (n, 31, 1) == 1) then ! Extend the sign bit. n = ior (n, not ((2_rik ** 32) - 1)) end if end subroutine int32_from_vm_bytes   subroutine uint32_from_vm_bytes (n, bytes, i) integer(kind = rik), intent(out) :: n character(1), intent(in) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   integer(kind = rik) :: n0, n1, n2, n3   n0 = iachar (bytes(i), kind = rik) n1 = ishft (iachar (bytes(i + 1), kind = rik), 8) n2 = ishft (iachar (bytes(i + 2), kind = rik), 16) n3 = ishft (iachar (bytes(i + 3), kind = rik), 24) n = ior (n0, ior (n1, ior (n2, n3))) end subroutine uint32_from_vm_bytes   elemental function bool2int (bool) result (int) logical, intent(in) :: bool integer(kind = rik) :: int   if (bool) then int = 1_rik else int = 0_rik end if end function bool2int   end module helpers   module string_buffers use, intrinsic :: iso_fortran_env, only: error_unit use, intrinsic :: iso_fortran_env, only: int64 use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick use, non_intrinsic :: helpers   implicit none private   public :: strbuf_t public :: skip_whitespace public :: skip_non_whitespace public :: skip_whitespace_backwards public :: at_end_of_line   type :: strbuf_t integer(kind = nk), private :: len = 0 ! ! ‘chars’ is made public for efficient access to the individual ! characters. ! character(1, kind = ck), allocatable, public :: chars(:) contains procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage procedure, pass :: to_unicode_full_string => strbuf_t_to_unicode_full_string procedure, pass :: to_unicode_substring => strbuf_t_to_unicode_substring procedure, pass :: length => strbuf_t_length procedure, pass :: set => strbuf_t_set procedure, pass :: append => strbuf_t_append generic :: to_unicode => to_unicode_full_string generic :: to_unicode => to_unicode_substring generic :: assignment(=) => set end type strbuf_t   contains   function strbuf_t_to_unicode_full_string (strbuf) result (s) class(strbuf_t), intent(in) :: strbuf character(:, kind = ck), allocatable :: s   ! ! This does not actually ensure that the string is valid Unicode; ! any 31-bit ‘character’ is supported. !   integer(kind = nk) :: i   allocate (character(len = strbuf%len, kind = ck) :: s) do i = 1, strbuf%len s(i:i) = strbuf%chars(i) end do end function strbuf_t_to_unicode_full_string   function strbuf_t_to_unicode_substring (strbuf, i, j) result (s) ! ! ‘Extreme’ values of i and j are allowed, as shortcuts for ‘from ! the beginning’, ‘up to the end’, or ‘empty substring’. ! class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j character(:, kind = ck), allocatable :: s   ! ! This does not actually ensure that the string is valid Unicode; ! any 31-bit ‘character’ is supported. !   integer(kind = nk) :: i1, j1 integer(kind = nk) :: n integer(kind = nk) :: k   i1 = max (1_nk, i) j1 = min (strbuf%len, j) n = max (0_nk, (j1 - i1) + 1_nk)   allocate (character(n, kind = ck) :: s) do k = 1, n s(k:k) = strbuf%chars(i1 + (k - 1_nk)) end do end function strbuf_t_to_unicode_substring   elemental function strbuf_t_length (strbuf) result (n) class(strbuf_t), intent(in) :: strbuf integer(kind = nk) :: n   n = strbuf%len end function strbuf_t_length   subroutine strbuf_t_ensure_storage (strbuf, length_needed) class(strbuf_t), intent(inout) :: strbuf integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(strbuf_t) :: new_strbuf   len_needed = max (length_needed, 1_nk)   if (.not. allocated (strbuf%chars)) then ! Initialize a new strbuf%chars array. new_size = new_storage_size (len_needed) allocate (strbuf%chars(1:new_size)) else if (ubound (strbuf%chars, 1) < len_needed) then ! Allocate a new strbuf%chars array, larger than the current ! one, but containing the same characters. new_size = new_storage_size (len_needed) allocate (new_strbuf%chars(1:new_size)) new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len) call move_alloc (new_strbuf%chars, strbuf%chars) end if end subroutine strbuf_t_ensure_storage   subroutine strbuf_t_set (dst, src) class(strbuf_t), intent(inout) :: dst class(*), intent(in) :: src   integer(kind = nk) :: n integer(kind = nk) :: i   select type (src) type is (character(*, kind = ck)) n = len (src, kind = nk) call dst%ensure_storage(n) do i = 1, n dst%chars(i) = src(i:i) end do dst%len = n type is (character(*)) n = len (src, kind = nk) call dst%ensure_storage(n) do i = 1, n dst%chars(i) = src(i:i) end do dst%len = n class is (strbuf_t) n = src%len call dst%ensure_storage(n) dst%chars(1:n) = src%chars(1:n) dst%len = n class default error stop end select end subroutine strbuf_t_set   subroutine strbuf_t_append (dst, src) class(strbuf_t), intent(inout) :: dst class(*), intent(in) :: src   integer(kind = nk) :: n_dst, n_src, n integer(kind = nk) :: i   select type (src) type is (character(*, kind = ck)) n_dst = dst%len n_src = len (src, kind = nk) n = n_dst + n_src call dst%ensure_storage(n) do i = 1, n_src dst%chars(n_dst + i) = src(i:i) end do dst%len = n type is (character(*)) n_dst = dst%len n_src = len (src, kind = nk) n = n_dst + n_src call dst%ensure_storage(n) do i = 1, n_src dst%chars(n_dst + i) = src(i:i) end do dst%len = n class is (strbuf_t) n_dst = dst%len n_src = src%len n = n_dst + n_src call dst%ensure_storage(n) dst%chars((n_dst + 1):n) = src%chars(1:n_src) dst%len = n class default error stop end select end subroutine strbuf_t_append   function skip_whitespace (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (at_end_of_line (strbuf, j)) then done = .true. else if (.not. isspace (strbuf%chars(j))) then done = .true. else j = j + 1 end if end do end function skip_whitespace   function skip_non_whitespace (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (at_end_of_line (strbuf, j)) then done = .true. else if (isspace (strbuf%chars(j))) then done = .true. else j = j + 1 end if end do end function skip_non_whitespace   function skip_whitespace_backwards (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (j == -1) then done = .true. else if (.not. isspace (strbuf%chars(j))) then done = .true. else j = j - 1 end if end do end function skip_whitespace_backwards   function at_end_of_line (strbuf, i) result (bool) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i logical :: bool   bool = (strbuf%length() < i) end function at_end_of_line   end module string_buffers   module reading_one_line_from_a_stream use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick use, non_intrinsic :: string_buffers   implicit none private   ! get_line_from_stream: read an entire input line from a stream into ! a strbuf_t. public :: get_line_from_stream   character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)   ! The following is correct for Unix and its relatives. character(1, kind = ck), parameter :: newline_char = linefeed_char   contains   subroutine get_line_from_stream (unit_no, eof, no_newline, strbuf) integer, intent(in) :: unit_no logical, intent(out) :: eof ! End of file? logical, intent(out) :: no_newline ! There is a line but it has no ! newline? (Thus eof also must ! be .true.) class(strbuf_t), intent(inout) :: strbuf   character(1, kind = ck) :: ch   strbuf = '' call get_ch (unit_no, eof, ch) do while (.not. eof .and. ch /= newline_char) call strbuf%append (ch) call get_ch (unit_no, eof, ch) end do no_newline = eof .and. (strbuf%length() /= 0) end subroutine get_line_from_stream   subroutine get_ch (unit_no, eof, ch) ! ! Read a single code point from the stream. ! ! Currently this procedure simply inputs ‘ASCII’ bytes rather than ! Unicode code points. ! integer, intent(in) :: unit_no logical, intent(out) :: eof character(1, kind = ck), intent(out) :: ch   integer :: stat character(1) :: c = '*'   eof = .false.   if (unit_no == input_unit) then call get_input_unit_char (c, stat) else read (unit = unit_no, iostat = stat) c end if   if (stat < 0) then ch = ck_'*' eof = .true. else if (0 < stat) then write (error_unit, '("Input error with status code ", I0)') stat stop 1 else ch = char (ichar (c, kind = ick), kind = ck) end if end subroutine get_ch   !!! !!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely !!! will need to add also -fall-intrinsics or -U__GFORTRAN__ !!! !!! The first way, you get the FGETC intrinsic. The latter way, you !!! get the C interface code that uses getchar(3). !!! #ifdef __GFORTRAN__   subroutine get_input_unit_char (c, stat) ! ! The following works if you are using gfortran. ! ! (FGETC is considered a feature for backwards compatibility with ! g77. However, I know of no way to reconfigure input_unit as a ! Fortran 2003 stream, for use with ordinary ‘read’.) ! character, intent(inout) :: c integer, intent(out) :: stat   call fgetc (input_unit, c, stat) end subroutine get_input_unit_char   #else   subroutine get_input_unit_char (c, stat) ! ! An alternative implementation of get_input_unit_char. This ! actually reads input from the C standard input, which might not ! be the same as input_unit. ! use, intrinsic :: iso_c_binding, only: c_int character, intent(inout) :: c integer, intent(out) :: stat   interface ! ! Use getchar(3) to read characters from standard input. This ! assumes there is actually such a function available, and that ! getchar(3) does not exist solely as a macro. (One could write ! one’s own getchar() if necessary, of course.) ! function getchar () result (c) bind (c, name = 'getchar') use, intrinsic :: iso_c_binding, only: c_int integer(kind = c_int) :: c end function getchar end interface   integer(kind = c_int) :: i_char   i_char = getchar () ! ! The C standard requires that EOF have a negative value. If the ! value returned by getchar(3) is not EOF, then it will be ! representable as an unsigned char. Therefore, to check for end ! of file, one need only test whether i_char is negative. ! if (i_char < 0) then stat = -1 else stat = 0 c = char (i_char) end if end subroutine get_input_unit_char   #endif   end module reading_one_line_from_a_stream   module vm_reader use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds use, non_intrinsic :: helpers use, non_intrinsic :: string_buffers use, non_intrinsic :: reading_one_line_from_a_stream   implicit none private   public :: vm_code_t public :: vm_t public :: read_vm   ! ! Arbitrarily chosen opcodes. ! ! I think there should be a no-operation ‘nop’ opcode, to reserve ! space for later hand-patching. :) ! integer, parameter, public :: opcode_nop = 0 integer, parameter, public :: opcode_halt = 1 integer, parameter, public :: opcode_add = 2 integer, parameter, public :: opcode_sub = 3 integer, parameter, public :: opcode_mul = 4 integer, parameter, public :: opcode_div = 5 integer, parameter, public :: opcode_mod = 6 integer, parameter, public :: opcode_lt = 7 integer, parameter, public :: opcode_gt = 8 integer, parameter, public :: opcode_le = 9 integer, parameter, public :: opcode_ge = 10 integer, parameter, public :: opcode_eq = 11 integer, parameter, public :: opcode_ne = 12 integer, parameter, public :: opcode_and = 13 integer, parameter, public :: opcode_or = 14 integer, parameter, public :: opcode_neg = 15 integer, parameter, public :: opcode_not = 16 integer, parameter, public :: opcode_prtc = 17 integer, parameter, public :: opcode_prti = 18 integer, parameter, public :: opcode_prts = 19 integer, parameter, public :: opcode_fetch = 20 integer, parameter, public :: opcode_store = 21 integer, parameter, public :: opcode_push = 22 integer, parameter, public :: opcode_jmp = 23 integer, parameter, public :: opcode_jz = 24   character(8, kind = ck), parameter, public :: opcode_names(0:24) = & & (/ "nop ", & & "halt ", & & "add ", & & "sub ", & & "mul ", & & "div ", & & "mod ", & & "lt ", & & "gt ", & & "le ", & & "ge ", & & "eq ", & & "ne ", & & "and ", & & "or ", & & "neg ", & & "not ", & & "prtc ", & & "prti ", & & "prts ", & & "fetch ", & & "store ", & & "push ", & & "jmp ", & & "jz " /)   type :: vm_code_t integer(kind = rik), private :: len = 0_rik character(1), allocatable :: bytes(:) contains procedure, pass, private :: ensure_storage => vm_code_t_ensure_storage procedure, pass :: length => vm_code_t_length end type vm_code_t   type :: vm_t integer(kind = rik), allocatable :: string_boundaries(:) character(:, kind = ck), allocatable :: strings character(1), allocatable :: data(:) character(1), allocatable :: stack(:) type(vm_code_t) :: code integer(kind = rik) :: sp = 0_rik integer(kind = rik) :: pc = 0_rik end type vm_t   contains   subroutine vm_code_t_ensure_storage (code, length_needed) class(vm_code_t), intent(inout) :: code integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(vm_code_t) :: new_code   len_needed = max (length_needed, 1_nk)   if (.not. allocated (code%bytes)) then ! Initialize a new code%bytes array. new_size = new_storage_size (len_needed) allocate (code%bytes(0:(new_size - 1))) else if (ubound (code%bytes, 1) < len_needed - 1) then ! Allocate a new code%bytes array, larger than the current one, ! but containing the same bytes. new_size = new_storage_size (len_needed) allocate (new_code%bytes(0:(new_size - 1))) new_code%bytes(0:(code%len - 1)) = code%bytes(0:(code%len - 1)) call move_alloc (new_code%bytes, code%bytes) end if end subroutine vm_code_t_ensure_storage   elemental function vm_code_t_length (code) result (len) class(vm_code_t), intent(in) :: code integer(kind = rik) :: len   len = code%len end function vm_code_t_length   subroutine read_vm (inp, strbuf, vm) integer, intent(in) :: inp type(strbuf_t), intent(inout) :: strbuf type(vm_t), intent(out) :: vm   integer(kind = rik) :: data_size integer(kind = rik) :: number_of_strings   ! Read the header. call read_datasize_and_number_of_strings (inp, strbuf, data_size, number_of_strings)   ! Allocate storage for data_size 32-bit numbers. Initialize them ! to zero, for no better reason than that C initializes global ! variables to zero. allocate (vm%data(0_rik:(4_rik * (data_size - 1))), source = achar (0))   ! Allocate storage for indices/bounds of the strings to be loaded ! into the string storage space. allocate (vm%string_boundaries(0_rik:number_of_strings))   ! Fill the strings storage and the string boundaries array. call read_strings (inp, strbuf, number_of_strings, vm)   ! Read the program instructions. call read_code (inp, strbuf, vm)   ! Allocate a stack. Let us say that the stack size must be a ! multiple of 4, and is fixed at 65536 = 4**8 bytes. Pushing a ! 32-bit integer increases the stack pointer by 4, popping ! decreases it by 4. allocate (vm%stack(0_rik:(4_rik ** 8))) end subroutine read_vm   subroutine read_datasize_and_number_of_strings (inp, strbuf, data_size, number_of_strings) integer, intent(in) :: inp type(strbuf_t), intent(inout) :: strbuf integer(kind = rik), intent(out) :: data_size integer(kind = rik), intent(out) :: number_of_strings   logical :: eof logical :: no_newline integer(kind = nk) :: i, j character(:, kind = ck), allocatable :: data_size_str character(:, kind = ck), allocatable :: number_of_strings_str integer :: stat   call get_line_from_stream (inp, eof, no_newline, strbuf) if (eof) call bad_vm_assembly   i = skip_whitespace (strbuf, 1_nk) i = skip_datasize_keyword (strbuf, i) i = skip_whitespace (strbuf, i) i = skip_specific_character (strbuf, i, ck_':') i = skip_whitespace (strbuf, i) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly allocate (data_size_str, source = strbuf%to_unicode (i, j - 1))   i = skip_whitespace(strbuf, j) i = skip_strings_keyword (strbuf, i) i = skip_whitespace (strbuf, i) i = skip_specific_character (strbuf, i, ck_':') i = skip_whitespace (strbuf, i) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly allocate (number_of_strings_str, source = strbuf%to_unicode (i, j - 1))   read (data_size_str, *, iostat = stat) data_size if (stat /= 0) call bad_vm_assembly read (number_of_strings_str, *, iostat = stat) number_of_strings if (stat /= 0) call bad_vm_assembly end subroutine read_datasize_and_number_of_strings   subroutine read_strings (inp, strbuf, number_of_strings, vm) integer, intent(in) :: inp type(strbuf_t), intent(inout) :: strbuf integer(kind = rik), intent(in) :: number_of_strings type(vm_t), intent(inout) :: vm   type(strbuf_t) :: strings_temporary integer(kind = rik) :: i   vm%string_boundaries(0) = 0_rik do i = 0_rik, number_of_strings - 1 call read_one_string (inp, strbuf, strings_temporary) vm%string_boundaries(i + 1) = strings_temporary%length() end do allocate (vm%strings, source = strings_temporary%to_unicode()) end subroutine read_strings   subroutine read_one_string (inp, strbuf, strings_temporary) integer, intent(in) :: inp type(strbuf_t), intent(inout) :: strbuf type(strbuf_t), intent(inout) :: strings_temporary   logical :: eof logical :: no_newline integer(kind = nk) :: i logical :: done   call get_line_from_stream (inp, eof, no_newline, strbuf) if (eof) call bad_vm_assembly i = skip_whitespace (strbuf, 1_nk) i = skip_specific_character (strbuf, i, ck_'"') done = .false. do while (.not. done) if (i == strbuf%length() + 1) call bad_vm_assembly if (strbuf%chars(i) == ck_'"') then done = .true. else if (strbuf%chars(i) == backslash_char) then if (i == strbuf%length()) call bad_vm_assembly select case (strbuf%chars(i + 1)) case (ck_'n') call strings_temporary%append(newline_char) case (backslash_char) call strings_temporary%append(backslash_char) case default call bad_vm_assembly end select i = i + 2 else call strings_temporary%append(strbuf%chars(i)) i = i + 1 end if end do end subroutine read_one_string   subroutine read_code (inp, strbuf, vm) integer, intent(in) :: inp type(strbuf_t), intent(inout) :: strbuf type(vm_t), intent(inout) :: vm   logical :: eof logical :: no_newline   call get_line_from_stream (inp, eof, no_newline, strbuf) do while (.not. eof) call parse_instruction (strbuf, vm%code) call get_line_from_stream (inp, eof, no_newline, strbuf) end do end subroutine read_code   subroutine parse_instruction (strbuf, code) type(strbuf_t), intent(in) :: strbuf type(vm_code_t), intent(inout) :: code   integer(kind = nk) :: i, j integer :: stat   integer :: opcode integer(kind = rik) :: i_vm integer(kind = rik) :: arg   character(8, kind = ck) :: opcode_name_str character(:, kind = ck), allocatable :: i_vm_str character(:, kind = ck), allocatable :: arg_str   i = skip_whitespace (strbuf, 1_nk) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly allocate (i_vm_str, source = strbuf%to_unicode(i, j - 1)) read (i_vm_str, *, iostat = stat) i_vm if (stat /= 0) call bad_vm_assembly   i = skip_whitespace (strbuf, j) j = skip_non_whitespace (strbuf, i) opcode_name_str = ck_' ' opcode_name_str(1:(j - i)) = strbuf%to_unicode(i, j - 1) opcode = findloc (opcode_names, opcode_name_str, 1) - 1 if (opcode == -1) call bad_vm_assembly   select case (opcode)   case (opcode_push) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode) i = skip_whitespace (strbuf, j) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly allocate (arg_str, source = strbuf%to_unicode(i, j - 1)) read (arg_str, *, iostat = stat) arg if (stat /= 0) call bad_vm_assembly call int32_to_vm_bytes (arg, code%bytes, i_vm + 1) code%len = max (code%len, i_vm + 5)   case (opcode_fetch, opcode_store) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode) i = skip_whitespace (strbuf, j) i = skip_specific_character (strbuf, i, ck_'[') i = skip_whitespace (strbuf, i) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly if (strbuf%chars(j - 1) == ck_']') j = j - 1 allocate (arg_str, source = strbuf%to_unicode(i, j - 1)) read (arg_str, *, iostat = stat) arg if (stat /= 0) call bad_vm_assembly call uint32_to_vm_bytes (arg, code%bytes, i_vm + 1) code%len = max (code%len, i_vm + 5)   case (opcode_jmp, opcode_jz) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode) i = skip_whitespace (strbuf, j) i = skip_specific_character (strbuf, i, ck_'(') i = skip_whitespace (strbuf, i) j = skip_non_whitespace (strbuf, i) if (j == i) call bad_vm_assembly if (strbuf%chars(j - 1) == ck_')') j = j - 1 allocate (arg_str, source = strbuf%to_unicode(i, j - 1)) read (arg_str, *, iostat = stat) arg if (stat /= 0) call bad_vm_assembly call int32_to_vm_bytes (arg, code%bytes, i_vm + 1) code%len = max (code%len, i_vm + 5)   case default call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode) code%len = max (code%len, i_vm + 1) end select   end subroutine parse_instruction   function skip_datasize_keyword (strbuf, i) result (j) type(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   j = skip_specific_character (strbuf, i, ck_'D') j = skip_specific_character (strbuf, j, ck_'a') j = skip_specific_character (strbuf, j, ck_'t') j = skip_specific_character (strbuf, j, ck_'a') j = skip_specific_character (strbuf, j, ck_'s') j = skip_specific_character (strbuf, j, ck_'i') j = skip_specific_character (strbuf, j, ck_'z') j = skip_specific_character (strbuf, j, ck_'e') end function skip_datasize_keyword   function skip_strings_keyword (strbuf, i) result (j) type(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   j = skip_specific_character (strbuf, i, ck_'S') j = skip_specific_character (strbuf, j, ck_'t') j = skip_specific_character (strbuf, j, ck_'r') j = skip_specific_character (strbuf, j, ck_'i') j = skip_specific_character (strbuf, j, ck_'n') j = skip_specific_character (strbuf, j, ck_'g') j = skip_specific_character (strbuf, j, ck_'s') end function skip_strings_keyword   function skip_specific_character (strbuf, i, ch) result (j) type(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i character(1, kind = ck), intent(in) :: ch integer(kind = nk) :: j   if (strbuf%length() < i) call bad_vm_assembly if (strbuf%chars(i) /= ch) call bad_vm_assembly j = i + 1 end function skip_specific_character   subroutine bad_vm_assembly write (error_unit, '("The input is not a correct virtual machine program.")') stop 1 end subroutine bad_vm_assembly   end module vm_reader   module vm_runner use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds use, non_intrinsic :: helpers use, non_intrinsic :: vm_reader   implicit none private   public :: run_vm   contains   subroutine run_vm (outp, vm) integer, intent(in) :: outp type(vm_t), intent(inout) :: vm   logical :: done integer :: opcode   vm%sp = 0 vm%pc = 0 done = .false. do while (.not. done) if (vm%pc < 0 .or. vm%code%length() <= vm%pc) call pc_error opcode = iachar (vm%code%bytes(vm%pc)) vm%pc = vm%pc + 1 select case (opcode) case (opcode_nop) continue case (opcode_halt) done = .true. case (opcode_add) call alu_add (vm) case (opcode_sub) call alu_sub (vm) case (opcode_mul) call alu_mul (vm) case (opcode_div) call alu_div (vm) case (opcode_mod) call alu_mod (vm) case (opcode_lt) call alu_lt (vm) case (opcode_gt) call alu_gt (vm) case (opcode_le) call alu_le (vm) case (opcode_ge) call alu_ge (vm) case (opcode_eq) call alu_eq (vm) case (opcode_ne) call alu_ne (vm) case (opcode_and) call alu_and (vm) case (opcode_or) call alu_or (vm) case (opcode_neg) call alu_neg (vm) case (opcode_not) call alu_not (vm) case (opcode_prtc) call prtc (outp, vm) case (opcode_prti) call prti (outp, vm) case (opcode_prts) call prts (outp, vm) case (opcode_fetch) call fetch_int32 (vm) case (opcode_store) call store_int32 (vm) case (opcode_push) call push_int32 (vm) case (opcode_jmp) call jmp (vm) case (opcode_jz) call jz (vm) case default write (error_unit, '("VM opcode unrecognized: ", I0)') opcode stop 1 end select end do end subroutine run_vm   subroutine push_int32 (vm) type(vm_t), intent(inout) :: vm   ! ! Push the 32-bit integer data at pc to the stack, then increment ! pc by 4. !   if (ubound (vm%stack, 1) < vm%sp) then write (error_unit, '("VM stack overflow")') stop 1 end if if (vm%code%length() <= vm%pc + 4) call pc_error vm%stack(vm%sp:(vm%sp + 3)) = vm%code%bytes(vm%pc:(vm%pc + 3)) vm%sp = vm%sp + 4 vm%pc = vm%pc + 4 end subroutine push_int32   subroutine fetch_int32 (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: i integer(kind = rik) :: x   if (vm%code%length() <= vm%pc + 4) call pc_error call uint32_from_vm_bytes (i, vm%code%bytes, vm%pc) vm%pc = vm%pc + 4   if (ubound (vm%data, 1) < i * 4) then write (error_unit, '("VM data access error")') stop 1 end if call int32_from_vm_bytes (x, vm%data, i * 4)   if (ubound (vm%stack, 1) < vm%sp) then write (error_unit, '("VM stack overflow")') stop 1 end if call int32_to_vm_bytes (x, vm%stack, vm%sp) vm%sp = vm%sp + 4 end subroutine fetch_int32   subroutine store_int32 (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: i integer(kind = rik) :: x   if (vm%code%length() <= vm%pc + 4) call pc_error call uint32_from_vm_bytes (i, vm%code%bytes, vm%pc) vm%pc = vm%pc + 4   call ensure_there_is_enough_stack_data (vm, 4_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 4) vm%sp = vm%sp - 4   if (ubound (vm%data, 1) < i * 4) then write (error_unit, '("VM data access error")') stop 1 end if call int32_to_vm_bytes (x, vm%data, i * 4) end subroutine store_int32   subroutine jmp (vm) type(vm_t), intent(inout) :: vm   ! ! Add the 32-bit data at pc to pc itself. !   integer(kind = rik) :: x   if (vm%code%length() <= vm%pc + 4) call pc_error call int32_from_vm_bytes (x, vm%code%bytes, vm%pc) vm%pc = vm%pc + x end subroutine jmp   subroutine jz (vm) type(vm_t), intent(inout) :: vm   ! ! Conditionally add the 32-bit data at pc to pc itself. !   integer(kind = rik) :: x   call ensure_there_is_enough_stack_data (vm, 4_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 4) vm%sp = vm%sp - 4 if (x == 0) then if (vm%code%length() <= vm%pc + 4) call pc_error call int32_from_vm_bytes (x, vm%code%bytes, vm%pc) vm%pc = vm%pc + x else vm%pc = vm%pc + 4 end if end subroutine jz   subroutine alu_neg (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x   call ensure_there_is_enough_stack_data (vm, 4_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 4) x = -x call int32_to_vm_bytes (x, vm%stack, vm%sp - 4) end subroutine alu_neg   subroutine alu_not (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x   call ensure_there_is_enough_stack_data (vm, 4_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 4) x = bool2int (x == 0_rik) call int32_to_vm_bytes (x, vm%stack, vm%sp - 4) end subroutine alu_not   subroutine alu_add (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = x + y call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_add   subroutine alu_sub (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = x - y call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_sub   subroutine alu_mul (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = x * y call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_mul   subroutine alu_div (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = x / y ! This works like ‘/’ in C. call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_div   subroutine alu_mod (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = mod (x, y) ! This works like ‘%’ in C. call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_mod   subroutine alu_lt (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x < y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_lt   subroutine alu_gt (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x > y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_gt   subroutine alu_le (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x <= y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_le   subroutine alu_ge (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x >= y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_ge   subroutine alu_eq (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x == y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_eq   subroutine alu_ne (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x /= y) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_ne   subroutine alu_and (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x /= 0 .and. y /= 0) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_and   subroutine alu_or (vm) type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x, y, z   call ensure_there_is_enough_stack_data (vm, 8_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 8) call int32_from_vm_bytes (y, vm%stack, vm%sp - 4) z = bool2int (x /= 0 .or. y /= 0) call int32_to_vm_bytes (z, vm%stack, vm%sp - 8) vm%sp = vm%sp - 4 end subroutine alu_or   subroutine ensure_there_is_enough_stack_data (vm, n) type(vm_t), intent(in) :: vm integer(kind = rik), intent(in) :: n   if (vm%sp < n) then write (error_unit, '("VM stack underflow")') stop 1 end if end subroutine ensure_there_is_enough_stack_data   subroutine prtc (outp, vm) integer, intent(in) :: outp type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x   call ensure_there_is_enough_stack_data (vm, 4_rik) call uint32_from_vm_bytes (x, vm%stack, vm%sp - 4) write (outp, '(A1)', advance = 'no') char (x, kind = ck) vm%sp = vm%sp - 4 end subroutine prtc   subroutine prti (outp, vm) integer, intent(in) :: outp type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x   call ensure_there_is_enough_stack_data (vm, 4_rik) call int32_from_vm_bytes (x, vm%stack, vm%sp - 4) write (outp, '(I0)', advance = 'no') x vm%sp = vm%sp - 4 end subroutine prti   subroutine prts (outp, vm) integer, intent(in) :: outp type(vm_t), intent(inout) :: vm   integer(kind = rik) :: x integer(kind = rik) :: i, j   call ensure_there_is_enough_stack_data (vm, 4_rik) call uint32_from_vm_bytes (x, vm%stack, vm%sp - 4) if (ubound (vm%string_boundaries, 1) - 1 < x) then write (error_unit, '("VM string boundary error")') stop 1 end if i = vm%string_boundaries(x) j = vm%string_boundaries(x + 1) write (outp, '(A)', advance = 'no') vm%strings((i + 1):j) vm%sp = vm%sp - 4 end subroutine prts   subroutine pc_error write (error_unit, '("VM program counter error")') stop 1 end subroutine pc_error   end module vm_runner   program vm use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: output_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds use, non_intrinsic :: string_buffers use, non_intrinsic :: vm_reader use, non_intrinsic :: vm_runner   implicit none   integer, parameter :: inp_unit_no = 100 integer, parameter :: outp_unit_no = 101   integer :: arg_count character(200) :: arg integer :: inp integer :: outp   arg_count = command_argument_count () if (3 <= arg_count) then call print_usage else if (arg_count == 0) then inp = input_unit outp = output_unit else if (arg_count == 1) then call get_command_argument (1, arg) inp = open_for_input (trim (arg)) outp = output_unit else if (arg_count == 2) then call get_command_argument (1, arg) inp = open_for_input (trim (arg)) call get_command_argument (2, arg) outp = open_for_output (trim (arg)) end if   block type(strbuf_t) :: strbuf type(vm_t) :: vm   call read_vm (inp, strbuf, vm) call run_vm (outp, vm) end block end if   contains   function open_for_input (filename) result (unit_no) character(*), intent(in) :: filename integer :: unit_no   integer :: stat   open (unit = inp_unit_no, file = filename, status = 'old', & & action = 'read', access = 'stream', form = 'unformatted', & & iostat = stat) if (stat /= 0) then write (error_unit, '("Error: failed to open ", 1A, " for input")') filename stop 1 end if unit_no = inp_unit_no end function open_for_input   function open_for_output (filename) result (unit_no) character(*), intent(in) :: filename integer :: unit_no   integer :: stat   open (unit = outp_unit_no, file = filename, action = 'write', iostat = stat) if (stat /= 0) then write (error_unit, '("Error: failed to open ", 1A, " for output")') filename stop 1 end if unit_no = outp_unit_no end function open_for_output   subroutine print_usage character(200) :: progname   call get_command_argument (0, progname) write (output_unit, '("Usage: ", 1A, " [INPUT_FILE [OUTPUT_FILE]]")') & & trim (progname) end subroutine print_usage   end program vm
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#COBOL
COBOL
>>SOURCE FORMAT IS FREE identification division. *> this code is dedicated to the public domain *> (GnuCOBOL) 2.3-dev.0 program-id. generator. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 program-name pic x(32) value spaces global. 01 input-name pic x(32) value spaces global. 01 input-status pic xx global.   01 ast-record global. 03 ast-type pic x(14). 03 ast-value pic x(48). 03 filler redefines ast-value. 05 asl-left pic 999. 05 asl-right pic 999.   01 error-record pic x(64) value spaces global.   01 loadstack global. 03 l pic 99 value 0. 03 l-lim pic 99 value 64. 03 load-entry occurs 64. 05 l-node pic x(14). 05 l-left pic 999. 05 l-right pic 999. 05 l-link pic 999.   01 abstract-syntax-tree global. 03 t pic 999 value 0. 03 t1 pic 999. 03 t-lim pic 999 value 998. 03 filler occurs 998. 05 p1 pic 999. 05 p2 pic 999. 05 p3 pic 999. 05 n1 pic 999. 05 leaf. 07 leaf-type pic x(14). 07 leaf-value pic x(48). 05 node redefines leaf. 07 node-type pic x(14). 07 node-left pic 999. 07 node-right pic 999.   01 opcodes global. 03 opFETCH pic x value x'00'. 03 opSTORE pic x value x'01'. 03 opPUSH pic x value x'02'. 03 opADD pic x value x'03'. 03 opSUB pic x value x'04'. 03 opMUL pic x value x'05'. 03 opDIV pic x value x'06'. 03 opMOD pic x value x'07'. 03 opLT pic x value x'08'. 03 opGT pic x value x'09'. 03 opLE pic x value x'0A'. 03 opGE pic x value x'0B'. 03 opEQ pic x value x'0C'. 03 opNE pic x value x'0D'. 03 opAND pic x value x'0E'. 03 opOR pic x value x'0F'. 03 opNEG pic x value x'10'. 03 opNOT pic x value x'11'. 03 opJMP pic x value x'13'. 03 opJZ pic x value x'14'. 03 opPRTC pic x value x'15'. 03 opPRTS pic x value x'16'. 03 opPRTI pic x value x'17'. 03 opHALT pic x value x'18'.   01 variables global. 03 v pic 99. 03 v-max pic 99 value 0. 03 v-lim pic 99 value 16. 03 variable-entry occurs 16 pic x(48).   01 strings global. 03 s pic 99. 03 s-max pic 99 value 0. 03 s-lim pic 99 value 16. 03 string-entry occurs 16 pic x(48).   01 generated-code global. 03 c pic 999 value 1. 03 c1 pic 999. 03 c-lim pic 999 value 512. 03 kode pic x(512).   procedure division chaining program-name. start-generator. call 'loadast' if program-name <> spaces call 'readinput' *> close input-file end-if >>d perform print-ast call 'codegen' using t call 'emitbyte' using opHALT >>d call 'showhex' using kode c call 'listcode' stop run . print-ast. call 'printast' using t display 'ast:' upon syserr display 't=' t perform varying t1 from 1 by 1 until t1 > t if leaf-type(t1) = 'Identifier' or 'Integer' or 'String' display t1 space trim(leaf-type(t1)) space trim(leaf-value(t1)) upon syserr else display t1 space node-left(t1) space node-right(t1) space trim(node-type(t1)) upon syserr end-if end-perform . identification division. program-id. codegen common recursive. data division. working-storage section. 01 r pic ---9. linkage section. 01 n pic 999. procedure division using n. start-codegen. if n = 0 exit program end-if >>d display 'at 'c ' node=' space n space node-type(n) upon syserr evaluate node-type(n) when 'Identifier' call 'emitbyte' using opFetch call 'variableoffset' using leaf-value(n) call 'emitword' using v '0' when 'Integer' call 'emitbyte' using opPUSH call 'emitword' using leaf-value(n) '0' when 'String' call 'emitbyte' using opPUSH call 'stringoffset' using leaf-value(n) call 'emitword' using s '0' when 'Assign' call 'codegen' using node-right(n) call 'emitbyte' using opSTORE move node-left(n) to n1(n) call 'variableoffset' using leaf-value(n1(n)) call 'emitword' using v '0' when 'If' call 'codegen' using node-left(n) *> conditional expr call 'emitbyte' using opJZ *> jump to false path or exit move c to p1(n) call 'emitword' using '0' '0' move node-right(n) to n1(n) *> true path call 'codegen' using node-left(n1(n)) if node-right(n1(n)) <> 0 *> there is a false path call 'emitbyte' using opJMP *> jump past false path move c to p2(n) call 'emitword' using '0' '0' compute r = c - p1(n) *> fill in jump to false path call 'emitword' using r p1(n) call 'codegen' using node-right(n1(n)) *> false path compute r = c - p2(n) *> fill in jump to exit call 'emitword' using r p2(n) else compute r = c - p1(n) call 'emitword' using r p1(n) *> fill in jump to exit end-if when 'While' move c to p3(n) *> save address of while start call 'codegen' using node-left(n) *> conditional expr call 'emitbyte' using opJZ *> jump to exit move c to p2(n) call 'emitword' using '0' '0' call 'codegen' using node-right(n) *> while body call 'emitbyte' using opJMP *> jump to while start compute r = p3(n) - c call 'emitword' using r '0' compute r = c - p2(n) *> fill in jump to exit call 'emitword' using r p2(n) when 'Sequence' call 'codegen' using node-left(n) call 'codegen' using node-right(n) when 'Prtc' call 'codegen' using node-left(n) call 'emitbyte' using opPRTC when 'Prti' call 'codegen' using node-left(n) call 'emitbyte' using opPRTI when 'Prts' call 'codegen' using node-left(n) call 'emitbyte' using opPRTS when 'Less' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opLT when 'Greater' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opGT when 'LessEqual' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opLE when 'GreaterEqual' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opGE when 'Equal' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opEQ when 'NotEqual' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opNE when 'And' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opAND when 'Or' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opOR when 'Subtract' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opSUB when 'Add' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opADD when 'Divide' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opDIV when 'Multiply' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opMUL when 'Mod' call 'codegen' using node-left(n) call 'codegen' using node-right(n) call 'emitbyte' using opMOD when 'Negate' call 'codegen' using node-left(n) call 'emitbyte' using opNEG when 'Not' call 'codegen' using node-left(n) call 'emitbyte' using opNOT when other string 'in generator unknown node type: ' node-type(n) into error-record call 'reporterror' end-evaluate . end program codegen.   identification division. program-id. variableoffset common. data division. linkage section. 01 variable-value pic x(48). procedure division using variable-value. start-variableoffset. perform varying v from 1 by 1 until v > v-max or variable-entry(v) = variable-value continue end-perform if v > v-lim string 'in generator variable offset v exceeds ' v-lim into error-record call 'reporterror' end-if if v > v-max move v to v-max move variable-value to variable-entry(v) end-if . end program variableoffset.   identification division. program-id. stringoffset common. data division. linkage section. 01 string-value pic x(48). procedure division using string-value. start-stringoffset. perform varying s from 1 by 1 until s > s-max or string-entry(s) = string-value continue end-perform if s > s-lim string ' generator stringoffset s exceeds ' s-lim into error-record call 'reporterror' end-if if s > s-max move s to s-max move string-value to string-entry(s) end-if subtract 1 from s *> convert index to offset . end program stringoffset.   identification division. program-id. emitbyte common. data division. linkage section. 01 opcode pic x. procedure division using opcode. start-emitbyte. if c >= c-lim string 'in generator emitbyte c exceeds ' c-lim into error-record call 'reporterror' end-if move opcode to kode(c:1) add 1 to c . end program emitbyte.   identification division. program-id. emitword common. data division. working-storage section. 01 word-x. 03 word usage binary-int. 01 loc pic 999. linkage section. 01 word-value any length. 01 loc-value any length. procedure division using word-value loc-value. start-emitword. if c + length(word) > c-lim string 'in generator emitword exceeds ' c-lim into error-record call 'reporterror' end-if move numval(word-value) to word move numval(loc-value) to loc if loc = 0 move word-x to kode(c:length(word)) add length(word) to c else move word-x to kode(loc:length(word)) end-if . end program emitword.   identification division. program-id. listcode common. data division. working-storage section. 01 word-x. 03 word usage binary-int. 01 address-display pic ---9. 01 address-absolute pic zzz9. 01 data-display pic -(9)9. 01 v-display pic z9. 01 s-display pic z9. 01 c-display pic zzz9. procedure division. start-listcode. move v-max to v-display move s-max to s-display display 'Datasize: ' trim(v-display) space 'Strings: ' trim(s-display)   perform varying s from 1 by 1 until s > s-max display string-entry(s) end-perform   move 1 to c1 perform until c1 >= c compute c-display = c1 - 1 display c-display space with no advancing evaluate kode(c1:1) when opFETCH add 1 to c1 move kode(c1:4) to word-x compute address-display = word - 1 display 'fetch [' trim(address-display) ']' add 3 to c1 when opSTORE add 1 to c1 move kode(c1:4) to word-x compute address-display = word - 1 display 'store [' trim(address-display) ']' add 3 to c1 when opPUSH add 1 to c1 move kode(c1:4) to word-x move word to data-display display 'push ' trim(data-display) add 3 to c1 when opADD display 'add' when opSUB display 'sub' when opMUL display 'mul' when opDIV display 'div' when opMOD display 'mod' when opLT display 'lt' when opGT display 'gt' when opLE display 'le' when opGE display 'ge' when opEQ display 'eq' when opNE display 'ne' when opAND display 'and' when opOR display 'or' when opNEG display 'neg' when opNOT display 'not' when opJMP move kode(c1 + 1:length(word)) to word-x move word to address-display compute address-absolute = c1 + word display 'jmp (' trim(address-display) ') ' trim(address-absolute) add length(word) to c1 when opJZ move kode(c1 + 1:length(word)) to word-x move word to address-display compute address-absolute = c1 + word display 'jz (' trim(address-display) ') ' trim(address-absolute) add length(word) to c1 when opPRTC display 'prtc' when opPRTI display 'prti' when opPRTS display 'prts' when opHALT display 'halt' when other string 'in generator unknown opcode ' kode(c1:1) into error-record call 'reporterror' end-evaluate add 1 to c1 end-perform . end program listcode.   identification division. program-id. loadast common recursive. procedure division. start-loadast. if l >= l-lim string 'in generator loadast l exceeds ' l-lim into error-record call 'reporterror' end-if add 1 to l call 'readinput' evaluate true when ast-record = ';' when input-status = '10' move 0 to return-code when ast-type = 'Identifier' when ast-type = 'Integer' when ast-type = 'String' call 'makeleaf' using ast-type ast-value move t to return-code when ast-type = 'Sequence' move ast-type to l-node(l) call 'loadast' move return-code to l-left(l) call 'loadast' move t to l-right(l) call 'makenode' using l-node(l) l-left(l) l-right(l) move t to return-code when other move ast-type to l-node(l) call 'loadast' move return-code to l-left(l) call 'loadast' move return-code to l-right(l) call 'makenode' using l-node(l) l-left(l) l-right(l) move t to return-code end-evaluate subtract 1 from l . end program loadast.   identification division. program-id. printast common recursive. data division. linkage section. 01 n pic 999. procedure division using n. start-printast. if n = 0 display ';' upon syserr exit program end-if display leaf-type(n) upon syserr evaluate leaf-type(n) when 'Identifier' when 'Integer' when 'String' display leaf-type(n) space trim(leaf-value(n)) upon syserr when other display node-type(n) upon syserr call 'printast' using node-left(n) call 'printast' using node-right(n) end-evaluate . end program printast.   identification division. program-id. makenode common. data division. linkage section. 01 parm-type any length. 01 parm-l-left pic 999. 01 parm-l-right pic 999. procedure division using parm-type parm-l-left parm-l-right. start-makenode. if t >= t-lim string 'in generator makenode t exceeds ' t-lim into error-record call 'reporterror' end-if add 1 to t move parm-type to node-type(t) move parm-l-left to node-left(t) move parm-l-right to node-right(t) . end program makenode.   identification division. program-id. makeleaf common. data division. linkage section. 01 parm-type any length. 01 parm-value pic x(48). procedure division using parm-type parm-value. start-makeleaf. add 1 to t if t >= t-lim string 'in generator makeleaf t exceeds ' t-lim into error-record call 'reporterror' end-if move parm-type to leaf-type(t) move parm-value to leaf-value(t) . end program makeleaf.   identification division. program-id. readinput common. environment division. input-output section. file-control. select input-file assign using input-name status is input-status organization is line sequential. data division. file section. fd input-file. 01 input-record pic x(64). procedure division. start-readinput. if program-name = spaces move '00' to input-status accept ast-record on exception move '10' to input-status end-accept exit program end-if if input-name = spaces string program-name delimited by space '.ast' into input-name open input input-file if input-status = '35' string 'in generator ' trim(input-name) ' not found' into error-record call 'reporterror' end-if end-if read input-file into ast-record evaluate input-status when '00' continue when '10' close input-file when other string 'in generator ' trim(input-name) ' unexpected input-status: ' input-status into error-record call 'reporterror' end-evaluate . end program readinput.   program-id. reporterror common. procedure division. start-reporterror. report-error. display error-record upon syserr stop run with error status -1 . end program reporterror.   identification division. program-id. showhex common.   data division. working-storage section. 01 hex. 03 filler pic x(32) value '000102030405060708090A0B0C0D0E0F'. 03 filler pic x(32) value '101112131415161718191A1B1C1D1E1F'. 03 filler pic x(32) value '202122232425262728292A2B2C2D2E2F'. 03 filler pic x(32) value '303132333435363738393A3B3C3D3E3F'. 03 filler pic x(32) value '404142434445464748494A4B4C4D4E4F'. 03 filler pic x(32) value '505152535455565758595A5B5C5D5E5F'. 03 filler pic x(32) value '606162636465666768696A6B6C6D6E6F'. 03 filler pic x(32) value '707172737475767778797A7B7C7D7E7F'. 03 filler pic x(32) value '808182838485868788898A8B8C8D8E8F'. 03 filler pic x(32) value '909192939495969798999A9B9C9D9E9F'. 03 filler pic x(32) value 'A0A1A2A3A4A5A6A7A8A9AAABACADAEAF'. 03 filler pic x(32) value 'B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF'. 03 filler pic x(32) value 'C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF'. 03 filler pic x(32) value 'D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF'. 03 filler pic x(32) value 'E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF'. 03 filler pic x(32) value 'F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF'.   01 cdx pic 9999. 01 bdx pic 999. 01 byte-count pic 9. 01 bytes-per-word pic 9 value 4. 01 word-count pic 9. 01 words-per-line pic 9 value 8.   linkage section. 01 data-field any length. 01 length-data-field pic 999.   procedure division using by reference data-field by reference length-data-field. start-showhex. move 1 to byte-count move 1 to word-count perform varying cdx from 1 by 1 until cdx > length-data-field compute bdx = 2 * ord(data-field(cdx:1)) - 1 end-compute display hex(bdx:2) with no advancing upon syserr add 1 to byte-count end-add if byte-count > bytes-per-word display ' ' with no advancing upon syserr move 1 to byte-count add 1 to word-count end-add end-if if word-count > words-per-line display ' ' upon syserr move 1 to word-count end-if end-perform if word-count <> 1 or byte-count <> 1 display ' ' upon syserr end-if display ' ' upon syserr goback . end program showhex. end program generator.
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#Go
Go
package main   import ( "log" "math/rand" "testing" "time"   "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" )   // Step 1, sort routines. // These functions are copied without changes from the RC tasks Bubble Sort, // Insertion sort, and Quicksort.   func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }   func insertionsort(a []int) { for i := 1; i < len(a); i++ { value := a[i] j := i - 1 for j >= 0 && a[j] > value { a[j+1] = a[j] j = j - 1 } a[j+1] = value } }   func quicksort(a []int) { var pex func(int, int) pex = func(lower, upper int) { for { switch upper - lower { case -1, 0: return case 1: if a[upper] < a[lower] { a[upper], a[lower] = a[lower], a[upper] } return } bx := (upper + lower) / 2 b := a[bx] lp := lower up := upper outer: for { for lp < upper && !(b < a[lp]) { lp++ } for { if lp > up { break outer } if a[up] < b { break } up-- } a[lp], a[up] = a[up], a[lp] lp++ up-- } if bx < lp { if bx < lp-1 { a[bx], a[lp-1] = a[lp-1], b } up = lp - 2 } else { if bx > lp { a[bx], a[lp] = a[lp], b } up = lp - 1 lp++ } if up-lower < upper-lp { pex(lower, up) lower = lp } else { pex(lp, upper) upper = up } } } pex(0, len(a)-1) }   // Step 2.0 sequence routines. 2.0 is the easy part. 2.5, timings, follows.   func ones(n int) []int { s := make([]int, n) for i := range s { s[i] = 1 } return s }   func ascending(n int) []int { s := make([]int, n) v := 1 for i := 0; i < n; { if rand.Intn(3) == 0 { s[i] = v i++ } v++ } return s }   func shuffled(n int) []int { return rand.Perm(n) }   // Steps 2.5 write timings, and 3 plot timings are coded together. // If write means format and output human readable numbers, step 2.5 // is satisfied with the log output as the program runs. The timings // are plotted immediately however for step 3, not read and parsed from // any formated output. const ( nPts = 7 // number of points per test inc = 1000 // data set size increment per point )   var ( p *plot.Plot sortName = []string{"Bubble sort", "Insertion sort", "Quicksort"} sortFunc = []func([]int){bubblesort, insertionsort, quicksort} dataName = []string{"Ones", "Ascending", "Shuffled"} dataFunc = []func(int) []int{ones, ascending, shuffled} )   func main() { rand.Seed(time.Now().Unix()) var err error p, err = plot.New() if err != nil { log.Fatal(err) } p.X.Label.Text = "Data size" p.Y.Label.Text = "microseconds" p.Y.Scale = plot.LogScale{} p.Y.Tick.Marker = plot.LogTicks{} p.Y.Min = .5 // hard coded to make enough room for legend   for dx, name := range dataName { s, err := plotter.NewScatter(plotter.XYs{}) if err != nil { log.Fatal(err) } s.Shape = plotutil.DefaultGlyphShapes[dx] p.Legend.Add(name, s) } for sx, name := range sortName { l, err := plotter.NewLine(plotter.XYs{}) if err != nil { log.Fatal(err) } l.Color = plotutil.DarkColors[sx] p.Legend.Add(name, l) } for sx := range sortFunc { bench(sx, 0, 1) // for ones, a single timing is sufficient. bench(sx, 1, 5) // ascending and shuffled have some randomness though, bench(sx, 2, 5) // so average timings on 5 different random sets. }   if err := p.Save(5*vg.Inch, 5*vg.Inch, "comp.png"); err != nil { log.Fatal(err) } }   func bench(sx, dx, rep int) { log.Println("bench", sortName[sx], dataName[dx], "x", rep) pts := make(plotter.XYs, nPts) sf := sortFunc[sx] for i := range pts { x := (i + 1) * inc // to avoid timing sequence creation, create sequence before timing // then just copy the data inside the timing loop. copy time should // be the same regardless of sequence data. s0 := dataFunc[dx](x) // reference sequence s := make([]int, x) // working copy var tSort int64 for j := 0; j < rep; j++ { tSort += testing.Benchmark(func(b *testing.B) { for i := 0; i < b.N; i++ { copy(s, s0) sf(s) } }).NsPerOp() } tSort /= int64(rep) log.Println(x, "items", tSort, "ns") // step 2.5, write timings pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001} } pl, ps, err := plotter.NewLinePoints(pts) // step 3, plot timings if err != nil { log.Fatal(err) } pl.Color = plotutil.DarkColors[sx] ps.Color = plotutil.DarkColors[sx] ps.Shape = plotutil.DefaultGlyphShapes[dx] p.Add(pl, ps) }
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) The interpreter algorithm is relatively simple interp(x) if x == NULL return NULL elif x.node_type == Integer return x.value converted to an integer elif x.node_type == Ident return the current value of variable x.value elif x.node_type == String return x.value elif x.node_type == Assign globals[x.left.value] = interp(x.right) return NULL elif x.node_type is a binary operator return interp(x.left) operator interp(x.right) elif x.node_type is a unary operator, return return operator interp(x.left) elif x.node_type == If if (interp(x.left)) then interp(x.right.left) else interp(x.right.right) return NULL elif x.node_type == While while (interp(x.left)) do interp(x.right) return NULL elif x.node_type == Prtc print interp(x.left) as a character, no newline return NULL elif x.node_type == Prti print interp(x.left) as an integer, no newline return NULL elif x.node_type == Prts print interp(x.left) as a string, respecting newlines ("\n") return NULL elif x.node_type == Sequence interp(x.left) interp(x.right) return NULL else error("unknown node type") Notes: Because of the simple nature of our tiny language, Semantic analysis is not needed. Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0. This means, for instance, that 3 / 2 should result in 1. For division when one of the operands is negative, the result should be truncated towards 0. This means, for instance, that 3 / -2 should result in -1. Test program prime.t lex <prime.t | parse | interp /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 101 is prime Total primes found: 26 Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task Virtual Machine Interpreter task
#Python
Python
from __future__ import print_function import sys, shlex, operator   nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \ nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \ nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)   all_syms = { "Identifier"  : nd_Ident, "String"  : nd_String, "Integer"  : nd_Integer, "Sequence"  : nd_Sequence, "If"  : nd_If, "Prtc"  : nd_Prtc, "Prts"  : nd_Prts, "Prti"  : nd_Prti, "While"  : nd_While, "Assign"  : nd_Assign, "Negate"  : nd_Negate, "Not"  : nd_Not, "Multiply"  : nd_Mul, "Divide"  : nd_Div, "Mod"  : nd_Mod, "Add"  : nd_Add, "Subtract"  : nd_Sub, "Less"  : nd_Lss, "LessEqual"  : nd_Leq, "Greater"  : nd_Gtr, "GreaterEqual": nd_Geq, "Equal"  : nd_Eql, "NotEqual"  : nd_Neq, "And"  : nd_And, "Or"  : nd_Or}   input_file = None globals = {}   #*** show error and exit def error(msg): print("%s" % (msg)) exit(1)   class Node: def __init__(self, node_type, left = None, right = None, value = None): self.node_type = node_type self.left = left self.right = right self.value = value   #*** def make_node(oper, left, right = None): return Node(oper, left, right)   #*** def make_leaf(oper, n): return Node(oper, value = n)   #*** def fetch_var(var_name): n = globals.get(var_name, None) if n == None: globals[var_name] = n = 0 return n   #*** def interp(x): global globals   if x == None: return None elif x.node_type == nd_Integer: return int(x.value) elif x.node_type == nd_Ident: return fetch_var(x.value) elif x.node_type == nd_String: return x.value   elif x.node_type == nd_Assign: globals[x.left.value] = interp(x.right) return None elif x.node_type == nd_Add: return interp(x.left) + interp(x.right) elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right) elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right) # use C like division semantics # another way: abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0) elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right)) elif x.node_type == nd_Mod: return int(float(interp(x.left)) % interp(x.right)) elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right) elif x.node_type == nd_Gtr: return interp(x.left) > interp(x.right) elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right) elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right) elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right) elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right) elif x.node_type == nd_And: return interp(x.left) and interp(x.right) elif x.node_type == nd_Or: return interp(x.left) or interp(x.right) elif x.node_type == nd_Negate: return -interp(x.left) elif x.node_type == nd_Not: return not interp(x.left)   elif x.node_type == nd_If: if (interp(x.left)): interp(x.right.left) else: interp(x.right.right) return None   elif x.node_type == nd_While: while (interp(x.left)): interp(x.right) return None   elif x.node_type == nd_Prtc: print("%c" % (interp(x.left)), end='') return None   elif x.node_type == nd_Prti: print("%d" % (interp(x.left)), end='') return None   elif x.node_type == nd_Prts: print(interp(x.left), end='') return None   elif x.node_type == nd_Sequence: interp(x.left) interp(x.right) return None else: error("error in code generator - found %d, expecting operator" % (x.node_type))   def str_trans(srce): dest = "" i = 0 srce = srce[1:-1] while i < len(srce): if srce[i] == '\\' and i + 1 < len(srce): if srce[i + 1] == 'n': dest += '\n' i += 2 elif srce[i + 1] == '\\': dest += '\\' i += 2 else: dest += srce[i] i += 1   return dest   def load_ast(): line = input_file.readline() line_list = shlex.split(line, False, False)   text = line_list[0]   value = None if len(line_list) > 1: value = line_list[1] if value.isdigit(): value = int(value)   if text == ";": return None node_type = all_syms[text] if value != None: if node_type == nd_String: value = str_trans(value)   return make_leaf(node_type, value) left = load_ast() right = load_ast() return make_node(node_type, left, right)   #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1])   n = load_ast() interp(n)
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#CFEngine
CFEngine
  bundle agent __main__ { vars: "strings" slist => { "abcd", "123456789", "abcdef", "1234567" };   "sorted[$(with)]" string => "$(strings)", with => string_length( "$(strings)" );   "sort_idx" slist => reverse( sort( getindices( "sorted" ), lex ) );   reports: "'$(sorted[$(sort_idx)])' is $(sort_idx) characters in length."; }  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BASIC
BASIC
*** (1) TWO STRINGS *** LONGER STRING (13) SHORT STRING (12) *** (2) MORE THAN 2 STRINGS*** SHE DOESN'T STUDY GERMAN ON MONDAY (34) EVERY CHILD LIKES AN ICE CREAM (30) THE COURSE STARTS NEXT SUNDAY (29) DOES SHE LIVE IN PARIS? (23) SHE SWIMS EVERY MORNING (23) THE EARTH IS SPHERICAL (22) WE SEE THEM EVERY WEEK (22) HE DOESN'T TEACH MATH (21) CATS HATE WATER (15) I LIKE TEA (10)
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Java
Java
  import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap;   class Parser { private List<Token> source; private Token token; private int position;   static class Node { public NodeType nt; public Node left, right; public String value;   Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } }   static class Token { public TokenType tokentype; public String value; public int line; public int pos;   Token(TokenType token, String value, int line, int pos) { this.tokentype = token; this.value = value; this.line = line; this.pos = pos; } @Override public String toString() { return String.format("%5d  %5d %-15s %s", this.line, this.pos, this.tokentype, this.value); } }   static enum TokenType { End_of_input(false, false, false, -1, NodeType.nd_None), Op_multiply(false, true, false, 13, NodeType.nd_Mul), Op_divide(false, true, false, 13, NodeType.nd_Div), Op_mod(false, true, false, 13, NodeType.nd_Mod), Op_add(false, true, false, 12, NodeType.nd_Add), Op_subtract(false, true, false, 12, NodeType.nd_Sub), Op_negate(false, false, true, 14, NodeType.nd_Negate), Op_not(false, false, true, 14, NodeType.nd_Not), Op_less(false, true, false, 10, NodeType.nd_Lss), Op_lessequal(false, true, false, 10, NodeType.nd_Leq), Op_greater(false, true, false, 10, NodeType.nd_Gtr), Op_greaterequal(false, true, false, 10, NodeType.nd_Geq), Op_equal(false, true, true, 9, NodeType.nd_Eql), Op_notequal(false, true, false, 9, NodeType.nd_Neq), Op_assign(false, false, false, -1, NodeType.nd_Assign), Op_and(false, true, false, 5, NodeType.nd_And), Op_or(false, true, false, 4, NodeType.nd_Or), Keyword_if(false, false, false, -1, NodeType.nd_If), Keyword_else(false, false, false, -1, NodeType.nd_None), Keyword_while(false, false, false, -1, NodeType.nd_While), Keyword_print(false, false, false, -1, NodeType.nd_None), Keyword_putc(false, false, false, -1, NodeType.nd_None), LeftParen(false, false, false, -1, NodeType.nd_None), RightParen(false, false, false, -1, NodeType.nd_None), LeftBrace(false, false, false, -1, NodeType.nd_None), RightBrace(false, false, false, -1, NodeType.nd_None), Semicolon(false, false, false, -1, NodeType.nd_None), Comma(false, false, false, -1, NodeType.nd_None), Identifier(false, false, false, -1, NodeType.nd_Ident), Integer(false, false, false, -1, NodeType.nd_Integer), String(false, false, false, -1, NodeType.nd_String);   private final int precedence; private final boolean right_assoc; private final boolean is_binary; private final boolean is_unary; private final NodeType node_type;   TokenType(boolean right_assoc, boolean is_binary, boolean is_unary, int precedence, NodeType node) { this.right_assoc = right_assoc; this.is_binary = is_binary; this.is_unary = is_unary; this.precedence = precedence; this.node_type = node; } boolean isRightAssoc() { return this.right_assoc; } boolean isBinary() { return this.is_binary; } boolean isUnary() { return this.is_unary; } int getPrecedence() { return this.precedence; } NodeType getNodeType() { return this.node_type; } } static enum NodeType { nd_None(""), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");   private final String name;   NodeType(String name) { this.name = name; }   @Override public String toString() { return this.name; } } static void error(int line, int pos, String msg) { if (line > 0 && pos > 0) { System.out.printf("%s in line %d, pos %d\n", msg, line, pos); } else { System.out.println(msg); } System.exit(1); } Parser(List<Token> source) { this.source = source; this.token = null; this.position = 0; } Token getNextToken() { this.token = this.source.get(this.position++); return this.token; } Node expr(int p) { Node result = null, node; TokenType op; int q;   if (this.token.tokentype == TokenType.LeftParen) { result = paren_expr(); } else if (this.token.tokentype == TokenType.Op_add || this.token.tokentype == TokenType.Op_subtract) { op = (this.token.tokentype == TokenType.Op_subtract) ? TokenType.Op_negate : TokenType.Op_add; getNextToken(); node = expr(TokenType.Op_negate.getPrecedence()); result = (op == TokenType.Op_negate) ? Node.make_node(NodeType.nd_Negate, node) : node; } else if (this.token.tokentype == TokenType.Op_not) { getNextToken(); result = Node.make_node(NodeType.nd_Not, expr(TokenType.Op_not.getPrecedence())); } else if (this.token.tokentype == TokenType.Identifier) { result = Node.make_leaf(NodeType.nd_Ident, this.token.value); getNextToken(); } else if (this.token.tokentype == TokenType.Integer) { result = Node.make_leaf(NodeType.nd_Integer, this.token.value); getNextToken(); } else { error(this.token.line, this.token.pos, "Expecting a primary, found: " + this.token.tokentype); }   while (this.token.tokentype.isBinary() && this.token.tokentype.getPrecedence() >= p) { op = this.token.tokentype; getNextToken(); q = op.getPrecedence(); if (!op.isRightAssoc()) { q++; } node = expr(q); result = Node.make_node(op.getNodeType(), result, node); } return result; } Node paren_expr() { expect("paren_expr", TokenType.LeftParen); Node node = expr(0); expect("paren_expr", TokenType.RightParen); return node; } void expect(String msg, TokenType s) { if (this.token.tokentype == s) { getNextToken(); return; } error(this.token.line, this.token.pos, msg + ": Expecting '" + s + "', found: '" + this.token.tokentype + "'"); } Node stmt() { Node s, s2, t = null, e, v; if (this.token.tokentype == TokenType.Keyword_if) { getNextToken(); e = paren_expr(); s = stmt(); s2 = null; if (this.token.tokentype == TokenType.Keyword_else) { getNextToken(); s2 = stmt(); } t = Node.make_node(NodeType.nd_If, e, Node.make_node(NodeType.nd_If, s, s2)); } else if (this.token.tokentype == TokenType.Keyword_putc) { getNextToken(); e = paren_expr(); t = Node.make_node(NodeType.nd_Prtc, e); expect("Putc", TokenType.Semicolon); } else if (this.token.tokentype == TokenType.Keyword_print) { getNextToken(); expect("Print", TokenType.LeftParen); while (true) { if (this.token.tokentype == TokenType.String) { e = Node.make_node(NodeType.nd_Prts, Node.make_leaf(NodeType.nd_String, this.token.value)); getNextToken(); } else { e = Node.make_node(NodeType.nd_Prti, expr(0), null); } t = Node.make_node(NodeType.nd_Sequence, t, e); if (this.token.tokentype != TokenType.Comma) { break; } getNextToken(); } expect("Print", TokenType.RightParen); expect("Print", TokenType.Semicolon); } else if (this.token.tokentype == TokenType.Semicolon) { getNextToken(); } else if (this.token.tokentype == TokenType.Identifier) { v = Node.make_leaf(NodeType.nd_Ident, this.token.value); getNextToken(); expect("assign", TokenType.Op_assign); e = expr(0); t = Node.make_node(NodeType.nd_Assign, v, e); expect("assign", TokenType.Semicolon); } else if (this.token.tokentype == TokenType.Keyword_while) { getNextToken(); e = paren_expr(); s = stmt(); t = Node.make_node(NodeType.nd_While, e, s); } else if (this.token.tokentype == TokenType.LeftBrace) { getNextToken(); while (this.token.tokentype != TokenType.RightBrace && this.token.tokentype != TokenType.End_of_input) { t = Node.make_node(NodeType.nd_Sequence, t, stmt()); } expect("LBrace", TokenType.RightBrace); } else if (this.token.tokentype == TokenType.End_of_input) { } else { error(this.token.line, this.token.pos, "Expecting start of statement, found: " + this.token.tokentype); } return t; } Node parse() { Node t = null; getNextToken(); while (this.token.tokentype != TokenType.End_of_input) { t = Node.make_node(NodeType.nd_Sequence, t, stmt()); } return t; } void printAST(Node t) { int i = 0; if (t == null) { System.out.println(";"); } else { System.out.printf("%-14s", t.nt); if (t.nt == NodeType.nd_Ident || t.nt == NodeType.nd_Integer || t.nt == NodeType.nd_String) { System.out.println(" " + t.value); } else { System.out.println(); printAST(t.left); printAST(t.right); } } } public static void main(String[] args) { if (args.length > 0) { try { String value, token; int line, pos; Token t; boolean found; List<Token> list = new ArrayList<>(); Map<String, TokenType> str_to_tokens = new HashMap<>();   str_to_tokens.put("End_of_input", TokenType.End_of_input); str_to_tokens.put("Op_multiply", TokenType.Op_multiply); str_to_tokens.put("Op_divide", TokenType.Op_divide); str_to_tokens.put("Op_mod", TokenType.Op_mod); str_to_tokens.put("Op_add", TokenType.Op_add); str_to_tokens.put("Op_subtract", TokenType.Op_subtract); str_to_tokens.put("Op_negate", TokenType.Op_negate); str_to_tokens.put("Op_not", TokenType.Op_not); str_to_tokens.put("Op_less", TokenType.Op_less); str_to_tokens.put("Op_lessequal", TokenType.Op_lessequal); str_to_tokens.put("Op_greater", TokenType.Op_greater); str_to_tokens.put("Op_greaterequal", TokenType.Op_greaterequal); str_to_tokens.put("Op_equal", TokenType.Op_equal); str_to_tokens.put("Op_notequal", TokenType.Op_notequal); str_to_tokens.put("Op_assign", TokenType.Op_assign); str_to_tokens.put("Op_and", TokenType.Op_and); str_to_tokens.put("Op_or", TokenType.Op_or); str_to_tokens.put("Keyword_if", TokenType.Keyword_if); str_to_tokens.put("Keyword_else", TokenType.Keyword_else); str_to_tokens.put("Keyword_while", TokenType.Keyword_while); str_to_tokens.put("Keyword_print", TokenType.Keyword_print); str_to_tokens.put("Keyword_putc", TokenType.Keyword_putc); str_to_tokens.put("LeftParen", TokenType.LeftParen); str_to_tokens.put("RightParen", TokenType.RightParen); str_to_tokens.put("LeftBrace", TokenType.LeftBrace); str_to_tokens.put("RightBrace", TokenType.RightBrace); str_to_tokens.put("Semicolon", TokenType.Semicolon); str_to_tokens.put("Comma", TokenType.Comma); str_to_tokens.put("Identifier", TokenType.Identifier); str_to_tokens.put("Integer", TokenType.Integer); str_to_tokens.put("String", TokenType.String);   Scanner s = new Scanner(new File(args[0])); String source = " "; while (s.hasNext()) { String str = s.nextLine(); StringTokenizer st = new StringTokenizer(str); line = Integer.parseInt(st.nextToken()); pos = Integer.parseInt(st.nextToken()); token = st.nextToken(); value = ""; while (st.hasMoreTokens()) { value += st.nextToken() + " "; } found = false; if (str_to_tokens.containsKey(token)) { found = true; list.add(new Token(str_to_tokens.get(token), value, line, pos)); } if (found == false) { throw new Exception("Token not found: '" + token + "'"); } } Parser p = new Parser(list); p.printAST(p.parse()); } catch (FileNotFoundException e) { error(-1, -1, "Exception: " + e.getMessage()); } catch (Exception e) { error(-1, -1, "Exception: " + e.getMessage()); } } else { error(-1, -1, "No args"); } } }  
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#C.2B.2B
C++
#include <iostream> #define HEIGHT 4 #define WIDTH 4   struct Shape { public: char xCoord; char yCoord; char height; char width; char **figure; };   struct Glider : public Shape { static const char GLIDER_SIZE = 3; Glider( char x , char y ); ~Glider(); };   struct Blinker : public Shape { static const char BLINKER_HEIGHT = 3; static const char BLINKER_WIDTH = 1; Blinker( char x , char y ); ~Blinker(); };   class GameOfLife { public: GameOfLife( Shape sh ); void print(); void update(); char getState( char state , char xCoord , char yCoord , bool toggle); void iterate(unsigned int iterations); private: char world[HEIGHT][WIDTH]; char otherWorld[HEIGHT][WIDTH]; bool toggle; Shape shape; };   GameOfLife::GameOfLife( Shape sh ) : shape(sh) , toggle(true) { for ( char i = 0; i < HEIGHT; i++ ) { for ( char j = 0; j < WIDTH; j++ ) { world[i][j] = '.'; } } for ( char i = shape.yCoord; i - shape.yCoord < shape.height; i++ ) { for ( char j = shape.xCoord; j - shape.xCoord < shape.width; j++ ) { if ( i < HEIGHT && j < WIDTH ) { world[i][j] = shape.figure[ i - shape.yCoord ][j - shape.xCoord ]; } } } }   void GameOfLife::print() { if ( toggle ) { for ( char i = 0; i < HEIGHT; i++ ) { for ( char j = 0; j < WIDTH; j++ ) { std::cout << world[i][j]; } std::cout << std::endl; } } else { for ( char i = 0; i < HEIGHT; i++ ) { for ( char j = 0; j < WIDTH; j++ ) { std::cout << otherWorld[i][j]; } std::cout << std::endl; } } for ( char i = 0; i < WIDTH; i++ ) { std::cout << '='; } std::cout << std::endl; }   void GameOfLife::update() { if (toggle) { for ( char i = 0; i < HEIGHT; i++ ) { for ( char j = 0; j < WIDTH; j++ ) { otherWorld[i][j] = GameOfLife::getState(world[i][j] , i , j , toggle); } } toggle = !toggle; } else { for ( char i = 0; i < HEIGHT; i++ ) { for ( char j = 0; j < WIDTH; j++ ) { world[i][j] = GameOfLife::getState(otherWorld[i][j] , i , j , toggle); } } toggle = !toggle; } }   char GameOfLife::getState( char state, char yCoord, char xCoord, bool toggle ) { char neighbors = 0; if ( toggle ) { for ( char i = yCoord - 1; i <= yCoord + 1; i++ ) { for ( char j = xCoord - 1; j <= xCoord + 1; j++ ) { if ( i == yCoord && j == xCoord ) { continue; } if ( i > -1 && i < HEIGHT && j > -1 && j < WIDTH ) { if ( world[i][j] == 'X' ) { neighbors++; } } } } } else { for ( char i = yCoord - 1; i <= yCoord + 1; i++ ) { for ( char j = xCoord - 1; j <= xCoord + 1; j++ ) { if ( i == yCoord && j == xCoord ) { continue; } if ( i > -1 && i < HEIGHT && j > -1 && j < WIDTH ) { if ( otherWorld[i][j] == 'X' ) { neighbors++; } } } } } if (state == 'X') { return ( neighbors > 1 && neighbors < 4 ) ? 'X' : '.'; } else { return ( neighbors == 3 ) ? 'X' : '.'; } }   void GameOfLife::iterate( unsigned int iterations ) { for ( int i = 0; i < iterations; i++ ) { print(); update(); } }   Glider::Glider( char x , char y ) { xCoord = x; yCoord = y; height = GLIDER_SIZE; width = GLIDER_SIZE; figure = new char*[GLIDER_SIZE]; for ( char i = 0; i < GLIDER_SIZE; i++ ) { figure[i] = new char[GLIDER_SIZE]; } for ( char i = 0; i < GLIDER_SIZE; i++ ) { for ( char j = 0; j < GLIDER_SIZE; j++ ) { figure[i][j] = '.'; } } figure[0][1] = 'X'; figure[1][2] = 'X'; figure[2][0] = 'X'; figure[2][1] = 'X'; figure[2][2] = 'X'; }   Glider::~Glider() { for ( char i = 0; i < GLIDER_SIZE; i++ ) { delete[] figure[i]; } delete[] figure; }   Blinker::Blinker( char x , char y ) { xCoord = x; yCoord = y; height = BLINKER_HEIGHT; width = BLINKER_WIDTH; figure = new char*[BLINKER_HEIGHT]; for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { figure[i] = new char[BLINKER_WIDTH]; } for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { for ( char j = 0; j < BLINKER_WIDTH; j++ ) { figure[i][j] = 'X'; } } }   Blinker::~Blinker() { for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { delete[] figure[i]; } delete[] figure; }   int main() { Glider glider(0,0); GameOfLife gol(glider); gol.iterate(5); Blinker blinker(1,0); GameOfLife gol2(blinker); gol2.iterate(4); }  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pike
Pike
  class Point { int x, y; void create(int _x, int _y) { x = _x; y = _y; } }   void main() { object point = Point(10, 20); write("%d %d\n", point->x, point->y); }  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PL.2FI
PL/I
  define structure 1 point, 2 x float, 2 y float;      
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XPL0
XPL0
proc StrCopy(A, B); \Copy string: A --> B char A, B; \Strings: B must already have enough space "Reserved" int I; \Beware if strings overlap for I:= 0 to -1>>1-1 do [B(I):= A(I); if A(I) >= $80 then return ];   char S1, S2, S3(13); [S1:= "Hello, world!"; \S1 now points to the string S2:= S1; \S2 now also points to the string StrCopy(S1, S3); \S3 points to a separate copy of the string ]
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Z80_Assembly
Z80 Assembly
ld hl,MyString ld (PointerVariable),hl   MyString: ;assembler equates this label to a memory location at compile time byte "Hello",0   PointerVariable: word 0 ;placeholder for the address of the above string, gets written to by the code above.
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#Swift
Swift
let nPoints = 100   func generatePoint() -> (Int, Int) { while true { let x = Int.random(in: -15...16) let y = Int.random(in: -15...16) let r2 = x * x + y * y   if r2 >= 100 && r2 <= 225 { return (x, y) } } }   func filteringMethod() { var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)   for _ in 0..<nPoints { let (x, y) = generatePoint()   rows[y + 15][x + 15 * 2] = "*" }   for row in rows { print(row.joined()) } }   func precalculatingMethod() { var possiblePoints = [(Int, Int)]()   for y in -15...15 { for x in -15...15 { let r2 = x * x + y * y   if r2 >= 100 && r2 <= 225 { possiblePoints.append((x, y)) } } }   possiblePoints.shuffle()   var rows = [[String]](repeating: Array(repeating: " ", count: 62), count: 31)   for (x, y) in possiblePoints { rows[y + 15][x + 15 * 2] = "*" }   for row in rows { print(row.joined()) } }   print("Filtering method:") filteringMethod()   print("Precalculating method:") precalculatingMethod()
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#AutoHotkey
AutoHotkey
x = 1 If x MsgBox, x is %x% Else If x > 1 MsgBox, x is %x% Else MsgBox, x is %x%
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#Delphi
Delphi
  program Commatizing_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.RegularExpressions, system.StrUtils;   const PATTERN = '(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)'; TESTS: array[0..13] of string = ('123456789.123456789', '.123456789', '57256.1D-4', 'pi=3.14159265358979323846264338327950288419716939937510582097494459231', 'The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', '-in Aus$+1411.8millions', '===US$0017440 millions=== (in 2000 dollars)', '123.e8000 is pretty big.', 'The land area of the earth is 57268900(29% of the surface) square miles.', 'Ain''t no numbers in this here words, nohow, no way, Jose.', 'James was never known as 0000000007', 'Arthur Eddington wrote: I believe there are ' + '15747724136275002577605653961181555468044717914527116709366231425076185631031296' + ' protons in the universe.', ' $-140000±100 millions.', '6/9/1946 was a good year for some.');   var regex: TRegEx;   function Commatize(s: string; startIndex, period: integer; sep: string): string; var m: TMatch; s1, ip, pi, dp: string; splits: TArray<string>; i: integer; begin regex := TRegEx.Create(PATTERN);   if (startIndex < 0) or (startIndex >= s.Length) or (period < 1) or (sep.IsEmpty) then exit(s); m := regex.Match(s.Substring(startIndex, s.Length)); if not m.Success then exit(s);   s1 := m.Groups[0].Value; splits := s1.Split(['.']);   ip := splits[0];   if ip.Length > period then begin pi := ReverseString(ip); i := ((ip.Length - 1) div period) * period;   while i >= period do begin pi := pi.Substring(0, i) + sep + pi.Substring(i); i := i - period; end; ip := ReverseString(pi); end;   if s1.Contains('.') then begin dp := splits[1]; if dp.Length > period then begin i := ((dp.Length - 1) div period) * period; while i >= period do begin dp := dp.Substring(0, i) + sep + dp.Substring(i); i := i - period; end; end; ip := ip + '.' + dp; end; Result := s.Substring(0, startIndex) + s.Substring(startIndex).Replace(s1, ip, []); end;   var i: integer;   begin Writeln(commatize(TESTS[0], 0, 2, '*')); Writeln(commatize(TESTS[1], 0, 3, '-')); Writeln(commatize(TESTS[2], 0, 4, '__')); Writeln(commatize(TESTS[3], 0, 5, ' ')); Writeln(commatize(TESTS[4], 0, 3, '.')); for i := 5 to High(TESTS) do Writeln(commatize(TESTS[i], 0, 3, ',')); readln; end.
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ada
Ada
package String_Vec is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String);   use type String_Vec.Vector;
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_68
ALGOL 68
[]STRING list1 = ("AA","BB","CC"); []STRING list2 = ("AA","AA","AA"); []STRING list3 = ("AA","CC","BB"); []STRING list4 = ("AA","ACB","BB","CC"); []STRING list5 = ("single_element");   [][]STRING all lists to test = (list1, list2, list3, list4, list5);   PROC equal = ([]STRING list) BOOL: BEGIN BOOL ok := TRUE; FOR i TO UPB list - 1 WHILE ok DO ok := list[i] = list[i+1] OD; ok END;   PROC less than = ([]STRING list) BOOL: BEGIN BOOL ok := TRUE; FOR i TO UPB list - 1 WHILE ok DO ok := list[i] < list[i + 1] OD; ok END;   FOR i TO UPB all lists to test DO []STRING list = all lists to test[i]; print (("list:", (STRING s; FOR i TO UPB list DO s +:= " " + list[i] OD; s), new line)); IF equal (list) THEN print (("...is lexically equal", new line)) ELSE print (("...is not lexically equal", new line)) FI; IF less than (list) THEN print (("...is in strict ascending order", new line)) ELSE print (("...is not in strict ascending order", new line)) FI OD
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Ada
Ada
with Ada.Text_IO, Ada.Streams.Stream_IO, Ada.Strings.Unbounded, Ada.Command_Line, Ada.Exceptions; use Ada.Strings, Ada.Strings.Unbounded, Ada.Streams, Ada.Exceptions;   procedure Main is package IO renames Ada.Text_IO;   package Lexer is type Token is (Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_notequal, Op_not, Op_assign, Op_and, Op_or,   LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma,   Keyword_if, Keyword_else, Keyword_while, Keyword_print, Keyword_putc, Identifier, Token_Integer, Token_String, End_of_input,   Empty_Char_Error, Invalid_Escape_Error, Multi_Char_Error, EOF_Comment_Error, EOF_String_Error, EOL_String_Error, Invalid_Char_Error, Invalid_Num_Error );   subtype Operator is Token range Op_multiply .. Op_or; subtype Symbol is Token range Token'Succ(Operator'Last) .. Comma; subtype Keyword is Token range Token'Succ(Symbol'Last) .. Keyword_putc; subtype Error is Token range Empty_Char_Error .. Invalid_Num_Error; subtype Operator_or_Error is Token with Static_Predicate => Operator_or_Error in Operator | Error;   subtype Whitespace is Character with Static_Predicate => Whitespace in ' ' | ASCII.HT | ASCII.CR | ASCII.LF;   Lexer_Error : exception; Invalid_Escape_Code : constant Character := ASCII.NUL;   procedure run(input : Stream_IO.File_Type); end Lexer;   package body Lexer is use type Stream_IO.Count;   procedure run(input : Stream_IO.File_Type) is type State is (State_Start, State_Identifier, State_Integer, State_Char, State_String, State_Comment); curr_state : State := State_Start; curr_char : Character; curr_col, curr_row, token_col, token_row : Positive := 1; token_text : Unbounded_String := Unbounded.Null_Unbounded_String;   function look_ahead return Character is next_char : Character := ASCII.LF; begin if not Stream_IO.End_Of_File(input) then next_char := Character'Input(Stream_IO.Stream(input)); Stream_IO.Set_Index(input, Stream_IO.Index(input) - 1); end if; return next_char; end look_ahead;   procedure next_char is next : Character := Character'Input(Stream_IO.Stream(input)); begin curr_col := curr_col + 1; if curr_char = ASCII.LF then curr_row := curr_row + 1; curr_col := 1; end if; curr_char := next; end next_char;   procedure print_token(tok : Token; text : String := "") is procedure raise_error(text : String) is begin raise Lexer_Error with "Error: " & text; end; begin IO.Put(token_row'Image & ASCII.HT & token_col'Image & ASCII.HT); case tok is when Operator | Symbol | Keyword | End_of_input => IO.Put_Line(tok'Image); when Token_Integer => IO.Put_Line("INTEGER" & ASCII.HT & text); when Token_String => IO.Put_Line("STRING" & ASCII.HT & ASCII.Quotation & text & ASCII.Quotation); when Identifier => IO.Put_Line(tok'Image & ASCII.HT & text); when Empty_Char_Error => raise_error("empty character constant"); when Invalid_Escape_Error => raise_error("unknown escape sequence: " & text); when Multi_Char_Error => raise_error("multi-character constant: " & text); when EOF_Comment_Error => raise_error("EOF in comment"); when EOF_String_Error => raise_error("EOF in string"); when EOL_String_Error => raise_error("EOL in string"); when Invalid_Char_Error => raise_error("invalid character: " & curr_char); when Invalid_Num_Error => raise_error("invalid number: " & text); end case; end print_token;   procedure lookahead_choose(determiner : Character; a, b : Operator_or_Error) is begin if look_ahead = determiner then print_token(a); next_char; else print_token(b); end if; end lookahead_choose;   function to_escape_code(c : Character) return Character is begin case c is when 'n' => return ASCII.LF; when '\' => return '\'; when others => print_token(Invalid_Escape_Error, ASCII.Back_Slash & c); return Invalid_Escape_Code; end case; end to_escape_code; begin curr_char := Character'Input(Stream_IO.Stream(input)); loop case curr_state is when State_Start => token_col := curr_col; token_row := curr_row; case curr_char is when '*' => print_token(Op_multiply); when '/' => if look_ahead = '*' then next_char; curr_state := State_Comment; else print_token(Op_divide); end if; when '%' => print_token(Op_mod); when '+' => print_token(Op_add); when '-' => print_token(Op_subtract); when '(' => print_token(LeftParen); when ')' => print_token(RightParen); when '{' => print_token(LeftBrace); when '}' => print_token(RightBrace); when ';' => print_token(Semicolon); when ',' => print_token(Comma); when '<' => lookahead_choose('=', Op_lessequal, Op_less); when '>' => lookahead_choose('=', Op_greaterequal, Op_greater); when '!' => lookahead_choose('=', Op_notequal, Op_not); when '=' => lookahead_choose('=', Op_equal, Op_assign); when '&' => lookahead_choose('&', Op_and, Invalid_Char_Error); when '|' => lookahead_choose('|', Op_or, Invalid_Char_Error); when 'a' .. 'z' | 'A' .. 'Z' | '_' => Unbounded.Append(token_text, curr_char); curr_state := State_Identifier; when '0' .. '9' => Unbounded.Append(token_text, curr_char); curr_state := State_Integer; when ''' => curr_state := State_Char; when ASCII.Quotation => curr_state := State_String; when Whitespace => null; when others => null; end case; next_char;   when State_Identifier => case curr_char is when 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' => Unbounded.Append(token_text, curr_char); next_char; when others => if token_text = "if" then print_token(Keyword_if); elsif token_text = "else" then print_token(Keyword_else); elsif token_text = "while" then print_token(Keyword_while); elsif token_text = "print" then print_token(Keyword_print); elsif token_text = "putc" then print_token(Keyword_putc); else print_token(Identifier, To_String(token_text)); end if; Unbounded.Set_Unbounded_String(token_text, ""); curr_state := State_Start; end case;   when State_Integer => case curr_char is when '0' .. '9' => Unbounded.Append(token_text, curr_char); next_char; when 'a' .. 'z' | 'A' .. 'Z' | '_' => print_token(Invalid_Num_Error, To_String(token_text)); when others => print_token(Token_Integer, To_String(token_text)); Unbounded.Set_Unbounded_String(token_text, ""); curr_state := State_Start; end case;   when State_Char => case curr_char is when ''' => if Unbounded.Length(token_text) = 0 then print_token(Empty_Char_Error); elsif Unbounded.Length(token_text) = 1 then print_token(Token_Integer, Character'Pos(Element(token_text, 1))'Image); else print_token(Multi_Char_Error, To_String(token_text)); end if; Set_Unbounded_String(token_text, ""); curr_state := State_Start; when '\' => Unbounded.Append(token_text, to_escape_code(look_ahead)); next_char; when others => Unbounded.Append(token_text, curr_char); end case; next_char;   when State_String => case curr_char is when ASCII.Quotation => print_token(Token_String, To_String(token_text)); Set_Unbounded_String(token_text, ""); curr_state := State_Start; when '\' => if to_escape_code(look_ahead) /= Invalid_Escape_Code then Unbounded.Append(token_text, curr_char); end if; when ASCII.LF | ASCII.CR => print_token(EOL_String_Error); when others => Unbounded.Append(token_text, curr_char); end case; next_char;   when State_Comment => case curr_char is when '*' => if look_ahead = '/' then next_char; curr_state := State_Start; end if; when others => null; end case; next_char; end case; end loop; exception when error : Stream_IO.End_Error => if curr_state = State_String then print_token(EOF_String_Error); else print_token(End_of_input); end if; when error : Lexer.Lexer_Error => IO.Put_Line(Exception_Message(error)); end run; end Lexer;   source_file : Stream_IO.File_Type; begin if Ada.Command_Line.Argument_Count < 1 then IO.Put_Line("usage: lex [filename]"); return; end if; Stream_IO.Open(source_file, Stream_IO.In_File, Ada.Command_Line.Argument(1)); Lexer.run(source_file); exception when error : others => IO.Put_Line("Error: " & Exception_Message(error)); end Main;  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Ada
Ada
with Ada.Command_line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO;   procedure Print_Commands is begin -- The number of command line arguments is retrieved from the function Argument_Count -- The actual arguments are retrieved from the function Argument -- The program name is retrieved from the function Command_Name Put(Command_Name & " "); for Arg in 1..Argument_Count loop Put(Argument(Arg) & " "); end loop; New_Line; end Print_Commands;
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Aikido
Aikido
    foreach arg in args { println ("arg: " + arg) }    
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#360_Assembly
360 Assembly
  * An asterisk in column one denotes a comment line * Comments may also follow any syntactically complete instruction: LA 1,0 Comment NOP Comment (after a NOP instruction) * Comments after instructions with omitted operands require a comma "," END , Comment (without comma, "Comment" assumed an operand of "END")  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#4D
4D
`Comments in 4th Dimension begin with the accent character and extend to the end of the line (until 4D version 2004). // This is a comment starting from 4D v11 and newer. Accent character is replaced by //
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Go
Go
package main   import ( "bufio" "encoding/binary" "fmt" "log" "math" "os" "strconv" "strings" )   type code = byte   const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt )   var codeMap = map[string]code{ "fetch": fetch, "store": store, "push": push, "add": add, "sub": sub, "mul": mul, "div": div, "mod": mod, "lt": lt, "gt": gt, "le": le, "ge": ge, "eq": eq, "ne": ne, "and": and, "or": or, "neg": neg, "not": not, "jmp": jmp, "jz": jz, "prtc": prtc, "prts": prts, "prti": prti, "halt": halt, }   var ( err error scanner *bufio.Scanner object []code stringPool []string )   func reportError(msg string) { log.Fatalf("error : %s\n", msg) }   func check(err error) { if err != nil { log.Fatal(err) } }   func btoi(b bool) int32 { if b { return 1 } return 0 }   func itob(i int32) bool { if i != 0 { return true } return false }   func emitByte(c code) { object = append(object, c) }   func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } }   /*** Virtual Machine interpreter ***/ func runVM(dataSize int) { stack := make([]int32, dataSize+1) pc := int32(0) for { op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, stack[x]) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) ln := len(stack) stack[x] = stack[ln-1] stack = stack[:ln-1] pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, x) pc += 4 case add: ln := len(stack) stack[ln-2] += stack[ln-1] stack = stack[:ln-1] case sub: ln := len(stack) stack[ln-2] -= stack[ln-1] stack = stack[:ln-1] case mul: ln := len(stack) stack[ln-2] *= stack[ln-1] stack = stack[:ln-1] case div: ln := len(stack) stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1])) stack = stack[:ln-1] case mod: ln := len(stack) stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1]))) stack = stack[:ln-1] case lt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] < stack[ln-1]) stack = stack[:ln-1] case gt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] > stack[ln-1]) stack = stack[:ln-1] case le: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1]) stack = stack[:ln-1] case ge: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1]) stack = stack[:ln-1] case eq: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] == stack[ln-1]) stack = stack[:ln-1] case ne: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] != stack[ln-1]) stack = stack[:ln-1] case and: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1])) stack = stack[:ln-1] case or: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1])) stack = stack[:ln-1] case neg: ln := len(stack) stack[ln-1] = -stack[ln-1] case not: ln := len(stack) stack[ln-1] = btoi(!itob(stack[ln-1])) case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x case jz: ln := len(stack) v := stack[ln-1] stack = stack[:ln-1] if v != 0 { pc += 4 } else { x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x } case prtc: ln := len(stack) fmt.Printf("%c", stack[ln-1]) stack = stack[:ln-1] case prts: ln := len(stack) fmt.Printf("%s", stringPool[stack[ln-1]]) stack = stack[:ln-1] case prti: ln := len(stack) fmt.Printf("%d", stack[ln-1]) stack = stack[:ln-1] case halt: return default: reportError(fmt.Sprintf("Unknown opcode %d\n", op)) } } }   func translate(s string) string { var d strings.Builder for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } return d.String() }   func loadCode() int { var dataSize int firstLine := true for scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") if len(line) == 0 { if firstLine { reportError("empty line") } else { break } } lineList := strings.Fields(line) if firstLine { dataSize, err = strconv.Atoi(lineList[1]) check(err) nStrings, err := strconv.Atoi(lineList[3]) check(err) for i := 0; i < nStrings; i++ { scanner.Scan() s := strings.Trim(scanner.Text(), "\"\n") stringPool = append(stringPool, translate(s)) } firstLine = false continue } offset, err := strconv.Atoi(lineList[0]) check(err) instr := lineList[1] opCode, ok := codeMap[instr] if !ok { reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode)) } emitByte(opCode) switch opCode { case jmp, jz: p, err := strconv.Atoi(lineList[3]) check(err) emitWord(p - offset - 1) case push: value, err := strconv.Atoi(lineList[2]) check(err) emitWord(value) case fetch, store: value, err := strconv.Atoi(strings.Trim(lineList[2], "[]")) check(err) emitWord(value) } } check(scanner.Err()) return dataSize }   func main() { codeGen, err := os.Open("codegen.txt") check(err) defer codeGen.Close() scanner = bufio.NewScanner(codeGen) runVM(loadCode()) }
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Forth
Forth
CREATE BUF 0 , : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : >Integer >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ; : SKIP ( xt --) BEGIN PEEK OVER EXECUTE WHILE GETC DROP REPEAT DROP ; : WORD ( xt -- c-addr) DUP >R SKIP PAD 1+ BEGIN PEEK R@ EXECUTE INVERT WHILE GETC OVER C! CHAR+ REPEAT R> SKIP PAD TUCK - 1- PAD C! ; : INTERN ( c-addr -- c-addr) HERE TUCK OVER C@ CHAR+ DUP ALLOT CMOVE ; : "? [CHAR] " = ; : "TYPE" [CHAR] " EMIT TYPE [CHAR] " EMIT ; : . 0 .R ; : 3@ ( addr -- w3 w2 w1) [ 2 CELLS ]L + DUP @ SWAP CELL - DUP @ SWAP CELL - @ ;   CREATE BUF' 12 ALLOT : PREPEND ( c-addr c -- c-addr) BUF' 1+ C! COUNT 10 MIN DUP 1+ BUF' C! BUF' 2 + SWAP CMOVE BUF' ; : >NODE ( c-addr -- n) [CHAR] $ PREPEND FIND IF EXECUTE ELSE ." unrecognized node " COUNT TYPE CR THEN ; : NODE ( n left right -- addr) HERE >R , , , R> ;   : CONS ( a b l -- l) HERE >R , , , R> ; : FIRST ( l -- a) [ 2 CELLS ]L + @ ; : SECOND ( l -- b) CELL+ @ ; : C=? ( c-addr1 c-addr2 -- t|f) COUNT ROT COUNT COMPARE 0= ; : LOOKUP ( c-addr l -- n t | c-addr f) BEGIN DUP WHILE OVER OVER FIRST C=? IF NIP SECOND TRUE EXIT THEN @ REPEAT DROP FALSE ;   CREATE GLOBALS 0 , CREATE STRINGS 0 , : DEPTH ( pool -- n) DUP IF SECOND 1+ THEN ; : FISH ( c-addr pool -- n pool') TUCK LOOKUP IF SWAP ELSE INTERN OVER DEPTH ROT OVER >R CONS R> SWAP THEN ; : >Identifier ['] SPACE? WORD GLOBALS @ FISH GLOBALS ! ; : >String ['] "? WORD STRINGS @ FISH STRINGS ! ; : >; 0 ; : HANDLER [CHAR] @ PREPEND FIND DROP ; : READER ( c-addr -- xt t | f) [CHAR] > PREPEND FIND DUP 0= IF NIP THEN ; DEFER GETAST : READ ( c-addr -- right left) READER IF EXECUTE 0 ELSE GETAST GETAST THEN SWAP ; : (GETAST) ['] SPACE? WORD DUP HANDLER >R READ R> NODE ; ' (GETAST) IS GETAST   CREATE PC 0 , : i32! ( n addr --) OVER $FF AND OVER C! 1+ OVER 8 RSHIFT $FF AND OVER C! 1+ OVER 16 RSHIFT $FF AND OVER C! 1+ OVER 24 RSHIFT $FF AND OVER C! DROP DROP ; : i32, ( n --) HERE i32! 4 ALLOT 4 PC +! ; : i8, ( c --) C, 1 PC +! ; : i8@+ DUP 1+ SWAP C@ 1 PC +! ; : i32@+ ( addr -- addr+4 n) i8@+ >R i8@+ 8 LSHIFT R> OR >R i8@+ 16 LSHIFT R> OR >R i8@+ 24 LSHIFT R> OR ;   CREATE #OPS 0 , : OP: CREATE #OPS @ , 1 #OPS +! DOES> @ ; OP: fetch OP: store OP: push OP: jmp OP: jz OP: prtc OP: prti OP: prts OP: neg OP: not OP: add OP: sub OP: mul OP: div OP: mod OP: lt OP: gt OP: le OP: ge OP: eq OP: ne OP: and OP: or OP: halt   : GEN ( ast --) 3@ EXECUTE ; : @; ( r l) DROP DROP ; : @Identifier fetch i8, i32, DROP ; : @Integer push i8, i32, DROP ; : @String push i8, i32, DROP ; : @Prtc GEN prtc i8, DROP ; : @Prti GEN prti i8, DROP ; : @Prts GEN prts i8, DROP ; : @Not GEN not i8, DROP ; : @Negate GEN neg i8, DROP ; : @Sequence GEN GEN ; : @Assign CELL+ @ >R GEN store i8, R> i32, ; : @While PC @ SWAP GEN jz i8, HERE >R 0 i32, SWAP GEN jmp i8, i32, PC @ R> i32! ; : @If GEN jz i8, HERE >R 0 i32, CELL+ DUP CELL+ @ DUP @ ['] @; = IF DROP @ ELSE SWAP @ GEN jmp i8, HERE 0 i32, PC @ R> i32! >R THEN GEN PC @ R> i32! ; : BINARY >R GEN GEN R> i8, ; : @Subtract sub BINARY ;  : @Add add BINARY ; : @Mod mod BINARY ;  : @Multiply mul BINARY ; : @Divide div BINARY ; : @Less lt BINARY ;  : @LessEqual le BINARY ; : @Greater gt BINARY ;  : @GreaterEqual ge BINARY ; : @Equal eq BINARY ;  : @NotEqual ne BINARY ; : @And and BINARY ;  : @Or or BINARY ;   : REVERSE ( l -- l') 0 SWAP BEGIN DUP WHILE TUCK DUP @ ROT ROT  ! REPEAT DROP ; : .STRINGS STRINGS @ REVERSE BEGIN DUP WHILE DUP FIRST COUNT "TYPE" CR @ REPEAT DROP ; : .HEADER ( --) ." Datasize: " GLOBALS @ DEPTH . SPACE ." Strings: " STRINGS @ DEPTH . CR .STRINGS ; : GENERATE ( ast -- addr u) 0 PC ! HERE >R GEN halt i8, R> PC @ ; : ," [CHAR] " PARSE TUCK HERE SWAP CMOVE ALLOT ; CREATE "OPS" ," fetch store push jmp jz prtc prti prts " ," neg not add sub mul div mod lt " ," gt le ge eq ne and or halt " : .i32 i32@+ . ; : .[i32] [CHAR] [ EMIT .i32 [CHAR] ] EMIT ; : .off [CHAR] ( EMIT PC @ >R i32@+ DUP R> - . [CHAR] ) EMIT SPACE . ; CREATE .INT ' .[i32] , ' .[i32] , ' .i32 , ' .off , ' .off , : EMIT ( addr u --) >R 0 PC ! BEGIN PC @ R@ < WHILE PC @ 5 .R SPACE i8@+ DUP 6 * "OPS" + 6 TYPE DUP 5 < IF CELLS .INT + @ EXECUTE ELSE DROP THEN CR REPEAT DROP R> DROP ; GENERATE EMIT BYE
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#Haskell
Haskell
import Data.Time.Clock import Data.List   type Time = Integer type Sorter a = [a] -> [a]   -- Simple timing function (in microseconds) timed :: IO a -> IO (a, Time) timed prog = do t0 <- getCurrentTime x <- prog t1 <- x `seq` getCurrentTime return (x, ceiling $ 1000000 * diffUTCTime t1 t0)   -- testing sorting algorithm on a given set test :: [a] -> Sorter a -> IO [(Int, Time)] test set srt = mapM (timed . run) ns where ns = take 15 $ iterate (\x -> (x * 5) `div` 3) 10 run n = pure $ length $ srt (take n set)   -- sample sets constant = repeat 1   presorted = [1..]   random = (`mod` 100) <$> iterate step 42 where step x = (x * a + c) `mod` m (a, c, m) = (1103515245, 12345, 2^31-1)
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) The interpreter algorithm is relatively simple interp(x) if x == NULL return NULL elif x.node_type == Integer return x.value converted to an integer elif x.node_type == Ident return the current value of variable x.value elif x.node_type == String return x.value elif x.node_type == Assign globals[x.left.value] = interp(x.right) return NULL elif x.node_type is a binary operator return interp(x.left) operator interp(x.right) elif x.node_type is a unary operator, return return operator interp(x.left) elif x.node_type == If if (interp(x.left)) then interp(x.right.left) else interp(x.right.right) return NULL elif x.node_type == While while (interp(x.left)) do interp(x.right) return NULL elif x.node_type == Prtc print interp(x.left) as a character, no newline return NULL elif x.node_type == Prti print interp(x.left) as an integer, no newline return NULL elif x.node_type == Prts print interp(x.left) as a string, respecting newlines ("\n") return NULL elif x.node_type == Sequence interp(x.left) interp(x.right) return NULL else error("unknown node type") Notes: Because of the simple nature of our tiny language, Semantic analysis is not needed. Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0. This means, for instance, that 3 / 2 should result in 1. For division when one of the operands is negative, the result should be truncated towards 0. This means, for instance, that 3 / -2 should result in -1. Test program prime.t lex <prime.t | parse | interp /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 101 is prime Total primes found: 26 Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task Virtual Machine Interpreter task
#RATFOR
RATFOR
###################################################################### # # The Rosetta Code AST interpreter in Ratfor 77. # # # In FORTRAN 77 and therefore in Ratfor 77, there is no way to specify # that a value should be put on a call stack. Therefore there is no # way to implement recursive algorithms in Ratfor 77 (although see the # Ratfor for the "syntax analyzer" task, where a recursive language is # implemented *in* Ratfor). Thus we cannot simply follow the # recursive pseudocode, and instead use non-recursive algorithms. # # How to deal with FORTRAN 77 input is another problem. I use # formatted input, treating each line as an array of type # CHARACTER--regrettably of no more than some predetermined, finite # length. It is a very simple method and presents no significant # difficulties, aside from the restriction on line length of the # input. # # Output is a bigger problem. If one uses gfortran, "advance='no'" is # available, but not if one uses f2c. The method employed here is to # construct the output in lines--regrettably, again, of fixed length. # # # On a POSIX platform, the program can be compiled with f2c and run # somewhat as follows: # # ratfor77 interp-in-ratfor.r > interp-in-ratfor.f # f2c -C -Nc80 interp-in-ratfor.f # cc interp-in-ratfor.c -lf2c # ./a.out < compiler-tests/primes.ast # # With gfortran, a little differently: # # ratfor77 interp-in-ratfor.r > interp-in-ratfor.f # gfortran -fcheck=all -std=legacy interp-in-ratfor.f # ./a.out < compiler-tests/primes.ast # # # I/O is strictly from default input and to default output, which, on # POSIX systems, usually correspond respectively to standard input and # standard output. (I did not wish to have to deal with unit numbers; # these are now standardized in ISO_FORTRAN_ENV, but that is not # available in FORTRAN 77.) # #---------------------------------------------------------------------   # Some parameters you may wish to modify.   define(LINESZ, 256) # Size of an input line. define(OUTLSZ, 1024) # Size of an output line. define(STRNSZ, 4096) # Size of the string pool. define(NODSSZ, 4096) # Size of the nodes pool. define(STCKSZ, 4096) # Size of stacks. define(MAXVAR, 256) # Maximum number of variables.   #---------------------------------------------------------------------   define(NEWLIN, 10) # The Unix newline character (ASCII LF). define(DQUOTE, 34) # The double quote character. define(BACKSL, 92) # The backslash character.   #---------------------------------------------------------------------   define(NODESZ, 3) define(NNEXTF, 1) # Index for next-free. define(NTAG, 1) # Index for the tag. # For an internal node -- define(NLEFT, 2) # Index for the left node. define(NRIGHT, 3) # Index for the right node. # For a leaf node -- define(NITV, 2) # Index for the string pool index. define(NITN, 3) # Length of the value.   define(NIL, -1) # Nil node.   define(RGT, 10000) define(STAGE2, 20000)   # The following all must be less than RGT. define(NDID, 0) define(NDSTR, 1) define(NDINT, 2) define(NDSEQ, 3) define(NDIF, 4) define(NDPRTC, 5) define(NDPRTS, 6) define(NDPRTI, 7) define(NDWHIL, 8) define(NDASGN, 9) define(NDNEG, 10) define(NDNOT, 11) define(NDMUL, 12) define(NDDIV, 13) define(NDMOD, 14) define(NDADD, 15) define(NDSUB, 16) define(NDLT, 17) define(NDLE, 18) define(NDGT, 19) define(NDGE, 20) define(NDEQ, 21) define(NDNE, 22) define(NDAND, 23) define(NDOR, 24)   #---------------------------------------------------------------------   function issp (c)   # Is a character a space character?   implicit none   character c logical issp   integer ic   ic = ichar (c) issp = (ic == 32 || (9 <= ic && ic <= 13)) end   function skipsp (str, i, imax)   # Skip past spaces in a string.   implicit none   character str(*) integer i integer imax integer skipsp   logical issp   logical done   skipsp = i done = .false. while (!done) { if (imax <= skipsp) done = .true. else if (!issp (str(skipsp))) done = .true. else skipsp = skipsp + 1 } end   function skipns (str, i, imax)   # Skip past non-spaces in a string.   implicit none   character str(*) integer i integer imax integer skipns   logical issp   logical done   skipns = i done = .false. while (!done) { if (imax <= skipns) done = .true. else if (issp (str(skipns))) done = .true. else skipns = skipns + 1 } end   function trimrt (str, n)   # Find the length of a string, if one ignores trailing spaces.   implicit none   character str(*) integer n integer trimrt   logical issp   logical done   trimrt = n done = .false. while (!done) { if (trimrt == 0) done = .true. else if (!issp (str(trimrt))) done = .true. else trimrt = trimrt - 1 } end   #---------------------------------------------------------------------   subroutine addstq (strngs, istrng, src, i0, n0, i, n)   # Add a quoted string to the string pool.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character src(*) # Source string. integer i0, n0 # Index and length in source string. integer i, n # Index and length in string pool.   integer j logical done   1000 format ('attempt to treat an unquoted string as a quoted string')   if (src(i0) != char (DQUOTE) || src(i0 + n0 - 1) != char (DQUOTE)) { write (*, 1000) stop }   i = istrng   n = 0 j = i0 + 1 done = .false. while (j != i0 + n0 - 1) if (i == STRNSZ) { write (*, '(''string pool exhausted'')') stop } else if (src(j) == char (BACKSL)) { if (j == i0 + n0 - 1) { write (*, '(''incorrectly formed quoted string'')') stop } if (src(j + 1) == 'n') strngs(istrng) = char (NEWLIN) else if (src(j + 1) == char (BACKSL)) strngs(istrng) = src(j + 1) else { write (*, '(''unrecognized escape sequence'')') stop } istrng = istrng + 1 n = n + 1 j = j + 2 } else { strngs(istrng) = src(j) istrng = istrng + 1 n = n + 1 j = j + 1 } end   subroutine addstu (strngs, istrng, src, i0, n0, i, n)   # Add an unquoted string to the string pool.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character src(*) # Source string. integer i0, n0 # Index and length in source string. integer i, n # Index and length in string pool.   integer j   if (STRNSZ < istrng + (n0 - 1)) { write (*, '(''string pool exhausted'')') stop } for (j = 0; j < n0; j = j + 1) strngs(istrng + j) = src(i0 + j) i = istrng n = n0 istrng = istrng + n0 end   subroutine addstr (strngs, istrng, src, i0, n0, i, n)   # Add a string (possibly given as a quoted string) to the string # pool.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. character src(*) # Source string. integer i0, n0 # Index and length in source string. integer i, n # Index and length in string pool.   if (n0 == 0) { i = 0 n = 0 } else if (src(i0) == char (DQUOTE)) call addstq (strngs, istrng, src, i0, n0, i, n) else call addstu (strngs, istrng, src, i0, n0, i, n) end   #---------------------------------------------------------------------   subroutine push (stack, sp, i)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer i # Value to push.   if (sp == STCKSZ) { write (*, '(''stack overflow in push'')') stop } stack(sp) = i sp = sp + 1 end   function pop (stack, sp)   implicit none   integer stack(STCKSZ) integer sp # Stack pointer. integer pop   if (sp == 1) { write (*, '(''stack underflow in pop'')') stop } sp = sp - 1 pop = stack(sp) end   function nstack (sp)   implicit none   integer sp # Stack pointer. integer nstack   nstack = sp - 1 # Current cardinality of the stack. end   #---------------------------------------------------------------------   subroutine initnd (nodes, frelst)   # Initialize the nodes pool.   implicit none   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list.   integer i   for (i = 1; i < NODSSZ; i = i + 1) nodes(NNEXTF, i) = i + 1 nodes(NNEXTF, NODSSZ) = NIL frelst = 1 end   subroutine newnod (nodes, frelst, i)   # Get the index for a new node taken from the free list.   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list. integer i # Index of the new node.   integer j   if (frelst == NIL) { write (*, '(''nodes pool exhausted'')') stop } i = frelst frelst = nodes(NNEXTF, frelst) for (j = 1; j <= NODESZ; j = j + 1) nodes(j, i) = 0 end   subroutine frenod (nodes, frelst, i)   # Return a node to the free list.   integer nodes (NODESZ, NODSSZ) integer frelst # Head of the free list. integer i # Index of the node to free.   nodes(NNEXTF, i) = frelst frelst = i end   function strtag (str, i, n)   implicit none   character str(*) integer i, n integer strtag   character*16 s integer j   for (j = 0; j < 16; j = j + 1) if (j < n) s(j + 1 : j + 1) = str(i + j) else s(j + 1 : j + 1) = ' '   if (s == "Identifier ") strtag = NDID else if (s == "String ") strtag = NDSTR else if (s == "Integer ") strtag = NDINT else if (s == "Sequence ") strtag = NDSEQ else if (s == "If ") strtag = NDIF else if (s == "Prtc ") strtag = NDPRTC else if (s == "Prts ") strtag = NDPRTS else if (s == "Prti ") strtag = NDPRTI else if (s == "While ") strtag = NDWHIL else if (s == "Assign ") strtag = NDASGN else if (s == "Negate ") strtag = NDNEG else if (s == "Not ") strtag = NDNOT else if (s == "Multiply ") strtag = NDMUL else if (s == "Divide ") strtag = NDDIV else if (s == "Mod ") strtag = NDMOD else if (s == "Add ") strtag = NDADD else if (s == "Subtract ") strtag = NDSUB else if (s == "Less ") strtag = NDLT else if (s == "LessEqual ") strtag = NDLE else if (s == "Greater ") strtag = NDGT else if (s == "GreaterEqual ") strtag = NDGE else if (s == "Equal ") strtag = NDEQ else if (s == "NotEqual ") strtag = NDNE else if (s == "And ") strtag = NDAND else if (s == "Or ") strtag = NDOR else if (s == "; ") strtag = NIL else { write (*, '(''unrecognized input line: '', A16)') s stop } end   subroutine readln (strngs, istrng, tag, iarg, narg)   # Read a line of the AST input.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer tag # The node tag or NIL. integer iarg # Index of an argument in the string pool. integer narg # Length of an argument in the string pool.   integer trimrt integer strtag integer skipsp integer skipns   character line(LINESZ) character*20 fmt integer i, j, n   # Read a line of text as an array of characters. write (fmt, '(''('', I10, ''A)'')') LINESZ read (*, fmt) line   n = trimrt (line, LINESZ)   i = skipsp (line, 1, n + 1) j = skipns (line, i, n + 1) tag = strtag (line, i, j - i)   i = skipsp (line, j, n + 1) call addstr (strngs, istrng, line, i, (n + 1) - i, iarg, narg) end   function hasarg (tag)   implicit none   integer tag logical hasarg   hasarg = (tag == NDID || tag == NDINT || tag == NDSTR) end   subroutine rdast (strngs, istrng, nodes, frelst, iast)   # Read in the AST. A non-recursive algorithm is used.   implicit none   character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. integer iast # Index of root node of the AST.   integer nstack integer pop logical hasarg   integer stack(STCKSZ) integer sp # Stack pointer. integer tag, iarg, narg integer i, j, k   sp = 1   call readln (strngs, istrng, tag, iarg, narg) if (tag == NIL) iast = NIL else { call newnod (nodes, frelst, i) iast = i nodes(NTAG, i) = tag nodes(NITV, i) = 0 nodes(NITN, i) = 0 if (hasarg (tag)) { nodes(NITV, i) = iarg nodes(NITN, i) = narg } else { call push (stack, sp, i + RGT) call push (stack, sp, i) while (nstack (sp) != 0) { j = pop (stack, sp) k = mod (j, RGT) call readln (strngs, istrng, tag, iarg, narg) if (tag == NIL) i = NIL else { call newnod (nodes, frelst, i) nodes(NTAG, i) = tag if (hasarg (tag)) { nodes(NITV, i) = iarg nodes(NITN, i) = narg } else { call push (stack, sp, i + RGT) call push (stack, sp, i) } } if (j == k) nodes(NLEFT, k) = i else nodes(NRIGHT, k) = i } } } end   #---------------------------------------------------------------------   subroutine flushl (outbuf, noutbf)   # Flush a line from the output buffer.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf.   character*20 fmt integer i   if (noutbf == 0) write (*, '()') else { write (fmt, 1000) noutbf 1000 format ('(', I10, 'A)') write (*, fmt) (outbuf(i), i = 1, noutbf) noutbf = 0 } end   subroutine wrtchr (outbuf, noutbf, ch)   # Write a character to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character ch # The character to output.   # This routine silently truncates anything that goes past the buffer # boundary.   if (ch == char (NEWLIN)) call flushl (outbuf, noutbf) else if (noutbf < OUTLSZ) { noutbf = noutbf + 1 outbuf(noutbf) = ch } end   subroutine wrtstr (outbuf, noutbf, str, i, n)   # Write a substring to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. character str(*) # The string from which to output. integer i, n # Index and length of the substring.   integer j   for (j = 0; j < n; j = j + 1) call wrtchr (outbuf, noutbf, str(i + j)) end   subroutine wrtint (outbuf, noutbf, ival)   # Write a non-negative integer to output.   implicit none   character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer ival # The non-negative integer to print.   integer skipsp   character*40 buf integer i   # Using "write" probably is the slowest way one could think of to do # this, but people do formatted output all the time, anyway. :) The # reason, of course, is that output tends to be slow anyway. write (buf, '(I40)') ival for (i = skipsp (buf, 1, 41); i <= 40; i = i + 1) call wrtchr (outbuf, noutbf, buf(i:i)) end   #---------------------------------------------------------------------   define(VARSZ, 3) define(VNAMEI, 1) # Variable name's index in the string pool. define(VNAMEN, 2) # Length of the name. define(VVALUE, 3) # Variable's value.   function fndvar (vars, numvar, strngs, istrng, i0, n0)   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer i0, n0 # Index and length in the string pool. integer fndvar # The location of the variable.   integer j, k integer i, n logical done1 logical done2   j = 1 done1 = .false. while (!done1) if (j == numvar + 1) done1 = .true. else if (n0 == vars(VNAMEN, j)) { k = 0 done2 = .false. while (!done2) if (n0 <= k) done2 = .true. else if (strngs(i0 + k) == strngs(vars(VNAMEI, j) + k)) k = k + 1 else done2 = .true. if (k < n0) j = j + 1 else { done2 = .true. done1 = .true. } } else j = j + 1   if (j == numvar + 1) { if (numvar == MAXVAR) { write (*, '(''too many variables'')') stop } numvar = numvar + 1 call addstu (strngs, istrng, strngs, i0, n0, i, n) vars(VNAMEI, numvar) = i vars(VNAMEN, numvar) = n vars(VVALUE, numvar) = 0 fndvar = numvar } else fndvar = j end   function strint (strngs, i, n)   # Convert a string to a non-negative integer.   implicit none   character strngs(STRNSZ) # String pool. integer i, n integer strint   integer j   strint = 0 for (j = 0; j < n; j = j + 1) strint = (10 * strint) + (ichar (strngs(i + j)) - ichar ('0')) end   function logl2i (u)   # Convert LOGICAL to INTEGER.   implicit none   logical u integer logl2i   if (u) logl2i = 1 else logl2i = 0 end   subroutine run (vars, numvar, _ strngs, istrng, _ nodes, frelst, _ outbuf, noutbf, iast)   # Run (interpret) the AST. The algorithm employed is non-recursive.   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer iast # Root node of the AST.   integer fndvar integer logl2i integer nstack integer pop integer strint   integer dstack(STCKSZ) # Data stack. integer idstck # Data stack pointer. integer xstack(STCKSZ) # Execution stack. integer ixstck # Execution stack pointer. integer i integer i0, n0 integer tag integer ivar integer ival1, ival2 integer inode1, inode2   idstck = 1 ixstck = 1 call push (xstack, ixstck, iast) while (nstack (ixstck) != 0) { i = pop (xstack, ixstck) if (i == NIL) tag = NIL else tag = nodes(NTAG, i) if (tag == NIL) continue else if (tag == NDSEQ) { if (nodes(NRIGHT, i) != NIL) call push (xstack, ixstck, nodes(NRIGHT, i)) if (nodes(NLEFT, i) != NIL) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDID) { # Push the value of a variable. i0 = nodes(NITV, i) n0 = nodes(NITN, i) ivar = fndvar (vars, numvar, strngs, istrng, i0, n0) call push (dstack, idstck, vars(VVALUE, ivar)) } else if (tag == NDINT) { # Push the value of an integer literal. i0 = nodes(NITV, i) n0 = nodes(NITN, i) call push (dstack, idstck, strint (strngs, i0, n0)) } else if (tag == NDNEG) { # Evaluate the argument and prepare to negate it. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNEG + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDNEG + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Negate the evaluated argument. ival1 = pop (dstack, idstck) call push (dstack, idstck, -ival1) } else if (tag == NDNOT) { # Evaluate the argument and prepare to NOT it. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNOT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDNOT + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # NOT the evaluated argument. ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 == 0)) } else if (tag == NDAND) { # Evaluate the arguments and prepare to AND them. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDAND + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDAND + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # AND the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, _ logl2i (ival1 != 0 && ival2 != 0)) } else if (tag == NDOR) { # Evaluate the arguments and prepare to OR them. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDOR + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDOR + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # OR the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, _ logl2i (ival1 != 0 || ival2 != 0)) } else if (tag == NDADD) { # Evaluate the arguments and prepare to add them. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDADD + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDADD + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Add the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, ival1 + ival2) } else if (tag == NDSUB) { # Evaluate the arguments and prepare to subtract them. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDSUB + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDSUB + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Subtract the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, ival1 - ival2) } else if (tag == NDMUL) { # Evaluate the arguments and prepare to multiply them. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDMUL + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDMUL + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Multiply the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, ival1 * ival2) } else if (tag == NDDIV) { # Evaluate the arguments and prepare to compute the quotient # after division. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDDIV + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDDIV + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Divide the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, ival1 / ival2) } else if (tag == NDMOD) { # Evaluate the arguments and prepare to compute the # remainder after division. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDMOD + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDMOD + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # MOD the evaluated arguments. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, mod (ival1, ival2)) } else if (tag == NDEQ) { # Evaluate the arguments and prepare to test their equality. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDEQ + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDEQ + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Test for equality. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 == ival2)) } else if (tag == NDNE) { # Evaluate the arguments and prepare to test their # inequality. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDNE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDNE + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Test for inequality. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 != ival2)) } else if (tag == NDLT) { # Evaluate the arguments and prepare to test their # order. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDLT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDLT + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Do the test. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 < ival2)) } else if (tag == NDLE) { # Evaluate the arguments and prepare to test their # order. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDLE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDLE + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Do the test. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 <= ival2)) } else if (tag == NDGT) { # Evaluate the arguments and prepare to test their # order. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDGT + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDGT + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Do the test. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 > ival2)) } else if (tag == NDGE) { # Evaluate the arguments and prepare to test their # order. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDGE + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NRIGHT, i)) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDGE + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Do the test. ival2 = pop (dstack, idstck) ival1 = pop (dstack, idstck) call push (dstack, idstck, logl2i (ival1 >= ival2)) } else if (tag == NDASGN) { # Prepare a new node to do the actual assignment. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDASGN + STAGE2 nodes(NITV, inode1) = nodes(NITV, nodes(NLEFT, i)) nodes(NITN, inode1) = nodes(NITN, nodes(NLEFT, i)) call push (xstack, ixstck, inode1) # Evaluate the expression. call push (xstack, ixstck, nodes(NRIGHT, i)) } else if (tag == NDASGN + STAGE2) { # Do the actual assignment, and free the STAGE2 node. i0 = nodes(NITV, i) n0 = nodes(NITN, i) call frenod (nodes, frelst, i) ival1 = pop (dstack, idstck) ivar = fndvar (vars, numvar, strngs, istrng, i0, n0) vars(VVALUE, ivar) = ival1 } else if (tag == NDIF) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDIF + STAGE2 # The "then" and "else" clauses, respectively: nodes(NLEFT, inode1) = nodes(NLEFT, nodes(NRIGHT, i)) nodes(NRIGHT, inode1) = nodes(NRIGHT, nodes(NRIGHT, i)) call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDIF + STAGE2) { inode1 = nodes(NLEFT, i) # "Then" clause. inode2 = nodes(NRIGHT, i) # "Else" clause. call frenod (nodes, frelst, i) ival1 = pop (dstack, idstck) if (ival1 != 0) call push (xstack, ixstck, inode1) else if (inode2 != NIL) call push (xstack, ixstck, inode2) } else if (tag == NDWHIL) { call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDWHIL + STAGE2 nodes(NLEFT, inode1) = nodes(NRIGHT, i) # Loop body. nodes(NRIGHT, inode1) = i # Top of loop. call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDWHIL + STAGE2) { inode1 = nodes(NLEFT, i) # Loop body. inode2 = nodes(NRIGHT, i) # Top of loop. call frenod (nodes, frelst, i) ival1 = pop (dstack, idstck) if (ival1 != 0) { call push (xstack, ixstck, inode2) # Top of loop. call push (xstack, ixstck, inode1) # The body. } } else if (tag == NDPRTS) { # Print a string literal. (String literals occur only--and # always--within Prts nodes; therefore one need not devise a # way push strings to the stack.) i0 = nodes(NITV, nodes(NLEFT, i)) n0 = nodes(NITN, nodes(NLEFT, i)) call wrtstr (outbuf, noutbf, strngs, i0, n0) } else if (tag == NDPRTC) { # Evaluate the argument and prepare to print it. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDPRTC + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDPRTC + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Print the evaluated argument. ival1 = pop (dstack, idstck) call wrtchr (outbuf, noutbf, char (ival1)) } else if (tag == NDPRTI) { # Evaluate the argument and prepare to print it. call newnod (nodes, frelst, inode1) nodes(NTAG, inode1) = NDPRTI + STAGE2 call push (xstack, ixstck, inode1) call push (xstack, ixstck, nodes(NLEFT, i)) } else if (tag == NDPRTI + STAGE2) { # Free the STAGE2 node. call frenod (nodes, frelst, i) # Print the evaluated argument. ival1 = pop (dstack, idstck) call wrtint (outbuf, noutbf, ival1) } } end   #---------------------------------------------------------------------   program interp   implicit none   integer vars(VARSZ, MAXVAR) # Variables. integer numvar # Number of variables. character strngs(STRNSZ) # String pool. integer istrng # String pool's next slot. integer nodes (NODESZ, NODSSZ) # Nodes pool. integer frelst # Head of the free list. character outbuf(OUTLSZ) # Output line buffer. integer noutbf # Number of characters in outbuf. integer iast # Root node of the AST.   numvar = 0 istrng = 1 noutbf = 0   call initnd (nodes, frelst) call rdast (strngs, istrng, nodes, frelst, iast)   call run (vars, numvar, _ strngs, istrng, _ nodes, frelst, _ outbuf, noutbf, iast)   if (noutbf != 0) call flushl (outbuf, noutbf) end   ######################################################################
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Fortran
Fortran
  program demo_sort_indexed implicit none   call print_sorted_by_length( [character(len=20) :: "shorter","longer"] ) call print_sorted_by_length( [character(len=20) :: "abcd","123456789","abcdef","1234567"] ) call print_sorted_by_length( [character(len=20) :: 'the','quick','brown','fox','jumps','over','the','lazy','dog'])   contains   subroutine print_sorted_by_length(list) character(len=*) :: list(:) integer :: i   list(sort_int(len_trim(list)))=list ! sort by length from small to large write(*,'(i9,1x,a)')(len_trim(list(i)), list(i),i=size(list),1,-1)! print from last to first write(*,*)   end subroutine print_sorted_by_length   function sort_int(input) result(counts) ! **very** inefficient mini index sort integer :: input(:), counts(size(input)), i counts=[(count(input(i) > input)+count(input(i) == input(:i)),i=1, size(input) )] end function sort_int   end program demo_sort_indexed  
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Julia
Julia
struct ASTnode nodetype::Int left::Union{Nothing, ASTnode} right::Union{Nothing, ASTnode} value::Union{Nothing, Int, String} end   function syntaxanalyzer(inputfile) tkEOI, tkMul, tkDiv, tkMod, tkAdd, tkSub, tkNegate, tkNot, tkLss, tkLeq, tkGtr, tkGeq, tkEql, tkNeq, tkAssign, tkAnd, tkOr, tkIf, tkElse, tkWhile, tkPrint, tkPutc, tkLparen, tkRparen, tkLbrace, tkRbrace, tkSemi, tkComma, tkIdent, tkInteger, tkString = collect(1:31)   ndIdent, ndString, ndInteger, ndSequence, ndIf, ndPrtc, ndPrts, ndPrti, ndWhile, ndAssign, ndNegate, ndNot, ndMul, ndDiv, ndMod, ndAdd, ndSub, ndLss, ndLeq, ndGtr, ndGeq, ndEql, ndNeq, ndAnd, ndOr = collect(1:25)   TK_NAME, TK_RIGHT_ASSOC, TK_IS_BINARY, TK_IS_UNARY, TK_PRECEDENCE, TK_NODE = collect(1:6) # label Token columns Tokens = [ ["EOI" , false, false, false, -1, -1 ], ["*" , false, true, false, 13, ndMul ], ["/" , false, true, false, 13, ndDiv ], ["%" , false, true, false, 13, ndMod ], ["+" , false, true, false, 12, ndAdd ], ["-" , false, true, false, 12, ndSub ], ["-" , false, false, true, 14, ndNegate ], ["!" , false, false, true, 14, ndNot ], ["<" , false, true, false, 10, ndLss ], ["<=" , false, true, false, 10, ndLeq ], [">" , false, true, false, 10, ndGtr ], [">=" , false, true, false, 10, ndGeq ], ["==" , false, true, false, 9, ndEql ], ["!=" , false, true, false, 9, ndNeq ], ["=" , false, false, false, -1, ndAssign ], ["&&" , false, true, false, 5, ndAnd ], ["||" , false, true, false, 4, ndOr ], ["if" , false, false, false, -1, ndIf ], ["else" , false, false, false, -1, -1 ], ["while" , false, false, false, -1, ndWhile ], ["print" , false, false, false, -1, -1 ], ["putc" , false, false, false, -1, -1 ], ["(" , false, false, false, -1, -1 ], [")" , false, false, false, -1, -1 ], ["{" , false, false, false, -1, -1 ], ["}" , false, false, false, -1, -1 ], [";" , false, false, false, -1, -1 ], ["," , false, false, false, -1, -1 ], ["Ident" , false, false, false, -1, ndIdent ], ["Integer literal" , false, false, false, -1, ndInteger], ["String literal" , false, false, false, -1, ndString ]]   allsyms = Dict( "End_of_input" => tkEOI, "Op_multiply" => tkMul, "Op_divide" => tkDiv, "Op_mod" => tkMod, "Op_add" => tkAdd, "Op_subtract" => tkSub, "Op_negate" => tkNegate, "Op_not" => tkNot, "Op_less" => tkLss, "Op_lessequal" => tkLeq, "Op_greater" => tkGtr, "Op_greaterequal" => tkGeq, "Op_equal" => tkEql, "Op_notequal" => tkNeq, "Op_assign" => tkAssign, "Op_and" => tkAnd, "Op_or" => tkOr, "Keyword_if" => tkIf, "Keyword_else" => tkElse, "Keyword_while" => tkWhile, "Keyword_print" => tkPrint, "Keyword_putc" => tkPutc, "LeftParen" => tkLparen, "RightParen" => tkRparen, "LeftBrace" => tkLbrace, "RightBrace" => tkRbrace, "Semicolon" => tkSemi, "Comma" => tkComma, "Identifier" => tkIdent, "Integer" => tkInteger, "String" => tkString)   displaynodes = ["Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or"]   errline, errcol, tok, toktext = fill("", 4) error(msg) = throw("Error in syntax: $msg.") nilnode = ASTnode(0, nothing, nothing, nothing) tokother = ""   function gettok() s = readline(inputfile) if length(s) == 0 error("empty line") end linelist = split(strip(s), r"\s+", limit = 4) # line col Ident varname # 0 1 2 3 errline, errcol, toktext = linelist[1:3] if !haskey(allsyms, toktext) error("Unknown token $toktext") end tok = allsyms[toktext] tokother = (tok in [tkInteger, tkIdent, tkString]) ? linelist[4] : "" end   makenode(oper, left, right = nilnode) = ASTnode(oper, left, right, nothing) makeleaf(oper, n::Int) = ASTnode(oper, nothing, nothing, n) makeleaf(oper, n) = ASTnode(oper, nothing, nothing, string(n)) expect(msg, s) = if tok != s error("msg: Expecting $(Tokens[s][TK_NAME]), found $(Tokens[tok][TK_NAME])") else gettok() end   function expr(p) x = nilnode if tok == tkLparen x = parenexpr() elseif tok in [tkSub, tkAdd] op = tok == tkSub ? tkNegate : tkAdd gettok() node = expr(Tokens[tkNegate][TK_PRECEDENCE]) x = (op == tkNegate) ? makenode(ndNegate, node) : node elseif tok == tkNot gettok() x = makenode(ndNot, expr(Tokens[tkNot][TK_PRECEDENCE])) elseif tok == tkIdent x = makeleaf(ndIdent, tokother) gettok() elseif tok == tkInteger x = makeleaf(ndInteger, tokother) gettok() else error("Expecting a primary, found: $(Tokens[tok][TK_NAME])") end while Tokens[tok][TK_IS_BINARY] && (Tokens[tok][TK_PRECEDENCE] >= p) op = tok gettok() q = Tokens[op][TK_PRECEDENCE] if !Tokens[op][TK_RIGHT_ASSOC] q += 1 end node = expr(q) x = makenode(Tokens[op][TK_NODE], x, node) end x end   parenexpr() = (expect("paren_expr", tkLparen); node = expr(0); expect("paren_expr", tkRparen); node)   function stmt() t = nilnode if tok == tkIf gettok() e = parenexpr() s = stmt() s2 = nilnode if tok == tkElse gettok() s2 = stmt() end t = makenode(ndIf, e, makenode(ndIf, s, s2)) elseif tok == tkPutc gettok() e = parenexpr() t = makenode(ndPrtc, e) expect("Putc", tkSemi) elseif tok == tkPrint gettok() expect("Print", tkLparen) while true if tok == tkString e = makenode(ndPrts, makeleaf(ndString, tokother)) gettok() else e = makenode(ndPrti, expr(0)) end t = makenode(ndSequence, t, e) if tok != tkComma break end gettok() end expect("Print", tkRparen) expect("Print", tkSemi) elseif tok == tkSemi gettok() elseif tok == tkIdent v = makeleaf(ndIdent, tokother) gettok() expect("assign", tkAssign) e = expr(0) t = makenode(ndAssign, v, e) expect("assign", tkSemi) elseif tok == tkWhile gettok() e = parenexpr() s = stmt() t = makenode(ndWhile, e, s) elseif tok == tkLbrace gettok() while (tok != tkRbrace) && (tok != tkEOI) t = makenode(ndSequence, t, stmt()) end expect("Lbrace", tkRbrace) elseif tok != tkEOI error("Expecting start of statement, found: $(Tokens[tok][TK_NAME])") end return t end   function parse() t = nilnode gettok() while true t = makenode(ndSequence, t, stmt()) if (tok == tkEOI) || (t == nilnode) break end end t end   function prtASTnode(t) if t == nothing return elseif t == nilnode println(";") elseif t.nodetype in [ndIdent, ndInteger, ndString] println(rpad(displaynodes[t.nodetype], 14), t.value) else println(rpad(displaynodes[t.nodetype], 14)) end prtASTnode(t.left) prtASTnode(t.right) end   # runs the function prtASTnode(parse()) end   testtxt = """ 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String \"count is: \" 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String \"\\n\" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input """   syntaxanalyzer(IOBuffer(testtxt)) # for isolated testing   # syntaxanalyzer(length(ARGS) > 1 ? ARGS[1] : stdin) # for use as in the Python code  
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Chapel
Chapel
  config const gridHeight: int = 3; config const gridWidth: int = 3;   enum State { dead = 0, alive = 1 };   class ConwaysGameofLife {   var gridDomain: domain(2); var computeDomain: subdomain( gridDomain ); var grid: [gridDomain] int;   proc ConwaysGameofLife( height: int, width: int ) { this.gridDomain = {0..#height+2, 0..#width+2}; this.computeDomain = this.gridDomain.expand( -1 ); }   proc step(){   var tempGrid: [this.computeDomain] State; forall (i,j) in this.computeDomain { var isAlive = this.grid[i,j] == State.alive; var numAlive = (+ reduce this.grid[ i-1..i+1, j-1..j+1 ]) - if isAlive then 1 else 0; tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then State.alive else State.dead ; }   this.grid[this.computeDomain] = tempGrid;   }   proc this( i: int, j: int ) ref : State { return this.grid[i,j]; }   proc prettyPrint(): string { var str: string; for i in this.gridDomain.dim(1) { if i == 0 || i == gridDomain.dim(1).last { for j in this.gridDomain.dim(2) { str += "-"; } } else { for j in this.gridDomain.dim(2) { if j == 0 || j == this.gridDomain.dim(2).last { str += "|"; } else { str += if this.grid[i,j] == State.alive then "#" else " "; } } } str += "\n"; } return str; }   }   proc main{ var game = new ConwaysGameofLife( gridHeight, gridWidth ); game[gridHeight/2 + 1, gridWidth/2 ] = State.alive; game[gridHeight/2 + 1, gridWidth/2 + 1 ] = State.alive; game[gridHeight/2 + 1, gridWidth/2 + 2 ] = State.alive; for i in 1..3 { writeln( game.prettyPrint() ); game.step(); } }  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Plain_English
Plain English
A cartesian point is a record with an x coord and a y coord.
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Pop11
Pop11
uses objectclass; define :class Point; slot x = 0; slot y = 0; enddefine;
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Zig
Zig
const std = @import("std");   const debug = std.debug; const mem = std.mem;   test "copy a string" { const source = "A string.";   // Variable `dest1` will have the same type as `source`, which is // `*const [9:0]u8`. const dest1 = source;   // Variable `dest2`'s type is [9]u8. // // The difference between the two is that `dest1` string is null-terminated, // while `dest2` is not. var dest2: [source.len]u8 = undefined; mem.copy(u8, dest2[0..], source[0..]);   debug.assert(mem.eql(u8, dest1[0..], "A string.")); debug.assert(mem.eql(u8, dest2[0..], "A string.")); }
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
"abc".copy() // noop
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zonnon
zonnon
  module Main; var s,r: string; c: array 60 of char; begin s := "plain string";r := s; writeln(s); (* copy string to array of char *) copy(s,c);c[0] := 'P'; (* copy array of char to string *) copy(c,r);writeln(r); end Main.  
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once. There are several possible approaches to accomplish this. Here are two possible algorithms. 1) Generate random pairs of integers and filter out those that don't satisfy this condition: 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . 2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set.
#SystemVerilog
SystemVerilog
program main;   bit [39:0] bitmap [40];   class Point; rand bit signed [4:0] x; rand bit signed [4:0] y;   constraint on_circle_edge { (10*10) <= (x*x + y*y); (x*x + y*y) <= (15*15); };   function void do_point(); randomize; bitmap[x+20][y+20] = 1; endfunction endclass   initial begin Point p = new; repeat (100) p.do_point; foreach (bitmap[row]) $display( "%b", bitmap[row]); end   endprogram
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#AutoIt
AutoIt
If <expression> Then statements ... [ElseIf expression-n Then [elseif statements ... ]] ... [Else [else statements] ... EndIf  
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#Factor
Factor
USING: accessors grouping io kernel math regexp sequences splitting strings unicode ;   : numeric ( str -- new-str ) R/ [1-9][0-9]*/ first-match >string ;   : commas ( numeric-str period separator -- str ) [ reverse ] [ group ] [ reverse join reverse ] tri* ;   : (commatize) ( text from period separator -- str ) [ cut dup numeric dup ] 2dip commas replace append ;   : commatize* ( text from period separator -- str ) reach [ digit? ] any? [ (commatize) ] [ 3drop ] if ;   : commatize ( text -- str ) 0 3 "," commatize* ;   "pi=3.14159265358979323846264338327950288419716939937510582097494459231" 5 5 " " commatize* print   "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." 0 3 "." commatize* print   { "\"-in Aus$+1411.8millions\"" "===US$0017440 millions=== (in 2000 dollars)" "123.e8000 is pretty big." "The land area of the earth is 57268900(29% of the surface) square miles." "Ain't no numbers in this here words, nohow, no way, Jose." "James was never known as 0000000007" "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." " $-140000±100 millions." "6/9/1946 was a good year for some." } [ commatize print ] each
http://rosettacode.org/wiki/Commatizing_numbers
Commatizing numbers
Commatizing   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string. Task Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string. Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines. The number may be part of a larger (non-numeric) string such as:   «US$1744 millions»       ──or──   ±25000 motes. The string may possibly not have a number suitable for commatizing, so it should be untouched and no error generated. If any argument (option) is invalid, nothing is changed and no error need be generated (quiet execution, no fail execution).   Error message generation is optional. The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000 Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882 Any   period   (.)   in a number is assumed to be a   decimal point. The original string is never changed   except   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all. To wit, the following should be preserved:   leading signs (+, -)       ── even superfluous signs   leading/trailing/embedded blanks, tabs, and other whitespace   the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002 Any exponent character(s) should be supported:   1247e12   57256.1D-4   4444^60   7500∙10**35   8500x10**35   9500↑35   +55000↑3   1000**100   2048²   409632   10000pow(pi) Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24). The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (,) character. The   period length   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   period length   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3. E.G.:   in this example, the   period length   is five:   56789,12340,14148 The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1. The character strings below may be placed in a file (and read) or stored as simple strings within the program. Strings to be used as a minimum The value of   pi   (expressed in base 10)   should be separated with blanks every   5   places past the decimal point, the Zimbabwe dollar amount should use a decimal point for the "comma" separator:   pi=3.14159265358979323846264338327950288419716939937510582097494459231   The author has two Z$100000000000000 Zimbabwe notes (100 trillion).   "-in Aus$+1411.8millions"   ===US$0017440 millions=== (in 2000 dollars)   123.e8000 is pretty big.   The land area of the earth is 57268900(29% of the surface) square miles.   Ain't no numbers in this here words, nohow, no way, Jose.   James was never known as 0000000007   Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.   ␢␢␢$-140000±100 millions.   6/9/1946 was a good year for some. where the penultimate string has three leading blanks   (real blanks are to be used). Also see The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.
#FreeBASIC
FreeBASIC
Sub commatize(s As String, sep As String = ",", start As Byte = 1, paso As Byte = 3) Dim As Integer l = Len(s) For i As Integer = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j As Integer =i+1 To l+1 If j>l Then For k As Integer = j-1-paso To i Step -paso s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k As Integer = j-1-paso To i Step -paso s = Mid(s, 1, k) + sep + Mid(s, k+1, l-k+1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Print s End Sub   commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231"," ",6,5) commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",".") commatize("\'-in Aus$+1411.8millions\'",",") commatize("===US$0017440 millions=== (in 2000 dollars)") commatize("123.e8000 is pretty big.") commatize("The land area of the earth is 57268900(29% of the surface) square miles.") commatize("Ain't no numbers in this here words, nohow, no way, Jose.") commatize("James was never known as 0000000007") commatize("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.") commatize(" $-140000±100 millions.") commatize("6/9/1946 was a good year for some.")   Sleep
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_W
ALGOL W
 % returns true if all elements of the string array a are equal, false otherwise %  % As Algol W procedures cannot determine the bounds of an array, the bounds  %  % must be specified in lo and hi  % logical procedure allStringsEqual ( string(256) array a ( * )  ; integer value lo, hi ) ; begin logical same; integer listPos; same  := true; listPos := lo + 1; while same and listPos <= hi do begin same  := a( lo ) = a( listPos ); listPos := listPos + 1 end; same end allStringsEqual ;    % returns true if the elements of the string array a are in ascending order,  %  % false otherwise  %  % As Algol W procedures cannot determine the bounds of an array, the bounds  %  % must be specified in lo and hi  % logical procedure ascendingOrder ( string(256) array a ( * )  ; integer value lo, hi ) ; begin logical ordered; integer listPos; ordered := true; listPos := lo + 1; while ordered and listPos <= hi do begin ordered := a( listPos - 1 ) < a( listPos ); listPos := listPos + 1 end; ordered end ascendingOrder ;
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AppleScript
AppleScript
-- allEqual :: [String] -> Bool on allEqual(xs) _and(zipWith(my _equal, xs, rest of xs)) end allEqual   -- azSorted :: [String] -> Bool on azSorted(xs) _and(zipWith(my azBeforeOrSame, xs, rest of xs)) end azSorted   -- _equal :: a -> a -> Bool on _equal(a, b) a = b end _equal   -- azBefore :: String -> String -> Bool on azBeforeOrSame(a, b) a ≥ b end azBeforeOrSame   -- _and :: [a] -> Bool on _and(xs) foldr(_equal, true, xs) end _and     -- TEST on run set lstA to ["isiZulu", "isiXhosa", "isiNdebele", "Xitsonga", "Tshivenda", ¬ "Setswana", "Sesotho sa Leboa", "Sesotho", "English", "Afrikaans"]   set lstB to ["Afrikaans", "English", "Sesotho", "Sesotho sa Leboa", "Setswana", ¬ "Tshivenda", "Xitsonga", "isiNdebele", "isiXhosa", "isiZulu"]   set lstC to ["alpha", "alpha", "alpha", "alpha", "alpha", "alpha", "alpha", ¬ "alpha", "alpha", "alpha"]     {allEqual:map(allEqual, [lstA, lstB, lstC]), azSorted:map(azSorted, [lstA, lstB, lstC])}   -- > {allEqual:{false, false, true}, azSorted:{false, true, true}} end run       -- GENERIC FUNCTIONS   -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to lambda(v, item i of xs, i, xs) end repeat return v end tell end foldr   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to lambda(item i of xs, i, xs) end repeat return lst end tell end map   -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set nx to length of xs set ny to length of ys if nx < 1 or ny < 1 then {} else set lng to cond(nx < ny, nx, ny) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to lambda(item i of xs, item i of ys) end repeat return lst end tell end if end zipWith   -- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) on cond(bool, f, g) if bool then f else g end if end cond   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property lambda : f end script end if end mReturn
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#ALGOL_68
ALGOL 68
BEGIN # implement C-like getchar, where EOF and EOLn are "characters" (-1 and 10 resp.). # INT eof = -1, eoln = 10; BOOL eof flag := FALSE; STRING buf := ""; INT col := 1; INT line := 0; on logical file end (stand in, (REF FILE f)BOOL: eof flag := TRUE); PROC getchar = INT: IF eof flag THEN eof ELIF col = UPB buf THEN col +:= 1; eoln ELIF col > UPB buf THEN IF line > 0 THEN read(newline) FI; line +:= 1; read(buf); IF eof flag THEN col := 1; eof ELSE col := 0; getchar FI ELSE col +:= 1; ABS buf[col] FI; PROC nextchar = INT: IF eof flag THEN eof ELIF col >= UPB buf THEN eoln ELSE ABS buf[col+1] FI;   PROC is blank = (INT ch) BOOL: ch = 0 OR ch = 9 OR ch = 10 OR ch = 13 OR ch = ABS " "; PROC is digit = (INT ch) BOOL: ch >= ABS "0" AND ch <= ABS "9"; PROC is ident start = (INT ch) BOOL: ch >= ABS "A" AND ch <= ABS "Z" OR ch >= ABS "a" AND ch <= ABS "z" OR ch = ABS "_"; PROC is ident = (INT ch) BOOL: is ident start(ch) OR is digit(ch);   PROC ident or keyword = (INT start char) VOID: BEGIN STRING w := REPR start char; INT start col = col; WHILE is ident (next char) DO w +:= REPR getchar OD; IF w = "if" THEN output2("Keyword_if", start col) ELIF w = "else" THEN output2("Keyword_else", start col) ELIF w = "while" THEN output2("Keyword_while", start col) ELIF w = "print" THEN output2("Keyword_print", start col) ELIF w = "putc" THEN output2("Keyword_putc", start col) ELSE output2("Identifier " + w, start col) FI END; PROC char = VOID: BEGIN INT start col = col; INT ch := getchar; IF ch = ABS "'" THEN error("Empty character constant") ELIF ch = ABS "\" THEN ch := getchar; IF ch = ABS "n" THEN ch := 10 ELIF ch = ABS "\" THEN SKIP ELSE error("Unknown escape sequence. \" + REPR ch) FI FI; IF nextchar /= ABS "'" THEN error("Multi-character constant.") FI; getchar; output2("Integer " + whole(ch, 0), start col) END; PROC string = VOID: BEGIN INT start col = col; STRING s := """"; WHILE INT ch := getchar; ch /= ABS """" DO IF ch = eoln THEN error("End-of-line while scanning string literal. Closing string character not found before end-of-line.") ELIF ch = eof THEN error("End-of-file while scanning string literal. Closing string character not found.") ELIF ch = ABS "\" THEN s +:= REPR ch; ch := getchar; IF ch /= ABS "\" AND ch /= ABS "n" THEN error("Unknown escape sequence. \" + REPR ch) FI; s +:= REPR ch ELSE s +:= REPR ch FI OD; output2("String " + s + """", start col) END; PROC comment = VOID: BEGIN WHILE INT ch := getchar; NOT (ch = ABS "*" AND nextchar = ABS "/") DO IF ch = eof THEN error("End-of-file in comment. Closing comment characters not found.") FI OD; getchar END; PROC number = (INT first digit) VOID: BEGIN INT start col = col; INT n := first digit - ABS "0"; WHILE is digit (nextchar) DO INT u := getchar - ABS "0"; IF LENG n * 10 + LENG u > max int THEN error("Integer too big") FI; n := n * 10 + u OD; IF is ident start (nextchar) THEN error("Invalid number. Starts like a number, but ends in non-numeric characters.") FI; output2("Integer " + whole(n, 0), start col) END;   PROC output = (STRING s) VOID: output2(s, col); PROC output2 = (STRING s, INT col) VOID: print((whole(line,-8), whole(col,-8), " ", s, newline));   PROC if follows = (CHAR second, STRING longer, shorter) VOID: IF nextchar = ABS second THEN output(longer); getchar ELSE output(shorter) FI; PROC error = (STRING s)VOID: (put(stand error, ("At ", whole(line,0), ":", whole(col,0), " ", s, new line)); stop); PROC unrecognized = (INT char) VOID: error("Unrecognized character " + REPR char); PROC double char = (INT first, STRING op) VOID: IF nextchar /= first THEN unrecognized(first) ELSE output2(op, col-1); getchar FI;   WHILE INT ch := getchar; ch /= eof DO IF is blank(ch) THEN SKIP ELIF ch = ABS "(" THEN output("LeftParen") ELIF ch = ABS ")" THEN output("RightParen") ELIF ch = ABS "{" THEN output("LeftBrace") ELIF ch = ABS "}" THEN output("RightBrace") ELIF ch = ABS ";" THEN output("Semicolon") ELIF ch = ABS "," THEN output("Comma") ELIF ch = ABS "*" THEN output("Op_multiply") ELIF ch = ABS "/" THEN IF next char = ABS "*" THEN comment ELSE output("Op_divide") FI ELIF ch = ABS "%" THEN output("Op_mod") ELIF ch = ABS "+" THEN output("Op_add") ELIF ch = ABS "-" THEN output("Op_subtract") ELIF ch = ABS "<" THEN if follows("=", "Op_lessequal", "Op_less") ELIF ch = ABS ">" THEN if follows("=", "Op_greaterequal", "Op_greater") ELIF ch = ABS "=" THEN if follows("=", "Op_equal", "Op_assign") ELIF ch = ABS "!" THEN if follows("=", "Op_notequal", "Op_not") ELIF ch = ABS "&" THEN double char(ch, "Op_and") ELIF ch = ABS "|" THEN double char(ch, "Op_or") ELIF is ident start (ch) THEN ident or keyword (ch) ELIF ch = ABS """" THEN string ELIF ch = ABS "'" THEN char ELIF is digit(ch) THEN number(ch) ELSE unrecognized(ch) FI OD; output("End_Of_Input") END
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Aime
Aime
integer i;   i = 0; while (i < argc()) { o_text(argv(i)); o_byte('\n'); i += 1; }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#ALGOL_68
ALGOL 68
main:( FOR i TO argc DO printf(($"the argument #"g(-0)" is "gl$, i, argv(i))) OD )
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#6502_Assembly
6502 Assembly
nop  ; comments begin with a semicolon
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#68000_Assembly
68000 Assembly
MOVEM.L D0-D7/A0-A6,-(SP) ;push all registers onto the stack
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Input format: Given the following program: count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } The output from the Code generator is a virtual assembly code program: Output from gen, input to VM Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt The first line of the input specifies the datasize required and the number of constant strings, in the order that they are reference via the code. The data can be stored in a separate array, or the data can be stored at the beginning of the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if referenced at address 2. If there are one or more constant strings, they come next. The code refers to these strings by their index. The index starts at 0. So if there are 3 strings, and the code wants to reference the 3rd string, 2 will be used. Next comes the actual virtual assembly code. The first number is the code address of that instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. Registers: sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data: data string pool Instructions: Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not Print the word at stack top as a character. prtc Print the word at stack top as an integer. prti Stack top points to an index into the string pool. Print that entry. prts Unconditional stop. halt A simple example virtual machine def run_vm(data_size) int stack[data_size + 1000] set stack[0..data_size - 1] to 0 int pc = 0 while True: op = code[pc] pc += 1   if op == FETCH: stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]); pc += word_size elif op == STORE: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task AST Interpreter task
#Icon
Icon
# -*- Icon -*- # # The Rosetta Code virtual machine in Icon. Migrated from the # ObjectIcon. # # See https://rosettacode.org/wiki/Compiler/virtual_machine_interpreter #   record VirtualMachine(code, global_data, strings, stack, pc)   global opcode_names global opcode_values global op_halt global op_add global op_sub global op_mul global op_div global op_mod global op_lt global op_gt global op_le global op_ge global op_eq global op_ne global op_and global op_or global op_neg global op_not global op_prtc global op_prti global op_prts global op_fetch global op_store global op_push global op_jmp global op_jz   global whitespace_chars   procedure main(args) local f_inp, f_out local vm   whitespace_chars := ' \t\n\r\f\v' initialize_opcodes()   if 3 <= *args then { write("Usage: ", &progname, " [INPUT_FILE [OUTPUT_FILE]]") exit(1) }   if 1 <= *args then { f_inp := open(args[1], "r") | { write(&errout, "Failed to open ", args[1], " for reading.") exit(1) } } else { f_inp := &input }   if 2 <= *args then { f_out := open(args[2], "w") | { write(&errout, "Failed to open ", args[2], " for writing.") exit(1) } } else { f_out := &output }   vm := VirtualMachine() read_assembly_code(f_inp, vm) run_vm(f_out, vm) end   procedure initialize_opcodes() local i   opcode_names := ["halt", "add", "sub", "mul", "div", "mod", "lt", "gt", "le", "ge", "eq", "ne", "and", "or", "neg", "not", "prtc", "prti", "prts", "fetch", "store", "push", "jmp", "jz"]   opcode_values := table() every i := 1 to *opcode_names do opcode_values[opcode_names[i]] := char(i)   op_halt := opcode_values["halt"] op_add := opcode_values["add"] op_sub := opcode_values["sub"] op_mul := opcode_values["mul"] op_div := opcode_values["div"] op_mod := opcode_values["mod"] op_lt := opcode_values["lt"] op_gt := opcode_values["gt"] op_le := opcode_values["le"] op_ge := opcode_values["ge"] op_eq := opcode_values["eq"] op_ne := opcode_values["ne"] op_and := opcode_values["and"] op_or := opcode_values["or"] op_neg := opcode_values["neg"] op_not := opcode_values["not"] op_prtc := opcode_values["prtc"] op_prti := opcode_values["prti"] op_prts := opcode_values["prts"] op_fetch := opcode_values["fetch"] op_store := opcode_values["store"] op_push := opcode_values["push"] op_jmp := opcode_values["jmp"] op_jz := opcode_values["jz"] end   procedure int2bytes (n) local bytes   # The VM is little-endian.   bytes := "****" bytes[1] := char (iand(n, 16rFF)) bytes[2] := char(iand(ishift(n, -8), 16rFF)) bytes[3] := char(iand(ishift(n, -16), 16rFF)) bytes[4] := char(iand(ishift(n, -24), 16rFF)) return bytes end   procedure bytes2int(bytes, i) local n0, n1, n2, n3, n   # The VM is little-endian.   n0 := ord(bytes[i]) n1 := ishift(ord(bytes[i + 1]), 8) n2 := ishift(ord(bytes[i + 2]), 16) n3 := ishift(ord(bytes[i + 3]), 24) n := ior (n0, ior (n1, ior (n2, n3)))   # Do not forget to extend the sign bit. return (if n3 <= 16r7F then n else ior(n, icom(16rFFFFFFFF))) end   procedure read_assembly_code(f, vm) local data_size, number_of_strings local line, ch local i local address local opcode   # Read the header line. line := read(f) | bad_vm() line ? { tab(many(whitespace_chars)) tab(match("Datasize")) | bad_vm() tab(many(whitespace_chars)) tab(any(':')) | bad_vm() tab(many(whitespace_chars)) data_size := integer(tab(many(&digits))) | bad_vm() tab(many(whitespace_chars)) tab(match("Strings")) | bad_vm() tab(many(whitespace_chars)) tab(any(':')) | bad_vm() tab(many(whitespace_chars)) number_of_strings := integer(tab(many(&digits))) | bad_vm() }   # Read the strings. vm.strings := list(number_of_strings) every i := 1 to number_of_strings do { vm.strings[i] := "" line := read(f) | bad_vm() line ? { tab(many(whitespace_chars)) tab(any('"')) | bad_vm() while ch := tab(any(~'"')) do { if ch == '\\' then { ch := tab(any('n\\')) | bad_vm() vm.strings[i] ||:= (if (ch == "n") then "\n" else "\\") } else { vm.strings[i] ||:= ch } } } }   # Read the code. vm.code := "" while line := read(f) do { line ? { tab(many(whitespace_chars)) address := integer(tab(many(&digits))) | bad_vm() tab(many(whitespace_chars)) opcode := tab(many(~whitespace_chars)) | bad_vm() vm.code ||:= opcode_values[opcode] case opcode of { "push": { tab(many(whitespace_chars)) vm.code ||:= int2bytes(integer(tab(many(&digits)))) | int2bytes(integer(tab(any('-')) || tab(many(&digits)))) | bad_vm() } "fetch" | "store": { tab(many(whitespace_chars)) tab(any('[')) | bad_vm() tab(many(whitespace_chars)) vm.code ||:= int2bytes(integer(tab(many(&digits)))) | bad_vm() tab(many(whitespace_chars)) tab(any(']')) | bad_vm() } "jmp" | "jz": { tab(many(whitespace_chars)) tab(any('(')) | bad_vm() tab(many(whitespace_chars)) vm.code ||:= int2bytes(integer(tab(many(&digits)))) | int2bytes(integer(tab(any('-')) || tab(many(&digits)))) | bad_vm() tab(many(whitespace_chars)) tab(any(')')) | bad_vm() tab(many(whitespace_chars)) tab(many(&digits)) | bad_vm() } default: { # Do nothing } } } }   # Create a global data area. vm.global_data := list(data_size, &null)   initialize_vm(vm) end   procedure run_vm(f_out, vm) initialize_vm(vm) continue_vm(f_out, vm) end   procedure continue_vm(f_out, vm) while vm.code[vm.pc] ~== op_halt do step_vm(f_out, vm) end   procedure step_vm(f_out, vm) local opcode   opcode := vm.code[vm.pc] vm.pc +:= 1 case opcode of { op_add: binop(vm, "+") op_sub: binop(vm, "-") op_mul: binop(vm, "*") op_div: binop(vm, "/") op_mod: binop(vm, "%") op_lt: comparison(vm, "<") op_gt: comparison(vm, ">") op_le: comparison(vm, "<=") op_ge: comparison(vm, ">=") op_eq: comparison(vm, "=") op_ne: comparison(vm, "~=") op_and: logical_and(vm) op_or: logical_or(vm) op_neg: negate(vm) op_not: logical_not(vm) op_prtc: printc(f_out, vm) op_prti: printi(f_out, vm) op_prts: prints(f_out, vm) op_fetch: fetch_global(vm) op_store: store_global(vm) op_push: push_argument(vm) op_jmp: jump(vm) op_jz: jump_if_zero(vm) default: bad_opcode() } end   procedure negate(vm) vm.stack[1] := -vm.stack[1] end   procedure binop(vm, func) vm.stack[2] := func(vm.stack[2], vm.stack[1]) pop(vm.stack) end   procedure comparison(vm, func) vm.stack[2] := (if func(vm.stack[2], vm.stack[1]) then 1 else 0) pop(vm.stack) end   procedure logical_and(vm) vm.stack[2] := (if vm.stack[2] ~= 0 & vm.stack[1] ~= 0 then 1 else 0) pop(vm.stack) end   procedure logical_or(vm) vm.stack[2] := (if vm.stack[2] ~= 0 | vm.stack[1] ~= 0 then 1 else 0) pop(vm.stack) end   procedure logical_not(vm) vm.stack[1] := (if vm.stack[1] ~= 0 then 0 else 1) end   procedure printc(f_out, vm) writes(f_out, char(pop(vm.stack))) end   procedure printi(f_out, vm) writes(f_out, pop(vm.stack)) end   procedure prints(f_out, vm) writes(f_out, vm.strings[pop(vm.stack) + 1]) end   procedure fetch_global(vm) push(vm.stack, vm.global_data[get_argument(vm) + 1]) vm.pc +:= 4 end   procedure store_global(vm) vm.global_data[get_argument(vm) + 1] := pop(vm.stack) vm.pc +:= 4 end   procedure push_argument(vm) push(vm.stack, get_argument(vm)) vm.pc +:= 4 end   procedure jump(vm) vm.pc +:= get_argument(vm) end   procedure jump_if_zero(vm) if pop(vm.stack) = 0 then vm.pc +:= get_argument(vm) else vm.pc +:= 4 end   procedure get_argument(vm) return bytes2int(vm.code, vm.pc) end   procedure initialize_vm(vm) # The program counter starts at 1, for convenient indexing into # the code[] array. Icon indexing starts at 1 (for a *very* good # reason, but that’s a topic for another day). vm.pc := 1 vm.stack := [] end   procedure bad_vm() write(&errout, "Bad VM.") exit(1) end   procedure bad_opcode() write(&errout, "Bad opcode.") exit(1) end
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Virtual machine interpreter. The output is in text format, and represents virtual assembly code. The program should read input from a file and/or stdin, and write output to a file and/or stdout. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast while.ast can be input into the code generator. The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. Run as: lex < while.t | parse | gen Input to lex Output from lex, input to parse Output from parse Output from gen, input to VM count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Datasize: 1 Strings: 2 "count is: " "\n" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt Input format As shown in the table, above, the output from the syntax analyzer is a flattened AST. In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. Loading this data into an internal parse tree should be as simple as:   def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" return None   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right)   Output format - refer to the table above The first line is the header: Size of data, and number of constant strings. size of data is the number of 32-bit unique variables used. In this example, one variable, count number of constant strings is just that - how many there are After that, the constant strings Finally, the assembly code Registers sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. Data 32-bit integers and strings Instructions Each instruction is one byte. The following instructions also have a 32-bit integer operand: fetch [index] where index is an index into the data array. store [index] where index is an index into the data array. push n where value is a 32-bit integer that will be pushed onto the stack. jmp (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. jz (n) addr where (n) is a 32-bit integer specifying the distance between the current location and the desired location. addr is an unsigned value of the actual code address. The following instructions do not have an operand. They perform their operation directly against the stack: For the following instructions, the operation is performed against the top two entries in the stack: add sub mul div mod lt gt le ge eq ne and or For the following instructions, the operation is performed against the top entry in the stack: neg not prtc Print the word at stack top as a character. prti Print the word at stack top as an integer. prts Stack top points to an index into the string pool. Print that entry. halt Unconditional stop. Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Virtual Machine Interpreter task AST Interpreter task
#Fortran
Fortran
module compiler_type_kinds use, intrinsic :: iso_fortran_env, only: int32 use, intrinsic :: iso_fortran_env, only: int64   implicit none private   ! Synonyms. integer, parameter, public :: size_kind = int64 integer, parameter, public :: length_kind = size_kind integer, parameter, public :: nk = size_kind   ! Synonyms for character capable of storing a Unicode code point. integer, parameter, public :: unicode_char_kind = selected_char_kind ('ISO_10646') integer, parameter, public :: ck = unicode_char_kind   ! Synonyms for integers capable of storing a Unicode code point. integer, parameter, public :: unicode_ichar_kind = int32 integer, parameter, public :: ick = unicode_ichar_kind   ! Synonyms for integers in the virtual machine or the interpreter’s ! runtime. (The Rosetta Code task says integers in the virtual ! machine are 32-bit, but there is nothing in the task that prevents ! us using 64-bit integers in the compiler and interpreter.) integer, parameter, public :: runtime_int_kind = int64 integer, parameter, public :: rik = runtime_int_kind end module compiler_type_kinds   module helper_procedures use, non_intrinsic :: compiler_type_kinds, only: nk, rik, ck   implicit none private   public :: new_storage_size public :: next_power_of_two   public :: isspace public :: quoted_string   public :: int32_to_vm_bytes public :: uint32_to_vm_bytes public :: int32_from_vm_bytes public :: uint32_from_vm_bytes   character(1, kind = ck), parameter :: horizontal_tab_char = char (9, kind = ck) character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck) character(1, kind = ck), parameter :: vertical_tab_char = char (11, kind = ck) character(1, kind = ck), parameter :: formfeed_char = char (12, kind = ck) character(1, kind = ck), parameter :: carriage_return_char = char (13, kind = ck) character(1, kind = ck), parameter :: space_char = ck_' '   ! The following is correct for Unix and its relatives. character(1, kind = ck), parameter :: newline_char = linefeed_char   character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)   contains   elemental function new_storage_size (length_needed) result (size) integer(kind = nk), intent(in) :: length_needed integer(kind = nk) :: size   ! Increase storage by orders of magnitude.   if (2_nk**32 < length_needed) then size = huge (1_nk) else size = next_power_of_two (length_needed) end if end function new_storage_size   elemental function next_power_of_two (x) result (y) integer(kind = nk), intent(in) :: x integer(kind = nk) :: y   ! ! It is assumed that no more than 64 bits are used. ! ! The branch-free algorithm is that of ! https://archive.is/nKxAc#RoundUpPowerOf2 ! ! Fill in bits until one less than the desired power of two is ! reached, and then add one. !   y = x - 1 y = ior (y, ishft (y, -1)) y = ior (y, ishft (y, -2)) y = ior (y, ishft (y, -4)) y = ior (y, ishft (y, -8)) y = ior (y, ishft (y, -16)) y = ior (y, ishft (y, -32)) y = y + 1 end function next_power_of_two   elemental function isspace (ch) result (bool) character(1, kind = ck), intent(in) :: ch logical :: bool   bool = (ch == horizontal_tab_char) .or. & & (ch == linefeed_char) .or. & & (ch == vertical_tab_char) .or. & & (ch == formfeed_char) .or. & & (ch == carriage_return_char) .or. & & (ch == space_char) end function isspace   function quoted_string (str) result (qstr) character(*, kind = ck), intent(in) :: str character(:, kind = ck), allocatable :: qstr   integer(kind = nk) :: n, i, j   ! Compute n = the size of qstr. n = 2_nk do i = 1_nk, len (str, kind = nk) select case (str(i:i)) case (newline_char, backslash_char) n = n + 2 case default n = n + 1 end select end do   allocate (character(n, kind = ck) :: qstr)   ! Quote the string. qstr(1:1) = ck_'"' j = 2_nk do i = 1_nk, len (str, kind = nk) select case (str(i:i)) case (newline_char) qstr(j:j) = backslash_char qstr((j + 1):(j + 1)) = ck_'n' j = j + 2 case (backslash_char) qstr(j:j) = backslash_char qstr((j + 1):(j + 1)) = backslash_char j = j + 2 case default qstr(j:j) = str(i:i) j = j + 1 end select end do if (j /= n) error stop ! Check code correctness. qstr(n:n) = ck_'"' end function quoted_string   subroutine int32_to_vm_bytes (n, bytes, i) integer(kind = rik), intent(in) :: n character(1), intent(inout) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   bytes(i) = achar (ibits (n, 0, 8)) bytes(i + 1) = achar (ibits (n, 8, 8)) bytes(i + 2) = achar (ibits (n, 16, 8)) bytes(i + 3) = achar (ibits (n, 24, 8)) end subroutine int32_to_vm_bytes   subroutine uint32_to_vm_bytes (n, bytes, i) integer(kind = rik), intent(in) :: n character(1), intent(inout) :: bytes(0:*) integer(kind = rik), intent(in) :: i   call int32_to_vm_bytes (n, bytes, i) end subroutine uint32_to_vm_bytes   subroutine int32_from_vm_bytes (n, bytes, i) integer(kind = rik), intent(out) :: n character(1), intent(in) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   call uint32_from_vm_bytes (n, bytes, i) if (ibits (n, 31, 1) == 1) then ! Extend the sign bit. n = ior (n, not ((2_rik ** 32) - 1)) end if end subroutine int32_from_vm_bytes   subroutine uint32_from_vm_bytes (n, bytes, i) integer(kind = rik), intent(out) :: n character(1), intent(in) :: bytes(0:*) integer(kind = rik), intent(in) :: i   ! ! The virtual machine is presumed to be little-endian. Because I ! slightly prefer little-endian. !   integer(kind = rik) :: n0, n1, n2, n3   n0 = iachar (bytes(i), kind = rik) n1 = ishft (iachar (bytes(i + 1), kind = rik), 8) n2 = ishft (iachar (bytes(i + 2), kind = rik), 16) n3 = ishft (iachar (bytes(i + 3), kind = rik), 24) n = ior (n0, ior (n1, ior (n2, n3))) end subroutine uint32_from_vm_bytes   end module helper_procedures   module string_buffers use, intrinsic :: iso_fortran_env, only: error_unit use, intrinsic :: iso_fortran_env, only: int64 use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick use, non_intrinsic :: helper_procedures   implicit none private   public :: strbuf_t public :: skip_whitespace public :: skip_non_whitespace public :: skip_whitespace_backwards public :: at_end_of_line   type :: strbuf_t integer(kind = nk), private :: len = 0 ! ! ‘chars’ is made public for efficient access to the individual ! characters. ! character(1, kind = ck), allocatable, public :: chars(:) contains procedure, pass, private :: ensure_storage => strbuf_t_ensure_storage procedure, pass :: to_unicode_full_string => strbuf_t_to_unicode_full_string procedure, pass :: to_unicode_substring => strbuf_t_to_unicode_substring procedure, pass :: length => strbuf_t_length procedure, pass :: set => strbuf_t_set procedure, pass :: append => strbuf_t_append generic :: to_unicode => to_unicode_full_string generic :: to_unicode => to_unicode_substring generic :: assignment(=) => set end type strbuf_t   contains   function strbuf_t_to_unicode_full_string (strbuf) result (s) class(strbuf_t), intent(in) :: strbuf character(:, kind = ck), allocatable :: s   ! ! This does not actually ensure that the string is valid Unicode; ! any 31-bit ‘character’ is supported. !   integer(kind = nk) :: i   allocate (character(len = strbuf%len, kind = ck) :: s) do i = 1, strbuf%len s(i:i) = strbuf%chars(i) end do end function strbuf_t_to_unicode_full_string   function strbuf_t_to_unicode_substring (strbuf, i, j) result (s) ! ! ‘Extreme’ values of i and j are allowed, as shortcuts for ‘from ! the beginning’, ‘up to the end’, or ‘empty substring’. ! class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j character(:, kind = ck), allocatable :: s   ! ! This does not actually ensure that the string is valid Unicode; ! any 31-bit ‘character’ is supported. !   integer(kind = nk) :: i1, j1 integer(kind = nk) :: n integer(kind = nk) :: k   i1 = max (1_nk, i) j1 = min (strbuf%len, j) n = max (0_nk, (j1 - i1) + 1_nk)   allocate (character(n, kind = ck) :: s) do k = 1, n s(k:k) = strbuf%chars(i1 + (k - 1_nk)) end do end function strbuf_t_to_unicode_substring   elemental function strbuf_t_length (strbuf) result (n) class(strbuf_t), intent(in) :: strbuf integer(kind = nk) :: n   n = strbuf%len end function strbuf_t_length   subroutine strbuf_t_ensure_storage (strbuf, length_needed) class(strbuf_t), intent(inout) :: strbuf integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(strbuf_t) :: new_strbuf   len_needed = max (length_needed, 1_nk)   if (.not. allocated (strbuf%chars)) then ! Initialize a new strbuf%chars array. new_size = new_storage_size (len_needed) allocate (strbuf%chars(1:new_size)) else if (ubound (strbuf%chars, 1) < len_needed) then ! Allocate a new strbuf%chars array, larger than the current ! one, but containing the same characters. new_size = new_storage_size (len_needed) allocate (new_strbuf%chars(1:new_size)) new_strbuf%chars(1:strbuf%len) = strbuf%chars(1:strbuf%len) call move_alloc (new_strbuf%chars, strbuf%chars) end if end subroutine strbuf_t_ensure_storage   subroutine strbuf_t_set (dst, src) class(strbuf_t), intent(inout) :: dst class(*), intent(in) :: src   integer(kind = nk) :: n integer(kind = nk) :: i   select type (src) type is (character(*, kind = ck)) n = len (src, kind = nk) call dst%ensure_storage(n) do i = 1, n dst%chars(i) = src(i:i) end do dst%len = n type is (character(*)) n = len (src, kind = nk) call dst%ensure_storage(n) do i = 1, n dst%chars(i) = src(i:i) end do dst%len = n class is (strbuf_t) n = src%len call dst%ensure_storage(n) dst%chars(1:n) = src%chars(1:n) dst%len = n class default error stop end select end subroutine strbuf_t_set   subroutine strbuf_t_append (dst, src) class(strbuf_t), intent(inout) :: dst class(*), intent(in) :: src   integer(kind = nk) :: n_dst, n_src, n integer(kind = nk) :: i   select type (src) type is (character(*, kind = ck)) n_dst = dst%len n_src = len (src, kind = nk) n = n_dst + n_src call dst%ensure_storage(n) do i = 1, n_src dst%chars(n_dst + i) = src(i:i) end do dst%len = n type is (character(*)) n_dst = dst%len n_src = len (src, kind = nk) n = n_dst + n_src call dst%ensure_storage(n) do i = 1, n_src dst%chars(n_dst + i) = src(i:i) end do dst%len = n class is (strbuf_t) n_dst = dst%len n_src = src%len n = n_dst + n_src call dst%ensure_storage(n) dst%chars((n_dst + 1):n) = src%chars(1:n_src) dst%len = n class default error stop end select end subroutine strbuf_t_append   function skip_whitespace (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (at_end_of_line (strbuf, j)) then done = .true. else if (.not. isspace (strbuf%chars(j))) then done = .true. else j = j + 1 end if end do end function skip_whitespace   function skip_non_whitespace (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (at_end_of_line (strbuf, j)) then done = .true. else if (isspace (strbuf%chars(j))) then done = .true. else j = j + 1 end if end do end function skip_non_whitespace   function skip_whitespace_backwards (strbuf, i) result (j) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i integer(kind = nk) :: j   logical :: done   j = i done = .false. do while (.not. done) if (j == -1) then done = .true. else if (.not. isspace (strbuf%chars(j))) then done = .true. else j = j - 1 end if end do end function skip_whitespace_backwards   function at_end_of_line (strbuf, i) result (bool) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i logical :: bool   bool = (strbuf%length() < i) end function at_end_of_line   end module string_buffers   module reading_one_line_from_a_stream use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick use, non_intrinsic :: string_buffers   implicit none private   ! get_line_from_stream: read an entire input line from a stream into ! a strbuf_t. public :: get_line_from_stream   character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck)   ! The following is correct for Unix and its relatives. character(1, kind = ck), parameter :: newline_char = linefeed_char   contains   subroutine get_line_from_stream (unit_no, eof, no_newline, strbuf) integer, intent(in) :: unit_no logical, intent(out) :: eof ! End of file? logical, intent(out) :: no_newline ! There is a line but it has no ! newline? (Thus eof also must ! be .true.) class(strbuf_t), intent(inout) :: strbuf   character(1, kind = ck) :: ch   strbuf = '' call get_ch (unit_no, eof, ch) do while (.not. eof .and. ch /= newline_char) call strbuf%append (ch) call get_ch (unit_no, eof, ch) end do no_newline = eof .and. (strbuf%length() /= 0) end subroutine get_line_from_stream   subroutine get_ch (unit_no, eof, ch) ! ! Read a single code point from the stream. ! ! Currently this procedure simply inputs ‘ASCII’ bytes rather than ! Unicode code points. ! integer, intent(in) :: unit_no logical, intent(out) :: eof character(1, kind = ck), intent(out) :: ch   integer :: stat character(1) :: c = '*'   eof = .false.   if (unit_no == input_unit) then call get_input_unit_char (c, stat) else read (unit = unit_no, iostat = stat) c end if   if (stat < 0) then ch = ck_'*' eof = .true. else if (0 < stat) then write (error_unit, '("Input error with status code ", I0)') stat stop 1 else ch = char (ichar (c, kind = ick), kind = ck) end if end subroutine get_ch   !!! !!! If you tell gfortran you want -std=f2008 or -std=f2018, you likely !!! will need to add also -fall-intrinsics or -U__GFORTRAN__ !!! !!! The first way, you get the FGETC intrinsic. The latter way, you !!! get the C interface code that uses getchar(3). !!! #ifdef __GFORTRAN__   subroutine get_input_unit_char (c, stat) ! ! The following works if you are using gfortran. ! ! (FGETC is considered a feature for backwards compatibility with ! g77. However, I know of no way to reconfigure input_unit as a ! Fortran 2003 stream, for use with ordinary ‘read’.) ! character, intent(inout) :: c integer, intent(out) :: stat   call fgetc (input_unit, c, stat) end subroutine get_input_unit_char   #else   subroutine get_input_unit_char (c, stat) ! ! An alternative implementation of get_input_unit_char. This ! actually reads input from the C standard input, which might not ! be the same as input_unit. ! use, intrinsic :: iso_c_binding, only: c_int character, intent(inout) :: c integer, intent(out) :: stat   interface ! ! Use getchar(3) to read characters from standard input. This ! assumes there is actually such a function available, and that ! getchar(3) does not exist solely as a macro. (One could write ! one’s own getchar() if necessary, of course.) ! function getchar () result (c) bind (c, name = 'getchar') use, intrinsic :: iso_c_binding, only: c_int integer(kind = c_int) :: c end function getchar end interface   integer(kind = c_int) :: i_char   i_char = getchar () ! ! The C standard requires that EOF have a negative value. If the ! value returned by getchar(3) is not EOF, then it will be ! representable as an unsigned char. Therefore, to check for end ! of file, one need only test whether i_char is negative. ! if (i_char < 0) then stat = -1 else stat = 0 c = char (i_char) end if end subroutine get_input_unit_char   #endif   end module reading_one_line_from_a_stream   module ast_reader   ! ! The AST will be read into an array. Perhaps that will improve ! locality, compared to storing the AST as many linked heap nodes. ! ! In any case, implementing the AST this way is an interesting ! problem. !   use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: output_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds, only: nk, ck, ick, rik use, non_intrinsic :: helper_procedures, only: next_power_of_two use, non_intrinsic :: helper_procedures, only: new_storage_size use, non_intrinsic :: string_buffers use, non_intrinsic :: reading_one_line_from_a_stream   implicit none private   public :: string_table_t public :: ast_node_t public :: ast_t public :: read_ast   integer, parameter, public :: node_Nil = 0 integer, parameter, public :: node_Identifier = 1 integer, parameter, public :: node_String = 2 integer, parameter, public :: node_Integer = 3 integer, parameter, public :: node_Sequence = 4 integer, parameter, public :: node_If = 5 integer, parameter, public :: node_Prtc = 6 integer, parameter, public :: node_Prts = 7 integer, parameter, public :: node_Prti = 8 integer, parameter, public :: node_While = 9 integer, parameter, public :: node_Assign = 10 integer, parameter, public :: node_Negate = 11 integer, parameter, public :: node_Not = 12 integer, parameter, public :: node_Multiply = 13 integer, parameter, public :: node_Divide = 14 integer, parameter, public :: node_Mod = 15 integer, parameter, public :: node_Add = 16 integer, parameter, public :: node_Subtract = 17 integer, parameter, public :: node_Less = 18 integer, parameter, public :: node_LessEqual = 19 integer, parameter, public :: node_Greater = 20 integer, parameter, public :: node_GreaterEqual = 21 integer, parameter, public :: node_Equal = 22 integer, parameter, public :: node_NotEqual = 23 integer, parameter, public :: node_And = 24 integer, parameter, public :: node_Or = 25   type :: string_table_element_t character(:, kind = ck), allocatable :: str end type string_table_element_t   type :: string_table_t integer(kind = nk), private :: len = 0_nk type(string_table_element_t), allocatable, private :: strings(:) contains procedure, pass, private :: ensure_storage => string_table_t_ensure_storage procedure, pass :: look_up_index => string_table_t_look_up_index procedure, pass :: look_up_string => string_table_t_look_up_string procedure, pass :: length => string_table_t_length generic :: look_up => look_up_index generic :: look_up => look_up_string end type string_table_t   type :: ast_node_t integer :: node_variety   ! Runtime integer, symbol index, or string index. integer(kind = rik) :: int   ! The left branch begins at the next node. The right branch ! begins at the address of the left branch, plus the following. integer(kind = nk) :: right_branch_offset end type ast_node_t   type :: ast_t integer(kind = nk), private :: len = 0_nk type(ast_node_t), allocatable, public :: nodes(:) contains procedure, pass, private :: ensure_storage => ast_t_ensure_storage end type ast_t   contains   subroutine string_table_t_ensure_storage (table, length_needed) class(string_table_t), intent(inout) :: table integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(string_table_t) :: new_table   len_needed = max (length_needed, 1_nk)   if (.not. allocated (table%strings)) then ! Initialize a new table%strings array. new_size = new_storage_size (len_needed) allocate (table%strings(1:new_size)) else if (ubound (table%strings, 1) < len_needed) then ! Allocate a new table%strings array, larger than the current ! one, but containing the same strings. new_size = new_storage_size (len_needed) allocate (new_table%strings(1:new_size)) new_table%strings(1:table%len) = table%strings(1:table%len) call move_alloc (new_table%strings, table%strings) end if end subroutine string_table_t_ensure_storage   elemental function string_table_t_length (table) result (len) class(string_table_t), intent(in) :: table integer(kind = nk) :: len   len = table%len end function string_table_t_length   function string_table_t_look_up_index (table, str) result (index) class(string_table_t), intent(inout) :: table character(*, kind = ck), intent(in) :: str integer(kind = rik) :: index   ! ! This implementation simply stores the strings sequentially into ! an array. Obviously, for large numbers of strings, one might ! wish to do something more complex. ! ! Standard Fortran does not come, out of the box, with a massive ! runtime library for doing such things. They are, however, no ! longer nearly as challenging to implement in Fortran as they ! used to be. !   integer(kind = nk) :: i   i = 1 index = 0 do while (index == 0) if (i == table%len + 1) then ! The string is new and must be added to the table. i = table%len + 1 if (huge (1_rik) < i) then ! String indices are assumed to be storable as runtime ! integers. write (error_unit, '("string_table_t capacity exceeded")') stop 1 end if call table%ensure_storage(i) table%len = i allocate (table%strings(i)%str, source = str) index = int (i, kind = rik) else if (table%strings(i)%str == str) then index = int (i, kind = rik) else i = i + 1 end if end do end function string_table_t_look_up_index   function string_table_t_look_up_string (table, index) result (str) class(string_table_t), intent(inout) :: table integer(kind = rik), intent(in) :: index character(:, kind = ck), allocatable :: str   ! ! This is the reverse of string_table_t_look_up_index: given an ! index, find the string. !   if (index < 1 .or. table%len < index) then ! In correct code, this branch should never be reached. error stop else allocate (str, source = table%strings(index)%str) end if end function string_table_t_look_up_string   subroutine ast_t_ensure_storage (ast, length_needed) class(ast_t), intent(inout) :: ast integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(ast_t) :: new_ast   len_needed = max (length_needed, 1_nk)   if (.not. allocated (ast%nodes)) then ! Initialize a new ast%nodes array. new_size = new_storage_size (len_needed) allocate (ast%nodes(1:new_size)) else if (ubound (ast%nodes, 1) < len_needed) then ! Allocate a new ast%nodes array, larger than the current one, ! but containing the same nodes. new_size = new_storage_size (len_needed) allocate (new_ast%nodes(1:new_size)) new_ast%nodes(1:ast%len) = ast%nodes(1:ast%len) call move_alloc (new_ast%nodes, ast%nodes) end if end subroutine ast_t_ensure_storage   subroutine read_ast (unit_no, strbuf, ast, symtab, strtab) integer, intent(in) :: unit_no type(strbuf_t), intent(inout) :: strbuf type(ast_t), intent(inout) :: ast type(string_table_t), intent(inout) :: symtab type(string_table_t), intent(inout) :: strtab   logical :: eof logical :: no_newline integer(kind = nk) :: after_ast_address   ast%len = 0 symtab%len = 0 strtab%len = 0 call build_subtree (1_nk, after_ast_address)   contains   recursive subroutine build_subtree (here_address, after_subtree_address) integer(kind = nk), value :: here_address integer(kind = nk), intent(out) :: after_subtree_address   integer :: node_variety integer(kind = nk) :: i, j integer(kind = nk) :: left_branch_address integer(kind = nk) :: right_branch_address   ! Get a line from the parser output. call get_line_from_stream (unit_no, eof, no_newline, strbuf)   if (eof) then call ast_error else ! Prepare to store a new node. call ast%ensure_storage(here_address) ast%len = here_address   ! What sort of node is it? i = skip_whitespace (strbuf, 1_nk) j = skip_non_whitespace (strbuf, i) node_variety = strbuf_to_node_variety (strbuf, i, j - 1)   ast%nodes(here_address)%node_variety = node_variety   select case (node_variety) case (node_Nil) after_subtree_address = here_address + 1 case (node_Identifier) i = skip_whitespace (strbuf, j) j = skip_non_whitespace (strbuf, i) ast%nodes(here_address)%int = & & strbuf_to_symbol_index (strbuf, i, j - 1, symtab) after_subtree_address = here_address + 1 case (node_String) i = skip_whitespace (strbuf, j) j = skip_whitespace_backwards (strbuf, strbuf%length()) ast%nodes(here_address)%int = & & strbuf_to_string_index (strbuf, i, j, strtab) after_subtree_address = here_address + 1 case (node_Integer) i = skip_whitespace (strbuf, j) j = skip_non_whitespace (strbuf, i) ast%nodes(here_address)%int = strbuf_to_int (strbuf, i, j - 1) after_subtree_address = here_address + 1 case default ! The node is internal, and has left and right branches. ! The left branch will start at left_branch_address; the ! right branch will start at left_branch_address + ! right_side_offset. left_branch_address = here_address + 1 ! Build the left branch. call build_subtree (left_branch_address, right_branch_address) ! Build the right_branch. call build_subtree (right_branch_address, after_subtree_address) ast%nodes(here_address)%right_branch_offset = & & right_branch_address - left_branch_address end select   end if end subroutine build_subtree   end subroutine read_ast   function strbuf_to_node_variety (strbuf, i, j) result (node_variety) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j integer :: node_variety   ! ! This function has not been optimized in any way, unless the ! Fortran compiler can optimize it. ! ! Something like a ‘radix tree search’ could be done on the ! characters of the strbuf. Or a perfect hash function. Or a ! binary search. Etc. !   if (j == i - 1) then call ast_error else select case (strbuf%to_unicode(i, j)) case (ck_";") node_variety = node_Nil case (ck_"Identifier") node_variety = node_Identifier case (ck_"String") node_variety = node_String case (ck_"Integer") node_variety = node_Integer case (ck_"Sequence") node_variety = node_Sequence case (ck_"If") node_variety = node_If case (ck_"Prtc") node_variety = node_Prtc case (ck_"Prts") node_variety = node_Prts case (ck_"Prti") node_variety = node_Prti case (ck_"While") node_variety = node_While case (ck_"Assign") node_variety = node_Assign case (ck_"Negate") node_variety = node_Negate case (ck_"Not") node_variety = node_Not case (ck_"Multiply") node_variety = node_Multiply case (ck_"Divide") node_variety = node_Divide case (ck_"Mod") node_variety = node_Mod case (ck_"Add") node_variety = node_Add case (ck_"Subtract") node_variety = node_Subtract case (ck_"Less") node_variety = node_Less case (ck_"LessEqual") node_variety = node_LessEqual case (ck_"Greater") node_variety = node_Greater case (ck_"GreaterEqual") node_variety = node_GreaterEqual case (ck_"Equal") node_variety = node_Equal case (ck_"NotEqual") node_variety = node_NotEqual case (ck_"And") node_variety = node_And case (ck_"Or") node_variety = node_Or case default call ast_error end select end if end function strbuf_to_node_variety   function strbuf_to_symbol_index (strbuf, i, j, symtab) result (int) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j type(string_table_t), intent(inout) :: symtab integer(kind = rik) :: int   if (j == i - 1) then call ast_error else int = symtab%look_up(strbuf%to_unicode (i, j)) end if end function strbuf_to_symbol_index   function strbuf_to_int (strbuf, i, j) result (int) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j integer(kind = rik) :: int   integer :: stat character(:, kind = ck), allocatable :: str   if (j < i) then call ast_error else allocate (character(len = (j - i) + 1_nk, kind = ck) :: str) str = strbuf%to_unicode (i, j) read (str, *, iostat = stat) int if (stat /= 0) then call ast_error end if end if end function strbuf_to_int   function strbuf_to_string_index (strbuf, i, j, strtab) result (int) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j type(string_table_t), intent(inout) :: strtab integer(kind = rik) :: int   if (j == i - 1) then call ast_error else int = strtab%look_up(strbuf_to_string (strbuf, i, j)) end if end function strbuf_to_string_index   function strbuf_to_string (strbuf, i, j) result (str) class(strbuf_t), intent(in) :: strbuf integer(kind = nk), intent(in) :: i, j character(:, kind = ck), allocatable :: str   character(1, kind = ck), parameter :: linefeed_char = char (10, kind = ck) character(1, kind = ck), parameter :: backslash_char = char (92, kind = ck)   ! The following is correct for Unix and its relatives. character(1, kind = ck), parameter :: newline_char = linefeed_char   integer(kind = nk) :: k integer(kind = nk) :: count   if (strbuf%chars(i) /= ck_'"' .or. strbuf%chars(j) /= ck_'"') then call ast_error else ! Count how many characters are needed. count = 0 k = i + 1 do while (k < j) count = count + 1 if (strbuf%chars(k) == backslash_char) then k = k + 2 else k = k + 1 end if end do   allocate (character(len = count, kind = ck) :: str)   count = 0 k = i + 1 do while (k < j) if (strbuf%chars(k) == backslash_char) then if (k == j - 1) then call ast_error else select case (strbuf%chars(k + 1)) case (ck_'n') count = count + 1 str(count:count) = newline_char case (backslash_char) count = count + 1 str(count:count) = backslash_char case default call ast_error end select k = k + 2 end if else count = count + 1 str(count:count) = strbuf%chars(k) k = k + 1 end if end do end if end function strbuf_to_string   subroutine ast_error ! ! It might be desirable to give more detail. ! write (error_unit, '("The AST input seems corrupted.")') stop 1 end subroutine ast_error   end module ast_reader   module code_generation   ! ! First we generate code as if the virtual machine itself were part ! of this program. Then we disassemble the generated code. ! ! Because we are targeting only the one output language, this seems ! an easy way to perform the task. ! ! ! A point worth noting: the virtual machine is a stack ! architecture. ! ! Stack architectures have a long history. Burroughs famously ! preferred stack architectures for running Algol programs. See, for ! instance, ! https://en.wikipedia.org/w/index.php?title=Burroughs_large_systems&oldid=1068076420 !   use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: output_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds use, non_intrinsic :: helper_procedures use, non_intrinsic :: ast_reader   implicit none private   public :: generate_and_output_code public :: generate_code public :: output_code   ! The virtual machine cannot handle integers of more than 32 bits, ! two’s-complement. integer(kind = rik), parameter :: vm_huge_negint = -(2_rik ** 31_rik) integer(kind = rik), parameter :: vm_huge_posint = (2_rik ** 31_rik) - 1_rik   ! Arbitrarily chosen opcodes. integer, parameter :: opcode_nop = 0 ! I think there should be a nop ! opcode, to reserve space for ! later hand-patching. :) integer, parameter :: opcode_halt = 1 ! Does the ‘halt’ instruction ! apply brakes to the drum? integer, parameter :: opcode_add = 2 integer, parameter :: opcode_sub = 3 integer, parameter :: opcode_mul = 4 integer, parameter :: opcode_div = 5 integer, parameter :: opcode_mod = 6 integer, parameter :: opcode_lt = 7 integer, parameter :: opcode_gt = 8 integer, parameter :: opcode_le = 9 integer, parameter :: opcode_ge = 10 integer, parameter :: opcode_eq = 11 integer, parameter :: opcode_ne = 12 integer, parameter :: opcode_and = 13 integer, parameter :: opcode_or = 14 integer, parameter :: opcode_neg = 15 integer, parameter :: opcode_not = 16 integer, parameter :: opcode_prtc = 17 integer, parameter :: opcode_prti = 18 integer, parameter :: opcode_prts = 19 integer, parameter :: opcode_fetch = 20 integer, parameter :: opcode_store = 21 integer, parameter :: opcode_push = 22 integer, parameter :: opcode_jmp = 23 integer, parameter :: opcode_jz = 24   character(8, kind = ck), parameter :: opcode_names(0:24) = & & (/ "nop ", & & "halt ", & & "add ", & & "sub ", & & "mul ", & & "div ", & & "mod ", & & "lt ", & & "gt ", & & "le ", & & "ge ", & & "eq ", & & "ne ", & & "and ", & & "or ", & & "neg ", & & "not ", & & "prtc ", & & "prti ", & & "prts ", & & "fetch ", & & "store ", & & "push ", & & "jmp ", & & "jz " /)   type :: vm_code_t integer(kind = rik), private :: len = 0_rik character(1), allocatable :: bytes(:) contains procedure, pass, private :: ensure_storage => vm_code_t_ensure_storage procedure, pass :: length => vm_code_t_length end type vm_code_t   contains   subroutine vm_code_t_ensure_storage (code, length_needed) class(vm_code_t), intent(inout) :: code integer(kind = nk), intent(in) :: length_needed   integer(kind = nk) :: len_needed integer(kind = nk) :: new_size type(vm_code_t) :: new_code   len_needed = max (length_needed, 1_nk)   if (.not. allocated (code%bytes)) then ! Initialize a new code%bytes array. new_size = new_storage_size (len_needed) allocate (code%bytes(0:(new_size - 1))) else if (ubound (code%bytes, 1) < len_needed - 1) then ! Allocate a new code%bytes array, larger than the current one, ! but containing the same bytes. new_size = new_storage_size (len_needed) allocate (new_code%bytes(0:(new_size - 1))) new_code%bytes(0:(code%len - 1)) = code%bytes(0:(code%len - 1)) call move_alloc (new_code%bytes, code%bytes) end if end subroutine vm_code_t_ensure_storage   elemental function vm_code_t_length (code) result (len) class(vm_code_t), intent(in) :: code integer(kind = rik) :: len   len = code%len end function vm_code_t_length   subroutine generate_and_output_code (outp, ast, symtab, strtab) integer, intent(in) :: outp ! The unit to write the output to. type(ast_t), intent(in) :: ast type(string_table_t), intent(inout) :: symtab type(string_table_t), intent(inout) :: strtab   type(vm_code_t) :: code integer(kind = rik) :: i_vm   code%len = 0 i_vm = 0_rik call generate_code (ast, 1_nk, i_vm, code) call output_code (outp, symtab, strtab, code) end subroutine generate_and_output_code   subroutine generate_code (ast, i_ast, i_vm, code) type(ast_t), intent(in) :: ast integer(kind = nk), intent(in) :: i_ast ! Index in the ast array. integer(kind = rik), intent(inout) :: i_vm ! Address in the virtual machine. type(vm_code_t), intent(inout) :: code   call traverse (i_ast)   ! Generate a halt instruction. call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_halt) i_vm = i_vm + 1   code%len = i_vm   contains   recursive subroutine traverse (i_ast) integer(kind = nk), intent(in) :: i_ast ! Index in the ast array.   select case (ast%nodes(i_ast)%node_variety)   case (node_Nil) continue   case (node_Integer) block integer(kind = rik) :: int_value   int_value = ast%nodes(i_ast)%int call ensure_integer_is_vm_compatible (int_value) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_push) call int32_to_vm_bytes (int_value, code%bytes, i_vm + 1) i_vm = i_vm + 5 end block   case (node_Identifier) block integer(kind = rik) :: variable_index   ! In the best Fortran tradition, we indexed the variables ! starting at one; however, the virtual machine starts them ! at zero. So subtract 1. variable_index = ast%nodes(i_ast)%int - 1   call ensure_integer_is_vm_compatible (variable_index) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_fetch) call uint32_to_vm_bytes (variable_index, code%bytes, i_vm + 1) i_vm = i_vm + 5 end block   case (node_String) block integer(kind = rik) :: string_index   ! In the best Fortran tradition, we indexed the strings ! starting at one; however, the virtual machine starts them ! at zero. So subtract 1. string_index = ast%nodes(i_ast)%int - 1   call ensure_integer_is_vm_compatible (string_index) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_push) call uint32_to_vm_bytes (string_index, code%bytes, i_vm + 1) i_vm = i_vm + 5 end block   case (node_Assign) block integer(kind = nk) :: i_left, i_right integer(kind = rik) :: variable_index   i_left = left_branch (i_ast) i_right = right_branch (i_ast)   ! In the best Fortran tradition, we indexed the variables ! starting at one; however, the virtual machine starts them ! at zero. So subtract 1. variable_index = ast%nodes(i_left)%int - 1   ! Create code to push the right side onto the stack call traverse (i_right)   ! Create code to store that result into the variable on the ! left side. call ensure_node_variety (node_Identifier, ast%nodes(i_left)%node_variety) call ensure_integer_is_vm_compatible (variable_index) call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_store) call uint32_to_vm_bytes (variable_index, code%bytes, i_vm + 1) i_vm = i_vm + 5 end block   case (node_Multiply) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_mul) i_vm = i_vm + 1   case (node_Divide) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_div) i_vm = i_vm + 1   case (node_Mod) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_mod) i_vm = i_vm + 1   case (node_Add) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_add) i_vm = i_vm + 1   case (node_Subtract) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_sub) i_vm = i_vm + 1   case (node_Less) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_lt) i_vm = i_vm + 1   case (node_LessEqual) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_le) i_vm = i_vm + 1   case (node_Greater) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_gt) i_vm = i_vm + 1   case (node_GreaterEqual) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_ge) i_vm = i_vm + 1   case (node_Equal) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_eq) i_vm = i_vm + 1   case (node_NotEqual) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_ne) i_vm = i_vm + 1   case (node_Negate) call ensure_node_variety (node_Nil, & & ast%nodes(right_branch (i_ast))%node_variety) call traverse (left_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_neg) i_vm = i_vm + 1   case (node_Not) call ensure_node_variety (node_Nil, & & ast%nodes(right_branch (i_ast))%node_variety) call traverse (left_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_not) i_vm = i_vm + 1   case (node_And) ! ! This is not a short-circuiting AND and so differs from ! C. One would not notice the difference, except in side ! effects that (I believe) are not possible in our tiny ! language. ! ! Even in a language such as Fortran that has actual AND and ! OR operators, an optimizer may generate short-circuiting ! code and so spoil one’s expectations for side ! effects. (Therefore gfortran may issue a warning if you ! call an unpure function within an .AND. or ! .OR. expression.) ! ! A C equivalent to what we have our code generator doing ! (and to Fortran’s .AND. operator) might be something like ! ! #define AND(a, b) ((!!(a)) * (!!(b))) ! ! This macro takes advantage of the equivalence of AND to ! multiplication modulo 2. The ‘!!’ notations are a C idiom ! for converting values to 0 and 1. ! call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_and) i_vm = i_vm + 1   case (node_Or) ! ! This is not a short-circuiting OR and so differs from ! C. One would not notice the difference, except in side ! effects that (I believe) are not possible in our tiny ! language. ! ! Even in a language such as Fortran that has actual AND and ! OR operators, an optimizer may generate short-circuiting ! code and so spoil one’s expectations for side ! effects. (Therefore gfortran may issue a warning if you ! call an unpure function within an .AND. or ! .OR. expression.) ! ! A C equivalent to what we have our code generator doing ! (and to Fortran’s .OR. operator) might be something like ! ! #define OR(a, b) (!( (!(a)) * (!(b)) )) ! ! This macro takes advantage of the equivalence of AND to ! multiplication modulo 2, and the equivalence of OR(a,b) to ! !AND(!a,!b). One could instead take advantage of the ! equivalence of OR to addition modulo 2: ! ! #define OR(a, b) ( ( (!!(a)) + (!!(b)) ) & 1 ) ! call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_or) i_vm = i_vm + 1   case (node_If) block integer(kind = nk) :: i_left, i_right integer(kind = nk) :: i_right_then_left, i_right_then_right logical :: there_is_an_else_clause integer(kind = rik) :: fixup_address1 integer(kind = rik) :: fixup_address2 integer(kind = rik) :: relative_address   i_left = left_branch (i_ast) i_right = right_branch (i_ast)   call ensure_node_variety (node_If, ast%nodes(i_right)%node_variety)   i_right_then_left = left_branch (i_right) i_right_then_right = right_branch (i_right)   there_is_an_else_clause = & & (ast%nodes(i_right_then_right)%node_variety /= node_Nil)   ! Generate code for the predicate. call traverse (i_left)   ! Generate a conditional jump over the predicate-true code. call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_jz) call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1) fixup_address1 = i_vm + 1 i_vm = i_vm + 5   ! Generate the predicate-true code. call traverse (i_right_then_left)   if (there_is_an_else_clause) then ! Generate an unconditional jump over the predicate-true ! code. call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_jmp) call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1) fixup_address2 = i_vm + 1 i_vm = i_vm + 5   ! Fix up the conditional jump, so it jumps to the ! predicate-false code. relative_address = i_vm - fixup_address1 call int32_to_vm_bytes (relative_address, code%bytes, fixup_address1)   ! Generate the predicate-false code. call traverse (i_right_then_right)   ! Fix up the unconditional jump, so it jumps past the ! predicate-false code. relative_address = i_vm - fixup_address2 call int32_to_vm_bytes (relative_address, code%bytes, fixup_address2) else ! Fix up the conditional jump, so it jumps past the ! predicate-true code. relative_address = i_vm - fixup_address1 call int32_to_vm_bytes (relative_address, code%bytes, fixup_address1) end if end block   case (node_While) block   ! ! Note there is another common way to translate a ! while-loop which is to put (logically inverted) predicate ! code *after* the loop-body code, followed by a ! conditional jump to the start of the loop. You start the ! loop by unconditionally jumping to the predicate code. ! ! If our VM had a ‘jnz’ instruction, that translation would ! almost certainly be slightly better than this one. Given ! that we do not have a ‘jnz’, the code would end up ! slightly enlarged; one would have to put ‘not’ before the ! ‘jz’ at the bottom of the loop. !   integer(kind = nk) :: i_left, i_right integer(kind = rik) :: loop_address integer(kind = rik) :: fixup_address integer(kind = rik) :: relative_address   i_left = left_branch (i_ast) i_right = right_branch (i_ast)   ! Generate code for the predicate. loop_address = i_vm call traverse (i_left)   ! Generate a conditional jump out of the loop. call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_jz) call int32_to_vm_bytes (0_rik, code%bytes, i_vm + 1) fixup_address = i_vm + 1 i_vm = i_vm + 5   ! Generate code for the loop body. call traverse (i_right)   ! Generate an unconditional jump to the top of the loop. call code%ensure_storage(i_vm + 5) code%bytes(i_vm) = achar (opcode_jmp) relative_address = loop_address - (i_vm + 1) call int32_to_vm_bytes (relative_address, code%bytes, i_vm + 1) i_vm = i_vm + 5   ! Fix up the conditional jump, so it jumps after the loop ! body. relative_address = i_vm - fixup_address call int32_to_vm_bytes (relative_address, code%bytes, fixup_address) end block   case (node_Prtc) call ensure_node_variety (node_Nil, & & ast%nodes(right_branch (i_ast))%node_variety) call traverse (left_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_prtc) i_vm = i_vm + 1   case (node_Prti) call ensure_node_variety (node_Nil, & & ast%nodes(right_branch (i_ast))%node_variety) call traverse (left_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_prti) i_vm = i_vm + 1   case (node_Prts) call ensure_node_variety (node_Nil, & & ast%nodes(right_branch (i_ast))%node_variety) call traverse (left_branch (i_ast)) call code%ensure_storage(i_vm + 1) code%bytes(i_vm) = achar (opcode_prts) i_vm = i_vm + 1   case (node_Sequence) call traverse (left_branch (i_ast)) call traverse (right_branch (i_ast))   case default call bad_ast   end select   code%len = i_vm   end subroutine traverse   elemental function left_branch (i_here) result (i_left) integer(kind = nk), intent(in) :: i_here integer(kind = nk) :: i_left   i_left = i_here + 1 end function left_branch   elemental function right_branch (i_here) result (i_right) integer(kind = nk), intent(in) :: i_here integer(kind = nk) :: i_right   i_right = i_here + 1 + ast%nodes(i_here)%right_branch_offset end function right_branch   subroutine ensure_node_variety (expected_node_variety, found_node_variety) integer, intent(in) :: expected_node_variety integer, intent(in) :: found_node_variety if (expected_node_variety /= found_node_variety) call bad_ast end subroutine ensure_node_variety   subroutine bad_ast call codegen_error_message write (error_unit, '("unexpected abstract syntax")') stop 1 end subroutine bad_ast   end subroutine generate_code   subroutine output_code (outp, symtab, strtab, code) integer, intent(in) :: outp ! The unit to write the output to. type(string_table_t), intent(inout) :: symtab type(string_table_t), intent(inout) :: strtab type(vm_code_t), intent(in) :: code   call write_header (outp, symtab%length(), strtab%length()) call write_strings (outp, strtab) call disassemble_instructions (outp, code) end subroutine output_code   subroutine write_header (outp, data_size, strings_size) integer, intent(in) :: outp integer(kind = rik) :: data_size integer(kind = rik) :: strings_size   call ensure_integer_is_vm_compatible (data_size) call ensure_integer_is_vm_compatible (strings_size) write (outp, '("Datasize: ", I0, " Strings: ", I0)') data_size, strings_size end subroutine write_header   subroutine write_strings (outp, strtab) integer, intent(in) :: outp type(string_table_t), intent(inout) :: strtab   integer(kind = rik) :: i   do i = 1_rik, strtab%length() write (outp, '(1A)') quoted_string (strtab%look_up(i)) end do end subroutine write_strings   subroutine disassemble_instructions (outp, code) integer, intent(in) :: outp type(vm_code_t), intent(in) :: code   integer(kind = rik) :: i_vm integer :: opcode integer(kind = rik) :: n   i_vm = 0_rik do while (i_vm /= code%length()) call write_vm_code_address (outp, i_vm) opcode = iachar (code%bytes(i_vm)) call write_vm_opcode (outp, opcode) select case (opcode) case (opcode_push) call int32_from_vm_bytes (n, code%bytes, i_vm + 1) call write_vm_int_literal (outp, n) i_vm = i_vm + 5 case (opcode_fetch, opcode_store) call uint32_from_vm_bytes (n, code%bytes, i_vm + 1) call write_vm_data_address (outp, n) i_vm = i_vm + 5 case (opcode_jmp, opcode_jz) call int32_from_vm_bytes (n, code%bytes, i_vm + 1) call write_vm_jump_address (outp, n, i_vm + 1) i_vm = i_vm + 5 case default i_vm = i_vm + 1 end select write (outp, '()', advance = 'yes') end do end subroutine disassemble_instructions   subroutine write_vm_code_address (outp, i_vm) integer, intent(in) :: outp integer(kind = rik), intent(in) :: i_vm   ! 10 characters is wide enough for any 32-bit unsigned number. write (outp, '(I10, 1X)', advance = 'no') i_vm end subroutine write_vm_code_address   subroutine write_vm_opcode (outp, opcode) integer, intent(in) :: outp integer, intent(in) :: opcode   character(8, kind = ck) :: opcode_name   opcode_name = opcode_names(opcode)   select case (opcode) case (opcode_push, opcode_fetch, opcode_store, opcode_jz, opcode_jmp) write (outp, '(1A)', advance = 'no') opcode_name(1:6) case default write (outp, '(1A)', advance = 'no') trim (opcode_name) end select end subroutine write_vm_opcode   subroutine write_vm_int_literal (outp, n) integer, intent(in) :: outp integer(kind = rik), intent(in) :: n   write (outp, '(I0)', advance = 'no') n end subroutine write_vm_int_literal   subroutine write_vm_data_address (outp, i) integer, intent(in) :: outp integer(kind = rik), intent(in) :: i   write (outp, '("[", I0, "]")', advance = 'no') i end subroutine write_vm_data_address   subroutine write_vm_jump_address (outp, relative_address, i_vm) integer, intent(in) :: outp integer(kind = rik), intent(in) :: relative_address integer(kind = rik), intent(in) :: i_vm   write (outp, '(" (", I0, ") ", I0)', advance = 'no') & & relative_address, i_vm + relative_address end subroutine write_vm_jump_address   subroutine ensure_integer_is_vm_compatible (n) integer(kind = rik), intent(in) :: n ! ! It would seem desirable to check this in the syntax analyzer, ! instead, so line and column numbers can be given. But checking ! here will not hurt. ! if (n < vm_huge_negint .or. vm_huge_posint < n) then call codegen_error_message write (error_unit, '("integer is too large for the virtual machine: ", I0)') n stop 1 end if end subroutine ensure_integer_is_vm_compatible   subroutine codegen_error_message write (error_unit, '("Code generation error: ")', advance = 'no') end subroutine codegen_error_message   end module code_generation   program gen use, intrinsic :: iso_fortran_env, only: input_unit use, intrinsic :: iso_fortran_env, only: output_unit use, intrinsic :: iso_fortran_env, only: error_unit use, non_intrinsic :: compiler_type_kinds use, non_intrinsic :: string_buffers use, non_intrinsic :: ast_reader use, non_intrinsic :: code_generation   implicit none   integer, parameter :: inp_unit_no = 100 integer, parameter :: outp_unit_no = 101   integer :: arg_count character(200) :: arg integer :: inp integer :: outp   type(strbuf_t) :: strbuf type(ast_t) :: ast type(string_table_t) :: symtab type(string_table_t) :: strtab   arg_count = command_argument_count () if (3 <= arg_count) then call print_usage else if (arg_count == 0) then inp = input_unit outp = output_unit else if (arg_count == 1) then call get_command_argument (1, arg) inp = open_for_input (trim (arg)) outp = output_unit else if (arg_count == 2) then call get_command_argument (1, arg) inp = open_for_input (trim (arg)) call get_command_argument (2, arg) outp = open_for_output (trim (arg)) end if   call read_ast (inp, strbuf, ast, symtab, strtab) call generate_and_output_code (outp, ast, symtab, strtab) end if   contains   function open_for_input (filename) result (unit_no) character(*), intent(in) :: filename integer :: unit_no   integer :: stat   open (unit = inp_unit_no, file = filename, status = 'old', & & action = 'read', access = 'stream', form = 'unformatted', & & iostat = stat) if (stat /= 0) then write (error_unit, '("Error: failed to open ", 1A, " for input")') filename stop 1 end if unit_no = inp_unit_no end function open_for_input   function open_for_output (filename) result (unit_no) character(*), intent(in) :: filename integer :: unit_no   integer :: stat   open (unit = outp_unit_no, file = filename, action = 'write', iostat = stat) if (stat /= 0) then write (error_unit, '("Error: failed to open ", 1A, " for output")') filename stop 1 end if unit_no = outp_unit_no end function open_for_output   subroutine print_usage character(200) :: progname   call get_command_argument (0, progname) write (output_unit, '("Usage: ", 1A, " [INPUT_FILE [OUTPUT_FILE]]")') & & trim (progname) end subroutine print_usage   end program gen
http://rosettacode.org/wiki/Compare_sorting_algorithms%27_performance
Compare sorting algorithms' performance
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Measure a relative performance of sorting algorithms implementations. Plot execution time vs. input sequence length dependencies for various implementation of sorting algorithm and different input sequence types (example figures). Consider three type of input sequences:   ones: sequence of all 1's.   Example: {1, 1, 1, 1, 1}   range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}   shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8} Consider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm). For example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations. Preliminary subtask:   Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort   Query Performance   Write float arrays to a text file   Plot x, y arrays   Polynomial Fitting General steps:   Define sorting routines to be considered.   Define appropriate sequence generators and write timings.   Plot timings.   What conclusions about relative performance of the sorting routines could be made based on the plots?
#J
J
  NB. extracts from other rosetta code projects ts=: 6!:2, 7!:2@] radix =: 3 : 0 256 radix y : a=. #{. z =. x #.^:_1 y e=. (-a) {."0 b =. i.x x#.1{::(<:@[;([: ; (b, {"1) <@}./. e,]))&>/^:a [ z;~a-1 NB. , ([: ; (b, {:"1) <@(}:"1@:}.)/. e,])^:(#{.z) y,.z ) bubble=: (([ (<. , >.) {.@]) , }.@])/^:_ insertion=:((>: # ]) , [ , < #])/ sel=: 1 : 'x # [' quick=: 3 : 0 if. 1 >: #y do. y else. e=. y{~?#y (quick y <sel e),(y =sel e),quick y >sel e end. ) gaps =: [: }: 1 (1+3*])^:(> {:)^:a:~ # insert =: (I.~ {. ]) , [ , ] }.~ I.~ gapinss =: #@] {. ,@|:@(] insert//.~ #@] $ i.@[) shell =: [: ; gapinss &.>/@(< ,~ ]&.>@gaps) builtin =: /:~       NB. characterization of the sorting algorithms.   sorts =: bubble`insertion`shell`quick`radix`builtin generators =: #&1`(i.@-)`(?.~) NB. data generators   round =: [: <. 1r2&+   ll =: (<_1 0)&{ NB. verb to extract lower left which holds ln data length lc =: (<_1 1)&{ NB. verb to fetch lower center which holds most recent time   NB. maximum_time characterize ln_start_size NB. characterize returns a rank 4 matrix with successive indexes for NB. algorithm, input arrangement, max number of tests in group, length time space characterize =: 4 : 0 max_time =. x start =. 1 3{.<:y for_sort. sorts do. for_generator. generators do. NB. limit time and paging prevention t =: }. (, (, [: ts '[email protected] ([email protected])' , ":@round@^)@>:@ll) ^: ((lc < max_time"_) *. ll < 17"_) ^:_ start if. generator -: {.generators do. g =. ,:t else. g =. g,t end. end. if. sort -: {.sorts do. s =. ,:g else. s =. s,g end. end. )   NB. character cell graphics   NB. From j phrases 10E. Approximation d3=: 1&,.@[ %.~ ] NB. a and b such that y is approx. a + b*x   NB. domain and range 0 to 14. D=:14   plot =: 1 : '(=/ round@(u&.(*&(D%<:y))))i.y' NB. function plot size points =: 4 : '1(<"1|:|.round y*D%~<:x)}0$~2#x' NB. size points x,:y   show =: [: |. [: '0'&~:@{:} ' ' ,: ":   plt =: 3 : 0 30 plt y NB. default size 30 : n =. >:i.-# experiments =. <@(#~"1 (0&<)@{.)"2 y pts =. n +./ .*x&points@>experiments coef =. d3/@>experiments (_*pts) + n +./ .*1 0 2|:coef&(p."1) plot x )  
http://rosettacode.org/wiki/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) The interpreter algorithm is relatively simple interp(x) if x == NULL return NULL elif x.node_type == Integer return x.value converted to an integer elif x.node_type == Ident return the current value of variable x.value elif x.node_type == String return x.value elif x.node_type == Assign globals[x.left.value] = interp(x.right) return NULL elif x.node_type is a binary operator return interp(x.left) operator interp(x.right) elif x.node_type is a unary operator, return return operator interp(x.left) elif x.node_type == If if (interp(x.left)) then interp(x.right.left) else interp(x.right.right) return NULL elif x.node_type == While while (interp(x.left)) do interp(x.right) return NULL elif x.node_type == Prtc print interp(x.left) as a character, no newline return NULL elif x.node_type == Prti print interp(x.left) as an integer, no newline return NULL elif x.node_type == Prts print interp(x.left) as a string, respecting newlines ("\n") return NULL elif x.node_type == Sequence interp(x.left) interp(x.right) return NULL else error("unknown node type") Notes: Because of the simple nature of our tiny language, Semantic analysis is not needed. Your interpreter should use C like division semantics, for both division and modulus. For division of positive operands, only the non-fractional portion of the result should be returned. In other words, the result should be truncated towards 0. This means, for instance, that 3 / 2 should result in 1. For division when one of the operands is negative, the result should be truncated towards 0. This means, for instance, that 3 / -2 should result in -1. Test program prime.t lex <prime.t | parse | interp /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 101 is prime Total primes found: 26 Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Syntax Analyzer task Code Generator task Virtual Machine Interpreter task
#Scala
Scala
  package xyz.hyperreal.rosettacodeCompiler   import scala.collection.mutable import scala.io.Source   object ASTInterpreter {   def fromStdin = fromSource(Source.stdin)   def fromString(src: String) = fromSource(Source.fromString(src))   def fromSource(s: Source) = { val lines = s.getLines   def load: Node = if (!lines.hasNext) TerminalNode else lines.next.split(" +", 2) match { case Array(name, value) => LeafNode(name, value) case Array(";") => TerminalNode case Array(name) => BranchNode(name, load, load) }   val vars = new mutable.HashMap[String, Any]   def interpInt(n: Node) = interp(n).asInstanceOf[Int]   def interpBoolean(n: Node) = interp(n).asInstanceOf[Boolean]   def interp(n: Node): Any = n match { case TerminalNode => null case LeafNode("Identifier", name) => vars get name match { case None => vars(name) = 0 0 case Some(v) => v } case LeafNode("Integer", "'\\n'") => '\n'.toInt case LeafNode("Integer", "'\\\\'") => '\\'.toInt case LeafNode("Integer", value: String) if value startsWith "'" => value(1).toInt case LeafNode("Integer", value: String) => value.toInt case LeafNode("String", value: String) => unescape(value.substring(1, value.length - 1)) case BranchNode("Assign", LeafNode(_, name), exp) => vars(name) = interp(exp) case BranchNode("Sequence", l, r) => interp(l); interp(r) case BranchNode("Prts" | "Prti", a, _) => print(interp(a)) case BranchNode("Prtc", a, _) => print(interpInt(a).toChar) case BranchNode("Add", l, r) => interpInt(l) + interpInt(r) case BranchNode("Subtract", l, r) => interpInt(l) - interpInt(r) case BranchNode("Multiply", l, r) => interpInt(l) * interpInt(r) case BranchNode("Divide", l, r) => interpInt(l) / interpInt(r) case BranchNode("Mod", l, r) => interpInt(l) % interpInt(r) case BranchNode("Negate", a, _) => -interpInt(a) case BranchNode("Less", l, r) => interpInt(l) < interpInt(r) case BranchNode("LessEqual", l, r) => interpInt(l) <= interpInt(r) case BranchNode("Greater", l, r) => interpInt(l) > interpInt(r) case BranchNode("GreaterEqual", l, r) => interpInt(l) >= interpInt(r) case BranchNode("Equal", l, r) => interpInt(l) == interpInt(r) case BranchNode("NotEqual", l, r) => interpInt(l) != interpInt(r) case BranchNode("And", l, r) => interpBoolean(l) && interpBoolean(r) case BranchNode("Or", l, r) => interpBoolean(l) || interpBoolean(r) case BranchNode("Not", a, _) => !interpBoolean(a) case BranchNode("While", l, r) => while (interpBoolean(l)) interp(r) case BranchNode("If", cond, BranchNode("If", yes, no)) => if (interpBoolean(cond)) interp(yes) else interp(no) }   interp(load) }   abstract class Node case class BranchNode(name: String, left: Node, right: Node) extends Node case class LeafNode(name: String, value: String) extends Node case object TerminalNode extends Node   }  
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#FutureBasic
FutureBasic
local fn MyArraySortFunction( obj1 as CFTypeRef, obj2 as CFTypeRef, context as ptr ) as NSComparisonResult NSComparisonResult result = NSOrderedDescending if len(obj1) >= len(obj2) then result = NSOrderedAscending end fn = result   void local fn DoIt CFStringRef string1 = @"abcd", string2 = @"abcdef", s   if len(string1) >= len(string2) print string1,len(string1) print string2,len(string2) else print string2,len(string2) print string1,len(string1) end if   print text ,,,,, 85   CFArrayRef strings = @[@"abcd",@"123456789",@"abcdef",@"1234567"] strings = fn ArraySortedArrayUsingFunction( strings, @fn MyArraySortFunction, NULL ) for s in strings print s,len(s) next end fn   window 1   fn DoIt   HandleEvents
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first. Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it. Extra credit Given more than two strings: list = ["abcd","123456789","abcdef","1234567"] Show the strings in descending length order. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Harbour
Harbour
    PROCEDURE Main() LOCAL s1 := "The long string" LOCAL s2 := "The short string" LOCAL a := { s1, s2 } LOCAL s3   ? s3 := "Here is how you can print the longer string first using Harbour language" ? ? "-------------------------------------------" PrintTheLongerFirst( a )   a := hb_ATokens( s3, " " ) ? "-------------------------------------------" PrintTheLongerFirst( a ) ? "-------------------------------------------" RETURN   FUNCTION PrintTheLongerFirst( a ) LOCAL n, tmp a := ASort( a,,, {|x,y| Len(x) > Len(y) } ) n:= Len( a[1] ) AEval( a, { |e| tmp := n-Len(e), Qout( e, Space(tmp) + ; hb_strFormat( "(length = %d chars)", Len(e) ) ) } ) RETURN NIL  
http://rosettacode.org/wiki/Compiler/syntax_analyzer
Compiler/syntax analyzer
A Syntax analyzer transforms a token stream (from the Lexical analyzer) into a Syntax tree, based on a grammar. Task[edit] Take the output from the Lexical analyzer task, and convert it to an Abstract Syntax Tree (AST), based on the grammar below. The output should be in a flattened format. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a parser module/library/class, it would be great if two versions of the solution are provided: One without the parser module, and one with. Grammar The simple programming language to be analyzed is more or less a (very tiny) subset of C. The formal grammar in Extended Backus-Naur Form (EBNF):   stmt_list = {stmt} ;   stmt = ';' | Identifier '=' expr ';' | 'while' paren_expr stmt | 'if' paren_expr stmt ['else' stmt] | 'print' '(' prt_list ')' ';' | 'putc' paren_expr ';' | '{' stmt_list '}'  ;   paren_expr = '(' expr ')' ;   prt_list = (string | expr) {',' (String | expr)} ;   expr = and_expr {'||' and_expr} ; and_expr = equality_expr {'&&' equality_expr} ; equality_expr = relational_expr [('==' | '!=') relational_expr] ; relational_expr = addition_expr [('<' | '<=' | '>' | '>=') addition_expr] ; addition_expr = multiplication_expr {('+' | '-') multiplication_expr} ; multiplication_expr = primary {('*' | '/' | '%') primary } ; primary = Identifier | Integer | '(' expr ')' | ('+' | '-' | '!') primary  ; The resulting AST should be formulated as a Binary Tree. Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions lex < while.t > while.lex Run one of the Syntax analyzer solutions parse < while.lex > while.ast The following table shows the input to lex, lex output, and the AST produced by the parser Input to lex Output from lex, input to parse Output from parse count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; } 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String "count is: " 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String "\n" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String "count is: " ; Prti Identifier count ; Prts String "\n" ; Assign Identifier count Add Identifier count Integer 1 Specifications List of node type names Identifier String Integer Sequence If Prtc Prts Prti While Assign Negate Not Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or In the text below, Null/Empty nodes are represented by ";". Non-terminal (internal) nodes For Operators, the following nodes should be created: Multiply Divide Mod Add Subtract Less LessEqual Greater GreaterEqual Equal NotEqual And Or For each of the above nodes, the left and right sub-nodes are the operands of the respective operation. In pseudo S-Expression format: (Operator expression expression) Negate, Not For these node types, the left node is the operand, and the right node is null. (Operator expression ;) Sequence - sub-nodes are either statements or Sequences. If - left node is the expression, the right node is If node, with it's left node being the if-true statement part, and the right node being the if-false (else) statement part. (If expression (If statement else-statement)) If there is not an else, the tree becomes: (If expression (If statement ;)) Prtc (Prtc (expression) ;) Prts (Prts (String "the string") ;) Prti (Prti (Integer 12345) ;) While - left node is the expression, the right node is the statement. (While expression statement) Assign - left node is the left-hand side of the assignment, the right node is the right-hand side of the assignment. (Assign Identifier expression) Terminal (leaf) nodes: Identifier: (Identifier ident_name) Integer: (Integer 12345) String: (String "Hello World!") ";": Empty node Some simple examples Sequences denote a list node; they are used to represent a list. semicolon's represent a null node, e.g., the end of this path. This simple program: a=11; Produces the following AST, encoded as a binary tree: Under each non-leaf node are two '|' lines. The first represents the left sub-node, the second represents the right sub-node: (1) Sequence (2) |-- ; (3) |-- Assign (4) |-- Identifier: a (5) |-- Integer: 11 In flattened form: (1) Sequence (2) ; (3) Assign (4) Identifier a (5) Integer 11 This program: a=11; b=22; c=33; Produces the following AST: ( 1) Sequence ( 2) |-- Sequence ( 3) | |-- Sequence ( 4) | | |-- ; ( 5) | | |-- Assign ( 6) | | |-- Identifier: a ( 7) | | |-- Integer: 11 ( 8) | |-- Assign ( 9) | |-- Identifier: b (10) | |-- Integer: 22 (11) |-- Assign (12) |-- Identifier: c (13) |-- Integer: 33 In flattened form: ( 1) Sequence ( 2) Sequence ( 3) Sequence ( 4) ; ( 5) Assign ( 6) Identifier a ( 7) Integer 11 ( 8) Assign ( 9) Identifier b (10) Integer 22 (11) Assign (12) Identifier c (13) Integer 33 Pseudo-code for the parser. Uses Precedence Climbing for expression parsing, and Recursive Descent for statement parsing. The AST is also built: def expr(p) if tok is "(" x = paren_expr() elif tok in ["-", "+", "!"] gettok() y = expr(precedence of operator) if operator was "+" x = y else x = make_node(operator, y) elif tok is an Identifier x = make_leaf(Identifier, variable name) gettok() elif tok is an Integer constant x = make_leaf(Integer, integer value) gettok() else error()   while tok is a binary operator and precedence of tok >= p save_tok = tok gettok() q = precedence of save_tok if save_tok is not right associative q += 1 x = make_node(Operator save_tok represents, x, expr(q))   return x   def paren_expr() expect("(") x = expr(0) expect(")") return x   def stmt() t = NULL if accept("if") e = paren_expr() s = stmt() t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL)) elif accept("putc") t = make_node(Prtc, paren_expr()) expect(";") elif accept("print") expect("(") repeat if tok is a string e = make_node(Prts, make_leaf(String, the string)) gettok() else e = make_node(Prti, expr(0))   t = make_node(Sequence, t, e) until not accept(",") expect(")") expect(";") elif tok is ";" gettok() elif tok is an Identifier v = make_leaf(Identifier, variable name) gettok() expect("=") t = make_node(Assign, v, expr(0)) expect(";") elif accept("while") e = paren_expr() t = make_node(While, e, stmt() elif accept("{") while tok not equal "}" and tok not equal end-of-file t = make_node(Sequence, t, stmt()) expect("}") elif tok is end-of-file pass else error() return t   def parse() t = NULL gettok() repeat t = make_node(Sequence, t, stmt()) until tok is end-of-file return t Once the AST is built, it should be output in a flattened format. This can be as simple as the following def prt_ast(t) if t == NULL print(";\n") else print(t.node_type) if t.node_type in [Identifier, Integer, String] # leaf node print the value of the Ident, Integer or String, "\n" else print("\n") prt_ast(t.left) prt_ast(t.right) If the AST is correctly built, loading it into a subsequent program should be as simple as def load_ast() line = readline() # Each line has at least one token line_list = tokenize the line, respecting double quotes   text = line_list[0] # first token is always the node type   if text == ";" # a terminal node return NULL   node_type = text # could convert to internal form if desired   # A line with two tokens is a leaf node # Leaf nodes are: Identifier, Integer, String # The 2nd token is the value if len(line_list) > 1 return make_leaf(node_type, line_list[1])   left = load_ast() right = load_ast() return make_node(node_type, left, right) Finally, the AST can also be tested by running it against one of the AST Interpreter solutions. Test program, assuming this is in a file called prime.t lex <prime.t | parse Input to lex Output from lex, input to parse Output from parse /* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n"); 4 1 Identifier count 4 7 Op_assign 4 9 Integer 1 4 10 Semicolon 5 1 Identifier n 5 3 Op_assign 5 5 Integer 1 5 6 Semicolon 6 1 Identifier limit 6 7 Op_assign 6 9 Integer 100 6 12 Semicolon 7 1 Keyword_while 7 7 LeftParen 7 8 Identifier n 7 10 Op_less 7 12 Identifier limit 7 17 RightParen 7 19 LeftBrace 8 5 Identifier k 8 6 Op_assign 8 7 Integer 3 8 8 Semicolon 9 5 Identifier p 9 6 Op_assign 9 7 Integer 1 9 8 Semicolon 10 5 Identifier n 10 6 Op_assign 10 7 Identifier n 10 8 Op_add 10 9 Integer 2 10 10 Semicolon 11 5 Keyword_while 11 11 LeftParen 11 12 LeftParen 11 13 Identifier k 11 14 Op_multiply 11 15 Identifier k 11 16 Op_lessequal 11 18 Identifier n 11 19 RightParen 11 21 Op_and 11 24 LeftParen 11 25 Identifier p 11 26 RightParen 11 27 RightParen 11 29 LeftBrace 12 9 Identifier p 12 10 Op_assign 12 11 Identifier n 12 12 Op_divide 12 13 Identifier k 12 14 Op_multiply 12 15 Identifier k 12 16 Op_notequal 12 18 Identifier n 12 19 Semicolon 13 9 Identifier k 13 10 Op_assign 13 11 Identifier k 13 12 Op_add 13 13 Integer 2 13 14 Semicolon 14 5 RightBrace 15 5 Keyword_if 15 8 LeftParen 15 9 Identifier p 15 10 RightParen 15 12 LeftBrace 16 9 Keyword_print 16 14 LeftParen 16 15 Identifier n 16 16 Comma 16 18 String " is prime\n" 16 31 RightParen 16 32 Semicolon 17 9 Identifier count 17 15 Op_assign 17 17 Identifier count 17 23 Op_add 17 25 Integer 1 17 26 Semicolon 18 5 RightBrace 19 1 RightBrace 20 1 Keyword_print 20 6 LeftParen 20 7 String "Total primes found: " 20 29 Comma 20 31 Identifier count 20 36 Comma 20 38 String "\n" 20 42 RightParen 20 43 Semicolon 21 1 End_of_input Sequence Sequence Sequence Sequence Sequence ; Assign Identifier count Integer 1 Assign Identifier n Integer 1 Assign Identifier limit Integer 100 While Less Identifier n Identifier limit Sequence Sequence Sequence Sequence Sequence ; Assign Identifier k Integer 3 Assign Identifier p Integer 1 Assign Identifier n Add Identifier n Integer 2 While And LessEqual Multiply Identifier k Identifier k Identifier n Identifier p Sequence Sequence ; Assign Identifier p NotEqual Multiply Divide Identifier n Identifier k Identifier k Identifier n Assign Identifier k Add Identifier k Integer 2 If Identifier p If Sequence Sequence ; Sequence Sequence ; Prti Identifier n ; Prts String " is prime\n" ; Assign Identifier count Add Identifier count Integer 1 ; Sequence Sequence Sequence ; Prts String "Total primes found: " ; Prti Identifier count ; Prts String "\n" ; Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Lexical Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#M2000_Interpreter
M2000 Interpreter
  Module syntax_analyzer(b$){ enum tokens { Op_add, Op_subtract, Op_not=5, Op_multiply=10, Op_divide, Op_mod, Op_negate, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_notequal, Op_and, Op_or, Op_assign=100, Keyword_if=110, Keyword_else, Keyword_while, Keyword_print, Keyword_putc, LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma, Identifier, Integer, String, End_of_input }   Inventory precedence=Op_multiply:=13, Op_divide:=13, Op_mod:=13, Op_add:=12, Op_subtract:=12 Append precedence, Op_negate:=14, Op_not:=14, Op_less:=10, Op_lessequal:=10, Op_greater:=10 Append precedence, Op_greaterequal:=10, Op_equal:=9, Op_notequal:=9, Op_assign:=-1, Op_and:=5 Append precedence, Op_or:=4   Inventory symbols=Op_multiply:="Multiply", Op_divide:="Divide", Op_mod:="Mod", Op_add:="Add" Append symbols, Op_negate:="Negate", Op_not:="Not", Op_less:="Less", Op_subtract:="Subtract" Append symbols, Op_lessequal:="LessEqual", Op_greater:="Greater", Op_greaterequal:="GreaterEqual" Append symbols, Op_equal:="Equal", Op_notequal:="NotEqual", Op_and:="And", Op_or:="Or"   def lineNo, ColumnNo, m, line$, a, lim, cur=-1 const nl$=chr$(13)+chr$(10), Ansi=3 Dim lex$() lex$()=piece$(b$,chr$(13)+chr$(10)) lim=dimension(lex$(),1)-1 op=End_of_input flush k=0 Try { push (,) ' Null getone(&op) repeat stmt(&op) shift 2 ' swap two top items push ("Sequence", array, array) k++ until op=End_of_Input } er$=error$ if er$<>"" then print er$ : flush: break Print "Ast" Document Output$ prt_ast() clipboard Output$ Save.Doc Output$, "parse.t", Ansi document parse$ Load.Doc parse$,"parse.t", Ansi Report parse$   sub prt_ast(t) if len(t)<1 then Output$=";"+nl$ else.if len(t)=3 then Output$=t#val$(0) +nl$ prt_ast(t#val(1)) : prt_ast(t#val(2)) else Output$=t#val$(0) +nl$ end if end sub sub expr(p) ' only a number local x=(,), prev=op if op>=Identifier then x=(line$,) getone(&op) else.if op=LeftParen then paren_exp() x=array else.if op<10 then getone(&op) expr(precedence(int(Op_negate))) read local y if prev=Op_add then x=y else if prev=Op_subtract then prev=Op_negate x=(symbols(prev), y,(,)) End if else {error "??? "+eval$(op)} end if local prec while exist(precedence, int(op)) prev=op : prec=eval(precedence) if prec<14 and prec>=p else exit getone(&op) expr(prec+1) ' all operators are left associative (use prec for right a.) x=(symbols(int(prev)), x, array) End While Push x end sub sub paren_exp() expected(LeftParen) getone(&op) expr(0) expected(RightParen) getone(&op) end sub sub stmt(&op) local t=(,) if op=Identifier then t=(line$) getone(&op) expected(Op_assign) getone(&op) expr(0) read local rightnode Push ("Assign",t,rightnode) expected(Semicolon) getone(&op) else.if op=Semicolon then getone(&op) Push (";",) else.if op=Keyword_print then getone(&op) expected(LeftParen) repeat getone(&op) if op=String then Push ("Prts",(line$,),(,)) getone(&op) else expr(0) Push ("Prti", array,(,)) end if t=("Sequence", t, array) until op<>Comma expected(RightParen) getone(&op) expected(Semicolon) getone(&op) push t else.if op=Keyword_while then getone(&op) paren_exp() stmt(&op) shift 2 Push ("While",array, array) else.if op=Keyword_if then getone(&op) paren_exp() stmt(&op) local s2=(,) if op=Keyword_else then getone(&op) stmt(&op) read s2 end if shift 2 Push ("If",array ,("If",array,s2)) else.if op=Keyword_putc then getone(&op) paren_exp() Push ("Prtc",array,t) expected(Semicolon) getone(&op) else.if op=LeftBrace then Brace() else error "Unkown Op" end if end sub Sub Brace() getone(&op) while op<>RightBrace and op<>End_of_input stmt(&op) t=("Sequence", t, array) end while expected(RightBrace) getone(&op) push t End Sub Sub expected(what) if not op=what then {Error "Expected "+eval$(what)+str$(LineNo)+","+Str$(ColumnNo)} End Sub sub getone(&op) op=End_of_input while cur<lim cur++ line$=trim$(lex$(cur)) if line$<>"" then exit end while if cur=lim then exit sub LineNo=Val(line$,"int",m) line$=mid$(line$, m) ColumnNo=Val(line$,"int",m) line$=trim$(mid$(line$, m)) Rem : Print LineNo, ColumnNo m=instr(line$," ") if m>0 then op=Eval("."+leftpart$(line$, " ")) else op=Eval("."+line$) end sub }   syntax_analyzer { 1 1 LeftBrace 5 5 Identifier left_edge 5 17 Op_assign 5 19 Op_subtract 5 20 Integer 420 5 23 Semicolon 6 5 Identifier right_edge 6 17 Op_assign 6 20 Integer 300 6 23 Semicolon 7 5 Identifier top_edge 7 17 Op_assign 7 20 Integer 300 7 23 Semicolon 8 5 Identifier bottom_edge 8 17 Op_assign 8 19 Op_subtract 8 20 Integer 300 8 23 Semicolon 9 5 Identifier x_step 9 17 Op_assign 9 22 Integer 7 9 23 Semicolon 10 5 Identifier y_step 10 17 Op_assign 10 21 Integer 15 10 23 Semicolon 12 5 Identifier max_iter 12 17 Op_assign 12 20 Integer 200 12 23 Semicolon 14 5 Identifier y0 14 8 Op_assign 14 10 Identifier top_edge 14 18 Semicolon 15 5 Keyword_while 15 11 LeftParen 15 12 Identifier y0 15 15 Op_greater 15 17 Identifier bottom_edge 15 28 RightParen 15 30 LeftBrace 16 9 Identifier x0 16 12 Op_assign 16 14 Identifier left_edge 16 23 Semicolon 17 9 Keyword_while 17 15 LeftParen 17 16 Identifier x0 17 19 Op_less 17 21 Identifier right_edge 17 31 RightParen 17 33 LeftBrace 18 13 Identifier y 18 15 Op_assign 18 17 Integer 0 18 18 Semicolon 19 13 Identifier x 19 15 Op_assign 19 17 Integer 0 19 18 Semicolon 20 13 Identifier the_char 20 22 Op_assign 20 24 Integer 32 20 27 Semicolon 21 13 Identifier i 21 15 Op_assign 21 17 Integer 0 21 18 Semicolon 22 13 Keyword_while 22 19 LeftParen 22 20 Identifier i 22 22 Op_less 22 24 Identifier max_iter 22 32 RightParen 22 34 LeftBrace 23 17 Identifier x_x 23 21 Op_assign 23 23 LeftParen 23 24 Identifier x 23 26 Op_multiply 23 28 Identifier x 23 29 RightParen 23 31 Op_divide 23 33 Integer 200 23 36 Semicolon 24 17 Identifier y_y 24 21 Op_assign 24 23 LeftParen 24 24 Identifier y 24 26 Op_multiply 24 28 Identifier y 24 29 RightParen 24 31 Op_divide 24 33 Integer 200 24 36 Semicolon 25 17 Keyword_if 25 20 LeftParen 25 21 Identifier x_x 25 25 Op_add 25 27 Identifier y_y 25 31 Op_greater 25 33 Integer 800 25 37 RightParen 25 39 LeftBrace 26 21 Identifier the_char 26 30 Op_assign 26 32 Integer 48 26 36 Op_add 26 38 Identifier i 26 39 Semicolon 27 21 Keyword_if 27 24 LeftParen 27 25 Identifier i 27 27 Op_greater 27 29 Integer 9 27 30 RightParen 27 32 LeftBrace 28 25 Identifier the_char 28 34 Op_assign 28 36 Integer 64 28 39 Semicolon 29 21 RightBrace 30 21 Identifier i 30 23 Op_assign 30 25 Identifier max_iter 30 33 Semicolon 31 17 RightBrace 32 17 Identifier y 32 19 Op_assign 32 21 Identifier x 32 23 Op_multiply 32 25 Identifier y 32 27 Op_divide 32 29 Integer 100 32 33 Op_add 32 35 Identifier y0 32 37 Semicolon 33 17 Identifier x 33 19 Op_assign 33 21 Identifier x_x 33 25 Op_subtract 33 27 Identifier y_y 33 31 Op_add 33 33 Identifier x0 33 35 Semicolon 34 17 Identifier i 34 19 Op_assign 34 21 Identifier i 34 23 Op_add 34 25 Integer 1 34 26 Semicolon 35 13 RightBrace 36 13 Keyword_putc 36 17 LeftParen 36 18 Identifier the_char 36 26 RightParen 36 27 Semicolon 37 13 Identifier x0 37 16 Op_assign 37 18 Identifier x0 37 21 Op_add 37 23 Identifier x_step 37 29 Semicolon 38 9 RightBrace 39 9 Keyword_putc 39 13 LeftParen 39 14 Integer 10 39 18 RightParen 39 19 Semicolon 40 9 Identifier y0 40 12 Op_assign 40 14 Identifier y0 40 17 Op_subtract 40 19 Identifier y_step 40 25 Semicolon 41 5 RightBrace 42 1 RightBrace 43 1 End_of_Input }  
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Clojure
Clojure
(defn moore-neighborhood [[x y]] (for [dx [-1 0 1] dy [-1 0 1] :when (not (= [dx dy] [0 0]))] [(+ x dx) (+ y dy)]))   (defn step [set-of-cells] (set (for [[cell count] (frequencies (mapcat moore-neighborhood set-of-cells)) :when (or (= 3 count) (and (= 2 count) (contains? set-of-cells cell)))] cell)))   (defn print-world ([set-of-cells] (print-world set-of-cells 10)) ([set-of-cells world-size] (let [r (range 0 (+ 1 world-size))] (pprint (for [y r] (apply str (for [x r] (if (set-of-cells [x y]) \# \.))))))))   (defn run-life [world-size num-steps set-of-cells] (loop [s num-steps cells set-of-cells] (print-world cells world-size) (when (< 0 s) (recur (- s 1) (step cells)))))   (def *blinker* #{[1 2] [2 2] [3 2]}) (def *glider* #{[1 0] [2 1] [0 2] [1 2] [2 2]})  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#PowerShell
PowerShell
  class Point { [Int]$a [Int]$b Point() { $this.a = 0 $this.b = 0 } Point([Int]$a, [Int]$b) { $this.a = $a $this.b = $b } [Int]add() {return $this.a + $this.b} [Int]mul() {return $this.a * $this.b} } $p1 = [Point]::new() $p2 = [Point]::new(3,2) $p1.add() $p2.mul()  
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Prolog
Prolog
point(10, 20).
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Zoomscript
Zoomscript
var a var b a = "World" b = a a = "Hello" print (a," ",b)
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET a$ = "Hello": REM a$ is the original string 20 LET b$ = a$: REM b$ is the copy
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> main: s = "string to copy" t = s {s,"\n",t}println exit(0)