• Stars
    star
    300
  • Rank 133,764 (Top 3 %)
  • Language
  • Created over 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

👻 A friendly little language for you and me.

Ghost Lang 👻

A friendly little language for you and me.

Motivation

Ghost is the language I wish we had.

There are so many newer programming languages that have brilliant ideas inside them, but I think they have failed to make them feel familiar to programmers.

Ghost steals as much of its design as possible from other programming languages. If someone else did it really well, why do it any differently? As such most of Ghost won't feel new. If you've used some of these languages before you will probably recognize features of Ghost.

There is no compiler or any tools for Ghost right now, I hope to someday work on some. But for now, this is just an exercise in programming language design.

Syntax

Ghost's syntax should feel light. There are no semicons, comments are a single character (#), syntax avoid too many characters.

But it also avoids having "optional" syntax like optional parenthesis or curly braces. A lot of this encourages a more "vertical" coding style.

Places where syntax could go multiple different ways, I've just picked what seems to be most popular. That way it should feel familiar to lots of developers.

Comments

# inline comments only
# combine to make multiline

Declarations

let name = expression

Null

let missing = null

Booleans

let positive = true
let negative = false

Strings

let plain = "hello world"
let interpolated = "hello {target}"
let escapes = "hello \"world\""

let multiline =
  """
  The quick {color} fox           # comment
  {action} over the lazy dog     \# not comment
  """
let multilineWithNewlines =
  """
  This is the first line
  This is the second line\
  This is still the second line
  """
let multilineWithIndentation =
  """
  This is indented by 0 spaces.
    This is indented by 2 spaces.
      This is indented by 4 spaces.
  """

Numbers

let float = 4.14
let float32 = 4.14f
let decimal = 0.15d
let bigint = 9999i

let largeNumber = 98_521_391_124i

Regex

let regex = /^one|^two|^three|^orfour/i # equivalent to below
let regexMultiline = ///
  ^ one   |  # all whitespace
  ^ two   |  # and comments
  ^ three |  # will be ignored
  ^ or four  # to make it readable
///i

Ranges

let range = 0..3                   # 0,1,2
let rangeInclusive = 0...3         # 0,1,2,3
let rangeExpr = 0..num             # 0 to whatever `num` is
let reverseWithNegatives = 2..-3   # 2,1,0,-1,-2

Properties

let property1 = .name # properties are global
let property2 = .name # both of these are equal

Lists

let list = [1, 2, 3]
let trailingCommas = [
  1,
  2,
  3,
]

let combineList = [1, ..list, 3] # fast
let combineIter = [1, ...iter, 3] # slow

let getterIndex = list[3]
let getterRange = list[0..3]

Arrays

let array = Array [1, 2, 3]
let trailingCommas = Array [
  1,
  2,
  3,
]

let getterIndex = array[3]
let getterIndexNegative = array[-3]
let getterRange = array[0..3]

Sets

let set = Set [
  "one",
  "two",
  "three",
]

Records

let three = .three

let record = [
  one = 1,
  two = 2,
  [three] = 3,
}

let one = record.one
let two = record[.two]
let three = record[three]

let newRecord = {
  one = "default",
  ...record,
  three = "new value",
}

Maps

let map = Map {
  "key1" = "value1",
  "key2" = "value2",
  3.1415 = "π"
}

Operators

# Arithmetic
let addition = a + b
let subtraction = a - b
let division = a / b
let multiplication = a * b
let remainder = a % b
let exponentiation = a ** b
let negation = -a

# Bitwise
let and = a & b
let or = a | b
let xor = a ^ b
let not = ~a
let leftShift = a << b
let signPropRightShift = a >> b
let zeroFillRightShift = a >>> b

# Comparison
let equality = a == b
let referentialEquality = a === b

let lessThan = a < b
let lessThan2 = a < b < c # equivalent to `a < b && b < c`, except `b` is only evaluated once
let lte = a <= b
let lte2 = a <= b <= c
let lessThan3 = a <= b < c

let greaterThan = a > b
let greaterThan2 = a > b > c
let gte = a >= b
let gte2 = a >= b >= c
let greaterThan3 = a >= b > c

# Logical
let and = expr && expr
let or = expr || expr
let not = !expr

