Carbon Coding Language: Google’s Experimental Successor to C++

On July 19th 2022, Google introduced Carbon Language. What exactly is Carbon, and what does it aim to achieve? Note that the Carbon coding language is experimental.

To understand Carbon, we first need to take a look at the language it’s attempting to augment. That is, C++. It remains the dominant programming language for performance critical software, and has been a stable foundation for massive codebases. However, improving C++ is extremely difficult. This is due to a few reasons:

  • Decades of technical debt
  • Prioritizing backwards compatibility over new features
  • C++, ideally, is about standardization rather than design

Carbon, as Google puts it, is okay with “exploring significant backwards incompatible changes”. This has pros for those wanting to work with a language developing with the mindset of “move fast and break things”.

Carbon promises a few things in their readme:

Carbon is fundamentally a successor language approach, rather than an attempt to incrementally evolve C++. It is designed around interoperability with C++ as well as large-scale adoption and migration for existing C++ codebases and developers. A successor language for C++ requires:

  • Performance matching C++, an essential property for our developers.
  • Seamless, bidirectional interoperability with C++, such that a library anywhere in an existing C++ stack can adopt Carbon without porting the rest.
  • A gentle learning curve with reasonable familiarity for C++ developers.
  • Comparable expressivity and support for existing software’s design and architecture.
  • Scalable migration, with some level of source-to-source translation for idiomatic C++ code.

Google wants Carbon to fill an analogous role for C++ in the future, much like TypeScript or Kotlin does for their respective languages.

JavaScript → TypeScript
Java → Kotlin
C++ → Carbon?

Talk is cheap, show me the code

Okay, so what does Carbon look like then?

First, let’s see how to calculate the area of a circle in C++.

// C++ Code
#include <math.h>
#include <iostream>
#include <span>
#include <vector>

struct Circle {
  float r;
};

void PrintTotalArea(std::span<Circle> circles){
  float area = 0;
  for (const Circle& c : circles) {
    area += M_PI * c.r * c.r;
  }
}

auto main(int argc, char** argv) -> {
  std::vector<Circle> circles = {{1.0}, {2.0}};
  // Converts 'vector' to 'span' implicitly
  PrintTotalArea(circles);
  return 0;
}
C++ coding example

Compared to Carbon:

// Carbon Code
package Geometry api;
import Math;

class Circle {
  var r: f32;
};

fn PrintTotalArea(circles: Slice(Circle)) {
  var area: f32 = 0;
  for (c: Circle in circles) {
    area += Math.Pi * c.r * c.r;
  }
}

fn Main() -> i32 {
  // Array like vector
  var circles: Array(Circle) = ({.r = 1.0}, {.r = 2.0});
  
  // Array to slice implicitly 
  PrintTotalArea(circles);
  return 0;
}
Carbon coding example

My initial thoughts are that the syntax looks mixed between C#, JavaScript, and C++. Prepending “var” before each variable seems redundant. Why not a type name followed by a declaration? One might argue that it leads to easy variable identification without memorization of variable types but that makes little sense as you put the type anyway. The way variables are initialized with “:” instead of =, reminds me of Javascript. Not sure if that’s a good thing, it looks less like C++ than I expected. Oddly, they chose “import” for the system packages it seems which is also shared with Python. I do like the shortening of function to fn. You could argue shorthand is the point because it’s cleaner and smaller, but again why is it defined as a function and then an ‘i32’? Seems redundant. unless they decided fn FunctionName() -> i32 is shorter than int FunctionName(). It could be their goal is simply to separate the syntax from other known languages enough to recognize at a glance. Maybe I’m missing something.

One neat feature they’ve shown is the interoperability between Carbon and C++. You can call C++ from Carbon and vice versa. You can rewrite or replace as little or as much of your libraries as you want without fear of breaking anything. Well, at least without breaking anything more than normal when dealing with C++.

// C++ code used in both Carbon and C++;
struct Circle ( float r; ); 
// Carbon exposing a function for C++:
package Geometry api; 
import Cpp library "circle.h";
import Math; 
fn PrintTotalArea(circles: Slice(Cpp.Circ/e)) {
    var area: f32 = 0;
    for (c: Cpp.Circle in circles) { 
        area += Math.Pi * c.r * c.r;
    } 
    Print("Total area: {0}", area); 
}
// C++ calling Carbon:
#include <vector>
auto main(int argc, char** argv) -> int { 
    std::vector<Circle> circles = {{1.0), (2.8)}}; 
    Geometry::PrintTotalArea(circles);
    return 0; 
}
C++ code used in both Carbon and C++

And better memory safety is also promised

Safety, and especially memory safety, remains a key challenge for C++ and something a successor language needs to address. Our initial priority and focus is on immediately addressing important, low-hanging fruit in the safety space:

  • Tracking uninitialized states better, increased enforcement of initialization, and systematically providing hardening against initialization bugs when desired.
  • Designing fundamental APIs and idioms to support dynamic bounds checks in debug and hardened builds.
  • Having a default debug build mode that is both cheaper and more comprehensive than existing C++ build modes even when combined with Address Sanitizer.

Time will tell if the language develops into a developer favorite or fades into obscurity like Dlang. What, you haven’t heard of D?


It helps me if you share this post

Published 2022-08-03 00:19:33

How to create a simple voice-activated assistant in C#.

This is really old. I will release another tutorial updating this eventually. Follow my blog to get an update when that happens. Thanks!

