Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions USE_OF_AI.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,14 @@ instructions. The AI helped me complete the IR structs; I wrote the rest by hand
| Unsigned `/`, `%` and `>>` (issue #1, pull request #35) | Me, reviewed by AI |
| Documentation, tests and deployment (README, website, release `v0.1.0`) | AI, at my request |

## November 7 and 8: issues #33, #4, #12 and #44

| Element | Who |
|---|---|
| Fixes of issues #4 and #12 | Me, reviewed and completed by AI |
| Several files (issue #44), samples, specs, branch script, documentation | AI, at my request |
| Commits, pull requests, explanations | AI |

## How I used the AI

Over the whole project, the AI was mostly used to **explain**: how a format, an encoding or an
Expand All @@ -248,3 +256,4 @@ without the AI. I still have to state their status:
- `b04d848` to `7b6e27c` (October 10 to 12), except `d198bad`: printing the AST, float literals,
sentence declarations, spans in the AST, samples, the start of the converter. The sessions are
no longer available.
- `b3c418f` and `6a814a5` (November 7): a declared variable set to zero (issue #33).
37 changes: 36 additions & 1 deletion docs/LANGUAGE_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Reference example (first slice):

- A function is a **verb**, declared in its dictionary form (`더하다`, `계산하다`, `먹다`).
The only exception to the all-Korean language: `main`, which is never called in the code.
A latin name is refused for any other function, except a `외부` one (the libc), which must
have one.
- **`다` marks functions**: every word ending in `다` is a verb, so a function. A variable or
parameter name cannot end in `다` (`바다`, "the sea"). This lets the compiler recognize a verb
without context, even when it is called before its declaration. A word in `다` not followed by
Expand Down Expand Up @@ -157,6 +159,8 @@ parameters.
- Each version has its own symbol in the object file (the name of the verb completed with the
types of the parameters), so that the linker tells them apart.
- `외부` functions cannot be overloaded: C has only one symbol per name.
- A function of another file is declared without a body and without `외부`: it gets the same
symbol as its definition there (see Several files).

### Examples

Expand Down Expand Up @@ -300,7 +304,8 @@ choice against the 받침 (`나을` → "받침이 없으니 '를'을 쓰세요"
| ★ | function | `TYPE을/를 반환하는 VERB다(TYPE name, …) { … }` | "VERB, which gives a TYPE"; without return: `VERB다(…) { … }` |
| | variable | `NAME은/는 VALUE이에요/예요` or `NAME은/는 TYPE이에요/예요` | with a value: deduced type (`0` → `정수`, `0.5` → `소수`); with a type: default value (zero of the type); `이에요` after a consonant, `예요` after a vowel; mutable by default |
| | constant | `고정된 NAME은/는 VALUE이에요/예요` | see Modifiers |
| ★ | external function (libc) | `외부 TYPE을/를 반환하는 name(TYPE name, …)` | latin name, no body; `…` for variadics: `외부 정수를 반환하는 printf(문자 주소 형식, …)` |
| | function of another file | `TYPE을/를 반환하는 VERB다(TYPE name, …)` | no body, no `외부`: defined in another file of the program, see Several files |
| ★ | external function (libc) | `외부 TYPE을/를 반환하는 name(TYPE name, …)` | latin name only (`외부` is for the libc), no body; `…` for variadics: `외부 정수를 반환하는 printf(문자 주소 형식, …)` |
| | structure | 구조 | |
| | export / public | | |

Expand All @@ -318,6 +323,36 @@ value, anything else a value. Default values: `0`, `0.0`, `거짓`, `빈 주소`
`고정된` with a type alone (`고정된 개수는 정수예요`) is an error: the constant would be zero
forever.

### Several files

A program can be split into several files, compiled together: `compiler -x lib.kr prog.kr`.
A file calls a function of another file through a declaration without a body and without
`외부`, a header:

```
// lib.kr
정수를 반환하는 더하다(정수 가, 정수 나) {
(가 + 나)를 반환해요.
}

// prog.kr
정수를 반환하는 더하다(정수 가, 정수 나) // defined in lib.kr

정수를 반환하는 main() {
결과는 정수예요.
40과 2를 더해서 결과에 넣어요.
결과를 반환해요. // 42
}
```

- `외부` is only for the libc: a latin name, the symbol as is (`printf`).
- A header has a name in `다` and the symbol of its definition (`더하다$int$int`), so its
parameter types must be the same as there.
- A single file must have its `main`. With several files, the linker reports a missing or a
second `main`.
- A header and the definition of the same function in one file: refused for now (the same
signature twice).

## Types

| | Concept | Word | Notes |
Expand Down
11 changes: 11 additions & 0 deletions specs/44-header-declaration/cases/header_and_definition.kr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// #44: a header and the definition of the same function in one file.

정수를 반환하는 더하다(정수 가, 정수 나)

정수를 반환하는 더하다(정수 가, 정수 나) {
(가 + 나)를 반환해요.
}

정수를 반환하는 main() {
0을 반환해요.
}
5 changes: 5 additions & 0 deletions specs/44-header-declaration/cases/lib.kr
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// #44: the library of prog.kr.

정수를 반환하는 더하다(정수 가, 정수 나) {
(가 + 나)를 반환해요.
}
9 changes: 9 additions & 0 deletions specs/44-header-declaration/cases/prog.kr
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// #44: 더하다 is defined in lib.kr, declared here without a body.

정수를 반환하는 더하다(정수 가, 정수 나)

정수를 반환하는 main() {
결과는 정수예요.
40과 2를 더해서 결과에 넣어요.
결과를 반환해요.
}
21 changes: 21 additions & 0 deletions specs/44-header-declaration/checks.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# #44: a function of another file, declared without a body.

links() { # links <exit code> <file.kr>...: compiled together with -x in a temporary folder, run
local expected="$1" dir code
shift
dir="$(mktemp -d)"
cp "$@" "$dir" || return 1
if ! (cd "$dir" && "$COMPILER" -x "${@##*/}" > /dev/null 2> err); then
echo "does not compile: $(tail -n 1 "$dir/err")"
rm -rf "$dir"
return 1
fi
"$dir/a.out" > /dev/null
code=$?
rm -rf "$dir"
[ "$code" -eq "$expected" ] || { echo "exit $code, expected $expected"; return 1; }
}

check "call_through_header" links 42 cases/lib.kr cases/prog.kr
check "header_and_definition" rejects cases/header_and_definition.kr "already defined"
manual "Decide whether a header and its definition may be in one file (refused for now)"
5 changes: 4 additions & 1 deletion src/converter/converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ pub struct Converter<'a> {
pub(super) functions: BTreeMap<String, usize>,
/// The IR being built: its strings and floats are filled while the functions are converted
pub(super) ir: ir::structs::Program,
/// The program is one file: it must have its `main`
pub(super) needs_main: bool,
}

impl<'a> Converter<'a> {
pub fn new(program: &'a Program) -> Self {
pub fn new(program: &'a Program, needs_main: bool) -> Self {
Self {
program,
needs_main,
functions: BTreeMap::new(),
ir: ir::structs::Program::default(),
}
Expand Down
2 changes: 1 addition & 1 deletion src/converter/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ fn takes_args(func: &Function, types: &[Type], values: &[Option<&Expr>]) -> bool

/// Whether the symbol of `func` has the types of its parameters: neither `외부` nor `main`
fn is_mangled(func: &Function) -> bool {
func.body.is_some() && func.name != "main"
!func.external && func.name != "main"
}

/// `op` cannot take operands of `types`
Expand Down
12 changes: 8 additions & 4 deletions src/converter/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ impl<'a> Converter<'a> {
pub fn get_all_functions(&mut self) -> Result<(), ConvertError> {
for (i, func) in self.program.functions.iter().enumerate() {
// `외부` and `main`: the libc symbols, their name as is for the linker
if func.body.is_none() || func.name == "main" {
// shortcut: no body means libc until a function of another file can be declared (#44)
if func.external || func.name == "main" {
// a function of another file is declared without 외부: 외부 is for the libc
if !func.name.is_ascii() {
let kind = ConvertErrorKind::ExternNotLatin(func.name.clone());
return Err(ConvertError::new(kind, func.span));
Expand Down Expand Up @@ -41,7 +41,7 @@ impl<'a> Converter<'a> {
&mut self,
func: &'a Function,
) -> Result<ir::structs::Function, ConvertError> {
// `외부`: nothing to check
// `외부` and a function of another file: nothing to check

let mut ir_func = ir::structs::Function::new(
func.mangled_name.clone(),
Expand Down Expand Up @@ -76,14 +76,18 @@ impl<'a> Converter<'a> {
Ok(ir_func)
}

/// The program has a `main` that returns a 정수
/// The program has a `main` that returns a 정수 (in one of its files, when it has several)
pub(super) fn check_main(&self) -> Result<(), ConvertError> {
let Some(main) = self
.program
.functions
.iter()
.find(|func| func.name == "main")
else {
// shortcut: in several files, gcc reports a missing or a second main at link time
if !self.needs_main {
return Ok(());
}
return Err(ConvertError::new(ConvertErrorKind::NoMain, Span::new(0, 0)));
};
if !matches!(main.return_type, Some(Type::Int { .. })) {
Expand Down
11 changes: 7 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@ fn compile(args: &Args, path: &str, main_parser: &Parser) -> Result<String, Box<
format!("{}:{line}:{col}: {err}", path)
})?;
print!("{ast}");
let ir = Converter::new(&ast).convert().map_err(|err| {
let (line, col) = err.span.line_col(&source);
format!("{}:{line}:{col}: {err}", path)
})?;
// in several files, only one has the main
let ir = Converter::new(&ast, args.paths.len() == 1)
.convert()
.map_err(|err| {
let (line, col) = err.span.line_col(&source);
format!("{}:{line}:{col}: {err}", path)
})?;
print!("{ir}");
let object = Path::new(path)
.with_extension("o")
Expand Down
7 changes: 7 additions & 0 deletions src/parser/cfg/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ pub const RULES: &[ParserProduction] = &[
NTerm(Block),
),
rule!(Function => term!(Verb::Da), NTerm(Block)),
// without a body: a function of another file, defined there
rule!(Function =>
NTerm(FunctionHead),
term!(Punctuation::LParen),
NTerm(Parameters),
term!(Punctuation::RParen),
),
rule!(ExternFunction =>
term!(Keyword::Extern),
NTerm(FunctionHead),
Expand Down
2 changes: 1 addition & 1 deletion src/parser/postparser/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl fmt::Display for Program {
/// `fn 더하다(int 가, int 나) -> int { … }`, `extern fn printf(char& 형식, ...) -> int`
impl fmt::Display for Function {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.body.is_none() {
if self.external {
write!(f, "extern ")?;
}
let mut params: Vec<String> = self.params.iter().map(Param::to_string).collect();
Expand Down
14 changes: 10 additions & 4 deletions src/parser/postparser/postparser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ fn function(node: &TreeNode) -> Result<Function, PostParseError> {
let [inner] = branch(node).1 else {
unreachable!()
};
let (head, params, body) = match branch(inner) {
let (head, params, body, external) = match branch(inner) {
// Function → VERB-고 TypeSpec 를 반환 Block
(NTerm::Function, [name @ TreeNode::Leaf(_), return_type, _, _, body]) => {
return Ok(Function {
Expand All @@ -110,6 +110,7 @@ fn function(node: &TreeNode) -> Result<Function, PostParseError> {
params: Vec::new(),
variadic: false,
body: Some(block(body)?),
external: false,
});
}
// Function → VERB-다 Block
Expand All @@ -122,12 +123,15 @@ fn function(node: &TreeNode) -> Result<Function, PostParseError> {
params: Vec::new(),
variadic: false,
body: Some(block(body)?),
external: false,
});
}
// Function → FunctionHead ( Parameters ) Block
(NTerm::Function, [head, _, params, _, body]) => (head, params, Some(block(body)?)),
(NTerm::Function, [head, _, params, _, body]) => (head, params, Some(block(body)?), false),
// Function → FunctionHead ( Parameters ): a function of another file
(NTerm::Function, [head, _, params, _]) => (head, params, None, false),
// ExternFunction → 외부 FunctionHead ( Parameters )
(NTerm::ExternFunction, [_, head, _, params, _]) => (head, params, None),
(NTerm::ExternFunction, [_, head, _, params, _]) => (head, params, None, true),
// Function → SentenceParameters 받아 VERB-고 TypeSpec 를 반환 Block
(NTerm::Function, [params, _, name, return_type, _, _, body]) => {
let params = sentence_parameters(params)?;
Expand All @@ -139,14 +143,15 @@ fn function(node: &TreeNode) -> Result<Function, PostParseError> {
params,
variadic: false,
body: Some(block(body)?),
external: false,
});
}
_ => unreachable!(),
};
let (name, name_span, return_type) = function_head(head)?;
let (params, variadic) = parameters(params)?;
// `외부` and `main`: the libc symbols, their name as is for the linker
let is_libc = body.is_none() || name == "main";
let is_libc = external || name == "main";
Ok(Function {
name: name.clone(),
mangled_name: mangle_name(name, &params, variadic, is_libc),
Expand All @@ -155,6 +160,7 @@ fn function(node: &TreeNode) -> Result<Function, PostParseError> {
params,
variadic,
body,
external,
})
}

Expand Down
4 changes: 3 additions & 1 deletion src/parser/postparser/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ pub struct Function {
pub params: Vec<Param>,
/// `, …` after the last parameter: any number of arguments (`printf`)
pub variadic: bool,
/// `None` for `외부`: declared here, defined elsewhere (libc)
/// `None` without a body: declared here, defined elsewhere (the libc, or another file)
pub body: Option<Vec<Statement>>,
/// `외부`: a libc function, whose symbol is its name as is
pub external: bool,
}

/// `정수 가`
Expand Down
Loading