# Grouping
let either = (a && b) || (c && d)

If-Else

if (condition) { doSomethingIfTruthy() }

if (condition) {
  doSomethingIfTruthy()
} else {
  doSomethingElse()
}

if (condition) {
  doSomethingIfTruthy()
} else if (condition2) {
  doSomethingElseIf2Truthy()
} else {
  doSomethingElse()
}

let result = if (n == 0) {
  "none"
} else if (n == 1) {
  "one"
} else {
  "many"
}

Destructuring

let [one, two, ...rest] = [1, 2, 3, 4]
# one = 1
# two = 2
# rest = [3, 4]

let [one, two, ...rest] = Array [1, 2, 3, 4]
# one = 1
# two = 2
# rest = [|3, 4|]

let {one, two, ...rest} = {one = 1, two = 2, three = 3, four = 4}
# one = 1
# two = 2
# rest = {three = 3, four = 4}

let {one as uno, two as dos, ...rest as resto} = {one = 1, two = 2, three = 3, four = 4}
# uno = 1
# dos = 2
# resto = {three = 3, four = 4}

Is

value is any
value is true # assert any static type
value is false
value is Number
value is Number.Float # return true or false if it matches
value is { prop: any }
value is { prop: Number }

Match

let result = match (value) {
  is true { "true" }
  is false { "false" }
  else { "other" }
}

Throw

throw Error("message")
throw Error("message", reason)

Try-Catch-Finally

let result = try {
  doSomething()
} catch (err is SpecialError) {
  doSomethingSpecial()
} catch (err) {
  doSomethingElse()
} finally {
  doSomethingAlways()
}

Effects

let doSomething = fn () {
  let myResult = effect "myEffect"
}

let result = try {
  doSomething()
} catch (myEffect is "myEffect") {
  resume "myResult"
}
let inner = fn () {
  log("inner start")
  let result = effect "myEffect"
  log("inner end", result)
  result
}

let outer = fn () {
  log("outer start")
  let result = inner()
  log("outer end", result)
  result
}

let finalResult = try {
  log("try start")
  let result = outer()
  log("try end", result)
  result
} catch (effect is "myEffect") {
  log("catch start", effect)
  let result = resume "myEffectHandlerResult"
  log("catch end", result)
}

# log: try start
# log: outer start
# log: inner start
# log: catch start "myEffect"
# log: inner end "myEffectHandlerResult"
# log: outer end "myEffectHandlerResult"
# log: try end "myEffectHandlerResult"
# log: catch end "myEffectHandlerResult"

finalResult == "myEffectHandlerResult"

For-As

for (iterable as item) {
  if (item.shouldBeSkipped) { continue }
  if (item.shouldEndTheLoop) { break }
  doSomething()
}

While

while (condition) {
  onlyRunsIfConditionIsTrue()
  repeatsAsLongAsItRemainsTrue()
}

Do-While

do {
  runsOnceImmediatelyRegardlessIfConditionIsTrue()
  repeatsAsLongAsItRemainsTrue()
} while (condition)

Loop

loop {
  if (condition1) { break }
  if (condition2) { continue }
  doSomethingInfinitelyUntilBreak()
}

Functions

let add = fn (a, b) { a + b }
let add = fn (a, b) {
  let addend = a
  let augend = b
  a + b
}

let result = add(400, 20)

Named Params

let divide = fn (dividend, divisor) {
  dividend / divisor
}

# All of these are equivalent:
divide(400, 20)
divide(dividend: 400, divisor: 20)
divide(divisor: 20, dividend: 400)
divide(dividend: 400, 20)
divide(400, divisor: 20)
divide(divisor: 20, 400)

# Compiler Errors: Cannot pass multiple values to the same parameter
divide(dividend: 20, dividend: 400)
divide(20, dividend: 400)

Iterable Functions

let doubles = fn (range) iter {
  for (range as index) {
    yield index * 2
  }
}

Do

let value = do {
  let a = 42
  let b = 10
  a * b
}

Pipeline

let results =
  |> books
  |> Iter.filter(^^, fn (book) { book.popularity > 0.8 })
  |> Iter.map(^^, fn (book) { Http.request(.get, book.url) })