While this sounds advanced (and it can be), it’s not that hard to set up a very basic setup where a custom application runs in the background in C# by using the built in speech recognition libraries in Windows 10.

Taking this idea further, I personally have a “Jarvis” that runs on my computer, automating basically all of my common actions, including launching games, music, sleeping my computer, adjusting the volume, minimizing windows, controlling the lights, and (best of all), sending emails and messages. I recommend using an external API for speech recognition if you’re serious about building something similar, as Microsoft’s sucks. You can build your own, or attempt to use something like Google’s API.

Anyway, here’s some simple C# code that should get some ideas flowing.


using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Speech.Recognition;
using Process = System.Diagnostics.Process;
using System.Diagnostics;
namespace VoiceAssistant
{
class Program
{
#region Native Stuff
const int Hide = 0;
const int Show = 1;
[DllImport("Kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);
[DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);
#endregion
static SpeechRecognitionEngine speechRecognitionEngine;
static bool speechOn = true;
private static string clipboardText;
private static bool shouldLog = true;
private static readonly string[] commands =
{
"assistant mute",
"assistant open clipboard",
"assistant new tab",
"assistant work music",
"assistant new github",
"assistant sleep computer confirmation 101",
"assistant shut down computer confirmation 101",
"assistant open story",
"assistant open rocket league"
};
static void HideWindow()
{
//Hide window
IntPtr hWndConsole = GetConsoleWindow();
if (hWndConsole != IntPtr.Zero)
{
ShowWindow(hWndConsole, Hide);
shouldLog = false;
//ShowWindow(hWndConsole, Show);
}
}
static void Main(string[] args)
{
HideWindow();
//Console.WriteLine("[ASSISTANT AI INITIALIZED]");
CultureInfo cultureInfo = new CultureInfo("en-us");
speechRecognitionEngine = new SpeechRecognitionEngine(cultureInfo);
speechRecognitionEngine.SetInputToDefaultAudioDevice();
speechRecognitionEngine.SpeechRecognized += SpeechRecognition;
speechRecognitionEngine.SpeechDetected += SpeechDetected;
speechRecognitionEngine.SpeechHypothesized += SpeechHypothesized;
LoadCommands();
while (true)
{
Thread.Sleep(60000);
}
}
static void LoadCommands()
{
/*Grammar muteCommand = new Grammar(new GrammarBuilder(commands[0]));
Grammar browserOpenCopiedLink = new Grammar(new GrammarBuilder(commands[1]));
Grammar browserCopyLink = new Grammar(new GrammarBuilder(commands[2]));
speechRecognitionEngine.LoadGrammar(muteCommand);
speechRecognitionEngine.LoadGrammar(browserOpenCopiedLink);
speechRecognitionEngine.LoadGrammar(browserCopyLink);*/
foreach (string command in commands)
{
speechRecognitionEngine.LoadGrammarAsync(new Grammar(new GrammarBuilder(command)));
}
speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
Console.Beep(600, 200);
Console.Beep(600, 200);
}
static void SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
//Log(e.Result.Text);
}
static void SpeechDetected(object sender, SpeechDetectedEventArgs e)
{
//Log("Detected speech.");
}
static void SpeechRecognition(object sender, SpeechRecognizedEventArgs e)
{
string resultText = e.Result.Text.ToLower();
float confidence = e.Result.Confidence;
SemanticValue semantics = e.Result.Semantics;
Log("\nRecognized: " + resultText + " | Confidence:" + confidence);
if (confidence < 0.6)
{
Log("Not sure what if you said that. Not proceeding.", ConsoleColor.Red);
return;
}
if (resultText == commands[0])
{
speechOn = !speechOn;
Log("Speech on: " + speechOn);
if (speechOn)
{
Console.Beep(600, 200);
Console.Beep(600, 200);
}
else
{
Console.Beep(400, 400);
}
return;
}
if (!speechOn)
{
Log("AI is muted. Not doing any commands.");
Console.Beep(400, 200);
return;
}
if (resultText == commands[1]) //Open link on clipboard.
{
Thread clipboardThread = new Thread(param =>
{
if (Clipboard.ContainsText(TextDataFormat.Text))
{
clipboardText = Clipboard.GetText(TextDataFormat.Text);
}
});
clipboardThread.SetApartmentState(ApartmentState.STA);
clipboardThread.Start();
clipboardThread.Join();
Log(clipboardText);
Process.Start(clipboardText);
}
if (resultText == commands[2]) //Open browser
{
Process.Start("https://google.com");
}
if (resultText == commands[3]) //Open work music
{
Process.Start("https://youtu.be/Qku9aoUlTXA?list=PLESPkMaANzSj91tvYnQkKwgx41vkxp6hs");
}
if (resultText == commands[4]) //Open Github new repository
{
Process.Start("https://github.com/new");
}
if (resultText == commands[5]) //Sleep computer
{
SetSuspendState(false, true, true);
}
if (resultText == commands[6]) //Shutdown computer
{
Process.Start("shutdown", "/s /t 0");
}
if (resultText == commands[7]) //Open story
{
Process.Start("https://docs.new");
}
if (resultText == commands[9]) //Open Rocket League
{
Process.Start("C:\\Users\\USER\\Documents\\SteamLauncher\\RocketLeague.exe");
}
}
static void Log(string input, ConsoleColor color = ConsoleColor.White)
{
if (shouldLog)
{
Console.ForegroundColor = color;
Console.WriteLine(input);
Console.ResetColor();
}
}
}
}


It helps me if you share this post

Published 2019-05-22 18:10:00