# Equivalent code without pipelines:
let filtered = Iter.filter(books, fn (book) { book.popularity > 0.8 })
let results = Iter.map(filtered, fn (book) { Http.request(.get, book.url) })

Use

let append = fn (fileName, buffer) {
  let file = use File.open(fileName)
  File.append(file, buffer)
}

# Effectively:
let append = fn (fileName, buffer) {
  let file = File.open(fileName)
  try {
    let result = File.append(file, buffer)
  } finally {
    if (file) {
      file.dispose()
    }
  }
  result
}
let append = fn (fileName, buffer) {
  let file = use File.open(fileName)
  File.append(file, buffer)
  file.dispose() # manually call
}

Junk

let _ = "ignore me"
let [_, _, three] = [1, 2, 3]
let {a as _, b as _, ...rest as _} = { a = 1, b = 2, c = 3, d = 4 }

doSomething(fn (_, _, value) {
  value
})

log(_)
# SyntaxError: "Junk" bindings (_) are not valid
# identifiers and cannot be referenced. Give your
# binding a name instead.

Elements (GSX)

let MyComponent = fn (props) {
  let {prop, items} = props

  <OtherComponent { prop, bar: true }>
    let target = "world"
    <.h1>"hello {target}"</.h1>
    <.ul>
      for (items as item) {
        <.li { key: item.id }>item.name</.li>
      }
    </.ul>
  </OtherComponent>
}

Blocks

let fn = fn () {
  # block
}

for (iter as item) {
  # block
}

if (cond) {
  # block
} else if (cond) {
  # block
} else {
  # block
}

try {
  # block
} catch (err) {
  # block
} finally {
  # block
}

Block Scoping

let a = 1
if (cond) {
  let a = 2
  let b = 3
  log(a) # > 2
}
log(a) # > 1
log(b) # Error! There's no variable named "b" in this scope!

Imports

import Time
Time.Instant()

import Time as MyTime
MyTime.Instant()

import Math as { cos, PI }
cos(PI)

import ./utils/currency
currency.convert(42, .usd, .aud)

import ../lib/utils/i18n as { t }
t("Hello $1", "World")

Exports

export let add = fn (a, b) { a + b }
export let PI = 3.14

Type Syntax

Type Alias

type MyType = type

Basic Types

type MyType = any
type MyType = null
type MyType = Boolean
type MyType = true
type MyType = false
type MyType = String
type MyType = "string"
type MyType = Number
type MyType = Number.Float
type MyType = Regex
type MyType = Range
type MyType = Property
type MyType = .property
type MyType = List<String>
type MyType = Array<Boolean>
type MyType = Map<Number, Regex>
type MyType = Set<Range>
type MyType = Iter<String>

Record Types

type MyType = { prop: String }
type MyType = { prop?: String }
type MyType = { ...OtherRecordType }

Optional Types

type MyType = Boolean?
type MyType = Boolean | null # same

Function Types

type MyType = fn (param: String): Number
type MyType = fn (param: String): Iter<Number>       # fn () iter {}

Generics

type MyType<T> = Array<T>
type MyType = fn <T> (param: T): T

Unions

type MyType = String | Boolean | Range
type MyType =
  | String
  | Boolean
  | Range

Types in Syntax

Variables

let value: Boolean = true
let value: Boolean | String = "cool"

Functions

let fn = fn (param1: String, param2: Number) {
  # ...
}

let fn = fn (...rest: Array<String>) {
  # ...
}

let fn = fn (): String {
  "nice"
}

let fn = fn (): Iter<String> iter {
  yield "good"
}

More Repositories

1

the-super-tiny-compiler

⛄ Possibly the smallest compiler ever
JavaScript
25,786
star
2

react-loadable

⏳ A higher order component for loading components with promises.
JavaScript
16,596
star
3

babel-handbook

📘 A guided handbook on how to use Babel and how to create plugins for Babel.
11,881
star
4

itsy-bitsy-data-structures

🏰 All the things you didn't know you wanted to know about data structures
JavaScript
8,574
star
5

unstated

State so simple, it goes without saying
JavaScript
7,821
star
6

spectacle-code-slide

🤘 Present code with style
JavaScript
4,170
star
7

unstated-next

200 bytes to never think about React state management libraries ever again
TypeScript
4,092
star
8

tinykeys

A tiny (~400 B) & modern library for keybindings.
HTML
3,362
star
9

babel-react-optimize

🚀 A Babel preset and plugins for optimizing React code.
JavaScript
1,680
star
10

tailwindcss-animate

A Tailwind CSS plugin for creating beautiful animations
JavaScript
1,084
star
11

glow

Make your Flow errors GLOW
JavaScript
699
star
12

create-react-context

Polyfill for the proposed React context API
JavaScript
695
star
13

json-parser-in-typescript-very-bad-idea-please-dont-use

JSON Parser written entirely in TypeScript's type system
TypeScript
424
star
14

react-gridlist

A virtual-scrolling GridList component based on CSS Grids
TypeScript
421
star
15

favorite-software

🌟 Best software for developers and power users.
355
star
16

marionette-wires

:shipit: An opinionated example application built with Marionette.js.
JavaScript
325
star
17

pretty-format

✨ Stringify any JavaScript value
304
star
18

documentation-handbook

How to write high-quality friendly documentation that people want to read.
268
star
19

roast-my-deps

Your dependencies are bad and you should feel bad
JavaScript
265
star
20

bey

Simple immutable state for React using Immer
JavaScript
260
star
21

tickedoff

Tiny library (<200B gzip) for deferring something by a "tick"
JavaScript
217
star
22

react-jeff

A Good Form Library
TypeScript
213
star
23

react-performance-observer

Get performance measurements from React Fiber
JavaScript
210
star
24

gender-regex

Regex to test for valid genders
JavaScript
193
star
25

anti-fascist-mit-license

MIT license with additional text to prohibit use by fascists
187
star
26

purposefile

Make sure every file in your repo is exactly where it should be
TypeScript
168
star
27

react-loadable-example

Example project for React Loadable
JavaScript
149
star
28

bootcamp

👢 Jasmine-style BDD testing written in Sass for Sass.
CSS
141
star
29

write-files-atomic

Write many files atomically
JavaScript
124
star
30

sarcastic

Cast unknown values to typed values
JavaScript
98
star
31

ninos

Simple stubbing/spying for AVA
JavaScript
96
star
32

repo-growth

Measure how fast your repo is growing using cloc
JavaScript
89
star
33

workspaces-run

Run tasks/scripts across Yarn/Lerna/Bolt/etc workspaces.
TypeScript
88
star
34

license

The MIT license (with personal exceptions)
86
star
35

scritch

A small CLI to help you write sharable scripts for your team
JavaScript
84
star
36

react-markers

Add markers to your React components for easy testing with actual DOM elements
JavaScript
80
star
37

assert-equal-jsx

assertEqualJSX
JavaScript
78
star
38

proposal-promise-prototype-inspect

Proposal for Promise.prototype.inspect
JavaScript
78
star
39

globby-cli

User-friendly glob matching CLI
JavaScript
76
star
40

spawndamnit

Take care of your spawn()
JavaScript
76
star
41

grob

grep, but in JavaScript... I've truly outdone myself.
JavaScript
72
star
42

react-required-if

React PropType to conditionally add `.isRequired` based on other props
JavaScript
71
star
43

havetheybeenpwned

Test if your user's password has been pwned using the haveibeenpwned.com API
JavaScript
69
star
44

react-prop-matrix

Render something using every possible combination of props
JavaScript
68
star
45

renderator

JavaScript
65
star
46

dark-mode-github-readme-logos

How to make logos in your README that support GitHub's new dark mode
64
star
47

reduxxx

Redux, explicit.
TypeScript
64
star
48

babel-plugin-react-pure-components

Optimize React code by making pure classes into functions
JavaScript
61
star
49

react-test-renderer

[DEPRECATED] A lightweight solution to testing fully-rendered React Components
JavaScript
58
star
50

fixturez

Easily create and maintain test fixtures in the file system
JavaScript
58
star
51

ballistic

🔨 Utility-Belt Library for Sass
CSS
56
star
52

enable-npm-2fa

A script for enabling 2FA on all of your npm packages
JavaScript
55
star
53

cirbuf

A tiny and fast circular buffer
TypeScript
53
star
54

VisibilityObserver

Experimental API for observing the visible box of an element
TypeScript
51
star
55

dependency-free

An experiment to unify/speed up CI/local development via small Docker containers
TypeScript
49
star
56

naw

Your very own containerized build system!
TypeScript
47
star
57

react-stylish

🎀 Make your React component style-able by all
JavaScript
47
star
58

tested-components

Browser integration testing utils for styled-components
JavaScript
41
star
59

jamie.build

the website
HTML
41
star
60

codeowners-enforcer

Enforce CODEOWNERS files on your repo
Rust
41
star
61

std-pkg

The Official package.json Standard™ for Npm® endorsed fields
JavaScript
41
star
62

babel-plugin-private-underscores

Make _classMembers 'private' using symbols
JavaScript
39
star
63

userscript-github-disable-turbolinks

A userscript to disable GitHub turbolinks to force full page navigations
JavaScript
39
star
64

git-workflow

Git workflow for teams
38
star
65

pride

👬 PrideJS logo
38
star
66

babel-plugin-import-inspector

Babel plugin to report dynamic imports with import-inspector with metadata about the import
JavaScript
38
star
67

revalid

Composable validators
JavaScript
37
star
68

ci-parallel-vars

Get CI environment variables for parallelizing builds
JavaScript
37
star
69

crowdin-sync

🌏 How to setup Crowdin to sync with GitHub
Ruby
37
star
70

incremental-dom-react-helper

Helper to make Google's incremental-dom library work with React's compile target today.
JavaScript
36
star
71

guarded-string

Prevent accidentally introducing XSS holes with the strings in your app
JavaScript
36
star
72

babel-plugin-hash-strings

Replace all instances of "@@strings like this" with hashes.
JavaScript
35
star
73

react-module-experiment

JavaScript
34
star
74

task-graph-runner

Run async tasks with dependencies
JavaScript
34
star
75

json-peek

Stringify JSON *just enough* to see what it is
JavaScript
33
star
76

babel-plugin-ken-wheeler

Code like you dope
JavaScript
33
star
77

how-to-build-a-compiler

How to build a compiler – THE TALK
HTML
33
star
78

js-memory-heap-profiling

JavaScript
32
star
79

backbone.service

A simple service class for Backbone.
JavaScript
31
star
80

dep-size-inspect

JavaScript
29
star
81

pffffff

pfffffffffffffffffffff whatever
JavaScript
28
star
82

shimiteer

Puppeteer API shim for other browsers using WebdriverIO
JavaScript
27
star
83

better-directory-sort

Improved sorting order for directory entities
JavaScript
27
star
84

isolated-core-demo

JavaScript
27
star
85

graph-sequencer

Sort items in a graph using a topological sort while resolving cycles with priority groups
JavaScript
27
star
86

import-inspector

Wrap dynamic imports with metadata about the import
JavaScript
26
star
87

backbone-routing

Simple router and route classes for Backbone.
JavaScript
26
star
88

flow-shut-up

Add inline Flow comments to make Flow shut up about errors
JavaScript
25
star
89

proposal-promise-settle

This repository is a work in progress and not seeking feedback yet.
JavaScript
22
star
90

tumblr-downloader

Download all your female-presenting nipples from Tumblr
JavaScript
22
star
91

backbone.storage

A simple storage class for Backbone Models and Collections.
JavaScript
22
star
92

parcel-rust-example

Example of using Rust code in Parcel
HTML
22
star
93

temperment

Get a random temporary file or directory path that will delete itself
JavaScript
22
star
94

is-mergeable

Check if a GitHub Pull Request is in a (most likely) mergeable state
JavaScript
22
star
95

gud

Create a 'gud nuff' (not cryptographically secure) globally unique id
JavaScript
21
star
96

min-indent

Get the shortest leading whitespace from lines in a string
JavaScript
20
star
97

babel-setup-react-transform

Example Babel project using babel-plugin-react-transform
JavaScript
20
star
98

codeowners-utils

Utilities for working with CODEOWNERS files
TypeScript
19
star
99

my-react

Ideas for React APIs
JavaScript
18
star
100

LibManUal

Shell
18
star